blob: cd4023eeda2276d5a82d8dec5e5144981bbcc312 [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
John McCallb4190042009-11-04 23:02:40 +00001501/// Checks an initializer expression for use of uninitialized fields, such as
1502/// containing the field that is being initialized. Returns true if there is an
1503/// uninitialized field was used an updates the SourceLocation parameter; false
1504/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001505static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001506 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001507 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001508 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1509
Nick Lewycky43ad1822010-06-15 07:32:55 +00001510 if (isa<CallExpr>(S)) {
1511 // Do not descend into function calls or constructors, as the use
1512 // of an uninitialized field may be valid. One would have to inspect
1513 // the contents of the function/ctor to determine if it is safe or not.
1514 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1515 // may be safe, depending on what the function/ctor does.
1516 return false;
1517 }
1518 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1519 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001520
1521 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1522 // The member expression points to a static data member.
1523 assert(VD->isStaticDataMember() &&
1524 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001525 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001526 return false;
1527 }
1528
1529 if (isa<EnumConstantDecl>(RhsField)) {
1530 // The member expression points to an enum.
1531 return false;
1532 }
1533
John McCallb4190042009-11-04 23:02:40 +00001534 if (RhsField == LhsField) {
1535 // Initializing a field with itself. Throw a warning.
1536 // But wait; there are exceptions!
1537 // Exception #1: The field may not belong to this record.
1538 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001539 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001540 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1541 // Even though the field matches, it does not belong to this record.
1542 return false;
1543 }
1544 // None of the exceptions triggered; return true to indicate an
1545 // uninitialized field was used.
1546 *L = ME->getMemberLoc();
1547 return true;
1548 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001549 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001550 // sizeof/alignof doesn't reference contents, do not warn.
1551 return false;
1552 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1553 // address-of doesn't reference contents (the pointer may be dereferenced
1554 // in the same expression but it would be rare; and weird).
1555 if (UOE->getOpcode() == UO_AddrOf)
1556 return false;
John McCallb4190042009-11-04 23:02:40 +00001557 }
John McCall7502c1d2011-02-13 04:07:26 +00001558 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001559 if (!*it) {
1560 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001561 continue;
1562 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001563 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1564 return true;
John McCallb4190042009-11-04 23:02:40 +00001565 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001566 return false;
John McCallb4190042009-11-04 23:02:40 +00001567}
1568
John McCallf312b1e2010-08-26 23:41:50 +00001569MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001570Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001571 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001572 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001573 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001574 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1575 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1576 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001577 "Member must be a FieldDecl or IndirectFieldDecl");
1578
Douglas Gregor464b2f02010-11-05 22:21:31 +00001579 if (Member->isInvalidDecl())
1580 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001581
John McCallb4190042009-11-04 23:02:40 +00001582 // Diagnose value-uses of fields to initialize themselves, e.g.
1583 // foo(foo)
1584 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001585 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001586 for (unsigned i = 0; i < NumArgs; ++i) {
1587 SourceLocation L;
1588 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1589 // FIXME: Return true in the case when other fields are used before being
1590 // uninitialized. For example, let this field be the i'th field. When
1591 // initializing the i'th field, throw a warning if any of the >= i'th
1592 // fields are used, as they are not yet initialized.
1593 // Right now we are only handling the case where the i'th field uses
1594 // itself in its initializer.
1595 Diag(L, diag::warn_field_is_uninit);
1596 }
1597 }
1598
Eli Friedman59c04372009-07-29 19:44:27 +00001599 bool HasDependentArg = false;
1600 for (unsigned i = 0; i < NumArgs; i++)
1601 HasDependentArg |= Args[i]->isTypeDependent();
1602
Chandler Carruth894aed92010-12-06 09:23:57 +00001603 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001604 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001605 // Can't check initialization for a member of dependent type or when
1606 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001607 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001608 RParenLoc,
1609 Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001610
John McCallf85e1932011-06-15 23:02:42 +00001611 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00001612 } else {
1613 // Initialize the member.
1614 InitializedEntity MemberEntity =
1615 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1616 : InitializedEntity::InitializeMember(IndirectMember, 0);
1617 InitializationKind Kind =
1618 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001619
Chandler Carruth894aed92010-12-06 09:23:57 +00001620 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1621
1622 ExprResult MemberInit =
1623 InitSeq.Perform(*this, MemberEntity, Kind,
1624 MultiExprArg(*this, Args, NumArgs), 0);
1625 if (MemberInit.isInvalid())
1626 return true;
1627
1628 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1629
1630 // C++0x [class.base.init]p7:
1631 // The initialization of each base and member constitutes a
1632 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001633 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001634 if (MemberInit.isInvalid())
1635 return true;
1636
1637 // If we are in a dependent context, template instantiation will
1638 // perform this type-checking again. Just save the arguments that we
1639 // received in a ParenListExpr.
1640 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1641 // of the information that we have about the member
1642 // initializer. However, deconstructing the ASTs is a dicey process,
1643 // and this approach is far more likely to get the corner cases right.
1644 if (CurContext->isDependentContext())
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001645 Init = new (Context) ParenListExpr(
1646 Context, LParenLoc, Args, NumArgs, RParenLoc,
1647 Member->getType().getNonReferenceType());
Chandler Carruth894aed92010-12-06 09:23:57 +00001648 else
1649 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001650 }
1651
Chandler Carruth894aed92010-12-06 09:23:57 +00001652 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001653 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001654 IdLoc, LParenLoc, Init,
1655 RParenLoc);
1656 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001657 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001658 IdLoc, LParenLoc, Init,
1659 RParenLoc);
1660 }
Eli Friedman59c04372009-07-29 19:44:27 +00001661}
1662
John McCallf312b1e2010-08-26 23:41:50 +00001663MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001664Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1665 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001666 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001667 SourceLocation LParenLoc,
1668 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001669 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001670 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1671 if (!LangOpts.CPlusPlus0x)
1672 return Diag(Loc, diag::err_delegation_0x_only)
1673 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001674
Sean Hunt41717662011-02-26 19:13:13 +00001675 // Initialize the object.
1676 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1677 QualType(ClassDecl->getTypeForDecl(), 0));
1678 InitializationKind Kind =
1679 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1680
1681 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1682
1683 ExprResult DelegationInit =
1684 InitSeq.Perform(*this, DelegationEntity, Kind,
1685 MultiExprArg(*this, Args, NumArgs), 0);
1686 if (DelegationInit.isInvalid())
1687 return true;
1688
1689 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001690 CXXConstructorDecl *Constructor
1691 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001692 assert(Constructor && "Delegating constructor with no target?");
1693
1694 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1695
1696 // C++0x [class.base.init]p7:
1697 // The initialization of each base and member constitutes a
1698 // full-expression.
1699 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1700 if (DelegationInit.isInvalid())
1701 return true;
1702
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001703 assert(!CurContext->isDependentContext());
Sean Hunt41717662011-02-26 19:13:13 +00001704 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1705 DelegationInit.takeAs<Expr>(),
1706 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001707}
1708
1709MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001710Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001711 Expr **Args, unsigned NumArgs,
1712 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001713 CXXRecordDecl *ClassDecl,
1714 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001715 bool HasDependentArg = false;
1716 for (unsigned i = 0; i < NumArgs; i++)
1717 HasDependentArg |= Args[i]->isTypeDependent();
1718
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001719 SourceLocation BaseLoc
1720 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1721
1722 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1723 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1724 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1725
1726 // C++ [class.base.init]p2:
1727 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001728 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001729 // of that class, the mem-initializer is ill-formed. A
1730 // mem-initializer-list can initialize a base class using any
1731 // name that denotes that base class type.
1732 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1733
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001734 if (EllipsisLoc.isValid()) {
1735 // This is a pack expansion.
1736 if (!BaseType->containsUnexpandedParameterPack()) {
1737 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1738 << SourceRange(BaseLoc, RParenLoc);
1739
1740 EllipsisLoc = SourceLocation();
1741 }
1742 } else {
1743 // Check for any unexpanded parameter packs.
1744 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1745 return true;
1746
1747 for (unsigned I = 0; I != NumArgs; ++I)
1748 if (DiagnoseUnexpandedParameterPack(Args[I]))
1749 return true;
1750 }
1751
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001752 // Check for direct and virtual base classes.
1753 const CXXBaseSpecifier *DirectBaseSpec = 0;
1754 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1755 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001756 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1757 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001758 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1759 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001760
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001761 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1762 VirtualBaseSpec);
1763
1764 // C++ [base.class.init]p2:
1765 // Unless the mem-initializer-id names a nonstatic data member of the
1766 // constructor's class or a direct or virtual base of that class, the
1767 // mem-initializer is ill-formed.
1768 if (!DirectBaseSpec && !VirtualBaseSpec) {
1769 // If the class has any dependent bases, then it's possible that
1770 // one of those types will resolve to the same type as
1771 // BaseType. Therefore, just treat this as a dependent base
1772 // class initialization. FIXME: Should we try to check the
1773 // initialization anyway? It seems odd.
1774 if (ClassDecl->hasAnyDependentBases())
1775 Dependent = true;
1776 else
1777 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1778 << BaseType << Context.getTypeDeclType(ClassDecl)
1779 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1780 }
1781 }
1782
1783 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001784 // Can't check initialization for a base of dependent type or when
1785 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001786 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001787 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001788 RParenLoc, BaseType));
Eli Friedman59c04372009-07-29 19:44:27 +00001789
John McCallf85e1932011-06-15 23:02:42 +00001790 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Sean Huntcbb67482011-01-08 20:30:50 +00001792 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001793 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001794 LParenLoc,
1795 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001796 RParenLoc,
1797 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001798 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001799
1800 // C++ [base.class.init]p2:
1801 // If a mem-initializer-id is ambiguous because it designates both
1802 // a direct non-virtual base class and an inherited virtual base
1803 // class, the mem-initializer is ill-formed.
1804 if (DirectBaseSpec && VirtualBaseSpec)
1805 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001806 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001807
1808 CXXBaseSpecifier *BaseSpec
1809 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1810 if (!BaseSpec)
1811 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1812
1813 // Initialize the base.
1814 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001815 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001816 InitializationKind Kind =
1817 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1818
1819 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1820
John McCall60d7b3a2010-08-24 06:29:42 +00001821 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001822 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001823 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001824 if (BaseInit.isInvalid())
1825 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001826
1827 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001828
1829 // C++0x [class.base.init]p7:
1830 // The initialization of each base and member constitutes a
1831 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001832 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001833 if (BaseInit.isInvalid())
1834 return true;
1835
1836 // If we are in a dependent context, template instantiation will
1837 // perform this type-checking again. Just save the arguments that we
1838 // received in a ParenListExpr.
1839 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1840 // of the information that we have about the base
1841 // initializer. However, deconstructing the ASTs is a dicey process,
1842 // and this approach is far more likely to get the corner cases right.
1843 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001844 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001845 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001846 RParenLoc, BaseType));
Sean Huntcbb67482011-01-08 20:30:50 +00001847 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001848 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001849 LParenLoc,
1850 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001851 RParenLoc,
1852 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001853 }
1854
Sean Huntcbb67482011-01-08 20:30:50 +00001855 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001856 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001857 LParenLoc,
1858 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001859 RParenLoc,
1860 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001861}
1862
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001863// Create a static_cast\<T&&>(expr).
1864static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
1865 QualType ExprType = E->getType();
1866 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
1867 SourceLocation ExprLoc = E->getLocStart();
1868 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
1869 TargetType, ExprLoc);
1870
1871 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1872 SourceRange(ExprLoc, ExprLoc),
1873 E->getSourceRange()).take();
1874}
1875
Anders Carlssone5ef7402010-04-23 03:10:23 +00001876/// ImplicitInitializerKind - How an implicit base or member initializer should
1877/// initialize its base or member.
1878enum ImplicitInitializerKind {
1879 IIK_Default,
1880 IIK_Copy,
1881 IIK_Move
1882};
1883
Anders Carlssondefefd22010-04-23 02:00:02 +00001884static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001885BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001886 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001887 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001888 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001889 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001890 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001891 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1892 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001893
John McCall60d7b3a2010-08-24 06:29:42 +00001894 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001895
1896 switch (ImplicitInitKind) {
1897 case IIK_Default: {
1898 InitializationKind InitKind
1899 = InitializationKind::CreateDefault(Constructor->getLocation());
1900 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1901 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001902 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001903 break;
1904 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001905
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001906 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00001907 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001908 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001909 ParmVarDecl *Param = Constructor->getParamDecl(0);
1910 QualType ParamType = Param->getType().getNonReferenceType();
1911
1912 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001913 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001914 Constructor->getLocation(), ParamType,
1915 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001916
Anders Carlssonc7957502010-04-24 22:02:54 +00001917 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001918 QualType ArgTy =
1919 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1920 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001921
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001922 if (Moving) {
1923 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
1924 }
1925
John McCallf871d0c2010-08-07 06:22:56 +00001926 CXXCastPath BasePath;
1927 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001928 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1929 CK_UncheckedDerivedToBase,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001930 Moving ? VK_RValue : VK_LValue,
1931 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001932
Anders Carlssone5ef7402010-04-23 03:10:23 +00001933 InitializationKind InitKind
1934 = InitializationKind::CreateDirect(Constructor->getLocation(),
1935 SourceLocation(), SourceLocation());
1936 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1937 &CopyCtorArg, 1);
1938 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001939 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001940 break;
1941 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00001942 }
John McCall9ae2f072010-08-23 23:25:46 +00001943
Douglas Gregor53c374f2010-12-07 00:41:46 +00001944 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001945 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001946 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001947
Anders Carlssondefefd22010-04-23 02:00:02 +00001948 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001949 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001950 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1951 SourceLocation()),
1952 BaseSpec->isVirtual(),
1953 SourceLocation(),
1954 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001955 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001956 SourceLocation());
1957
Anders Carlssondefefd22010-04-23 02:00:02 +00001958 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001959}
1960
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001961static bool RefersToRValueRef(Expr *MemRef) {
1962 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
1963 return Referenced->getType()->isRValueReferenceType();
1964}
1965
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001966static bool
1967BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001968 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00001969 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00001970 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001971 if (Field->isInvalidDecl())
1972 return true;
1973
Chandler Carruthf186b542010-06-29 23:50:44 +00001974 SourceLocation Loc = Constructor->getLocation();
1975
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001976 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
1977 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001978 ParmVarDecl *Param = Constructor->getParamDecl(0);
1979 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00001980
1981 // Suppress copying zero-width bitfields.
1982 if (const Expr *Width = Field->getBitWidth())
1983 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
1984 return false;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001985
1986 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001987 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001988 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001989
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001990 if (Moving) {
1991 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
1992 }
1993
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001994 // Build a reference to this field within the parameter.
1995 CXXScopeSpec SS;
1996 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1997 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001998 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
1999 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002000 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00002001 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002002 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002003 ParamType, Loc,
2004 /*IsArrow=*/false,
2005 SS,
2006 /*FirstQualifierInScope=*/0,
2007 MemberLookup,
2008 /*TemplateArgs=*/0);
2009 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002010 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002011
2012 // C++11 [class.copy]p15:
2013 // - if a member m has rvalue reference type T&&, it is direct-initialized
2014 // with static_cast<T&&>(x.m);
2015 if (RefersToRValueRef(CopyCtorArg.get())) {
2016 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg.take());
2017 }
2018
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002019 // When the field we are copying is an array, create index variables for
2020 // each dimension of the array. We use these index variables to subscript
2021 // the source array, and other clients (e.g., CodeGen) will perform the
2022 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002023 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002024 QualType BaseType = Field->getType();
2025 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002026 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002027 while (const ConstantArrayType *Array
2028 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002029 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002030 // Create the iteration variable for this array index.
2031 IdentifierInfo *IterationVarName = 0;
2032 {
2033 llvm::SmallString<8> Str;
2034 llvm::raw_svector_ostream OS(Str);
2035 OS << "__i" << IndexVariables.size();
2036 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2037 }
2038 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002039 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002040 IterationVarName, SizeType,
2041 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002042 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002043 IndexVariables.push_back(IterationVar);
2044
2045 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002046 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002047 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002048 assert(!IterationVarRef.isInvalid() &&
2049 "Reference to invented variable cannot fail!");
2050
2051 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00002052 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002053 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002054 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002055 Loc);
2056 if (CopyCtorArg.isInvalid())
2057 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002058
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002059 BaseType = Array->getElementType();
2060 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002061
2062 // The array subscript expression is an lvalue, which is wrong for moving.
2063 if (Moving && InitializingArray)
2064 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg.take());
2065
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002066 // Construct the entity that we will be initializing. For an array, this
2067 // will be first element in the array, which may require several levels
2068 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002069 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002070 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002071 if (Indirect)
2072 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2073 else
2074 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002075 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2076 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2077 0,
2078 Entities.back()));
2079
2080 // Direct-initialize to use the copy constructor.
2081 InitializationKind InitKind =
2082 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2083
2084 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2085 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2086 &CopyCtorArgE, 1);
2087
John McCall60d7b3a2010-08-24 06:29:42 +00002088 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002089 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002090 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002091 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002092 if (MemberInit.isInvalid())
2093 return true;
2094
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002095 if (Indirect) {
2096 assert(IndexVariables.size() == 0 &&
2097 "Indirect field improperly initialized");
2098 CXXMemberInit
2099 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2100 Loc, Loc,
2101 MemberInit.takeAs<Expr>(),
2102 Loc);
2103 } else
2104 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2105 Loc, MemberInit.takeAs<Expr>(),
2106 Loc,
2107 IndexVariables.data(),
2108 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002109 return false;
2110 }
2111
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002112 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2113
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002114 QualType FieldBaseElementType =
2115 SemaRef.Context.getBaseElementType(Field->getType());
2116
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002117 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002118 InitializedEntity InitEntity
2119 = Indirect? InitializedEntity::InitializeMember(Indirect)
2120 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002121 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002122 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002123
2124 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002125 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002126 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002127
Douglas Gregor53c374f2010-12-07 00:41:46 +00002128 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002129 if (MemberInit.isInvalid())
2130 return true;
2131
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002132 if (Indirect)
2133 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2134 Indirect, Loc,
2135 Loc,
2136 MemberInit.get(),
2137 Loc);
2138 else
2139 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2140 Field, Loc, Loc,
2141 MemberInit.get(),
2142 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002143 return false;
2144 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002145
Sean Hunt1f2f3842011-05-17 00:19:05 +00002146 if (!Field->getParent()->isUnion()) {
2147 if (FieldBaseElementType->isReferenceType()) {
2148 SemaRef.Diag(Constructor->getLocation(),
2149 diag::err_uninitialized_member_in_ctor)
2150 << (int)Constructor->isImplicit()
2151 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2152 << 0 << Field->getDeclName();
2153 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2154 return true;
2155 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002156
Sean Hunt1f2f3842011-05-17 00:19:05 +00002157 if (FieldBaseElementType.isConstQualified()) {
2158 SemaRef.Diag(Constructor->getLocation(),
2159 diag::err_uninitialized_member_in_ctor)
2160 << (int)Constructor->isImplicit()
2161 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2162 << 1 << Field->getDeclName();
2163 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2164 return true;
2165 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002166 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002167
John McCallf85e1932011-06-15 23:02:42 +00002168 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2169 FieldBaseElementType->isObjCRetainableType() &&
2170 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2171 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2172 // Instant objects:
2173 // Default-initialize Objective-C pointers to NULL.
2174 CXXMemberInit
2175 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2176 Loc, Loc,
2177 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2178 Loc);
2179 return false;
2180 }
2181
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002182 // Nothing to initialize.
2183 CXXMemberInit = 0;
2184 return false;
2185}
John McCallf1860e52010-05-20 23:23:51 +00002186
2187namespace {
2188struct BaseAndFieldInfo {
2189 Sema &S;
2190 CXXConstructorDecl *Ctor;
2191 bool AnyErrorsInInits;
2192 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002193 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002194 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002195
2196 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2197 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002198 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2199 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002200 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002201 else if (Generated && Ctor->isMoveConstructor())
2202 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002203 else
2204 IIK = IIK_Default;
2205 }
2206};
2207}
2208
Richard Smith7a614d82011-06-11 17:19:42 +00002209static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002210 FieldDecl *Field,
2211 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002212
Chandler Carruthe861c602010-06-30 02:59:29 +00002213 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002214 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002215 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002216 return false;
2217 }
2218
Richard Smith7a614d82011-06-11 17:19:42 +00002219 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2220 // has a brace-or-equal-initializer, the entity is initialized as specified
2221 // in [dcl.init].
2222 if (Field->hasInClassInitializer()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002223 CXXCtorInitializer *Init;
2224 if (Indirect)
2225 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2226 SourceLocation(),
2227 SourceLocation(), 0,
2228 SourceLocation());
2229 else
2230 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2231 SourceLocation(),
2232 SourceLocation(), 0,
2233 SourceLocation());
2234 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002235 return false;
2236 }
2237
John McCallf1860e52010-05-20 23:23:51 +00002238 // Don't try to build an implicit initializer if there were semantic
2239 // errors in any of the initializers (and therefore we might be
2240 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002241 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002242 return false;
2243
Sean Huntcbb67482011-01-08 20:30:50 +00002244 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002245 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2246 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002247 return true;
John McCallf1860e52010-05-20 23:23:51 +00002248
Francois Pichet00eb3f92010-12-04 09:14:42 +00002249 if (Init)
2250 Info.AllToInit.push_back(Init);
2251
John McCallf1860e52010-05-20 23:23:51 +00002252 return false;
2253}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002254
2255bool
2256Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2257 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002258 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002259 Constructor->setNumCtorInitializers(1);
2260 CXXCtorInitializer **initializer =
2261 new (Context) CXXCtorInitializer*[1];
2262 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2263 Constructor->setCtorInitializers(initializer);
2264
Sean Huntb76af9c2011-05-03 23:05:34 +00002265 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2266 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2267 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2268 }
2269
Sean Huntc1598702011-05-05 00:05:47 +00002270 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002271
Sean Hunt059ce0d2011-05-01 07:04:31 +00002272 return false;
2273}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002274
2275/// \brief Determine whether the given indirect field declaration is somewhere
2276/// within an anonymous union.
2277static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2278 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2279 CEnd = F->chain_end();
2280 C != CEnd; ++C)
2281 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2282 if (Record->isUnion())
2283 return true;
2284
2285 return false;
2286}
2287
John McCallb77115d2011-06-17 00:18:42 +00002288bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2289 CXXCtorInitializer **Initializers,
2290 unsigned NumInitializers,
2291 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002292 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002293 // Just store the initializers as written, they will be checked during
2294 // instantiation.
2295 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002296 Constructor->setNumCtorInitializers(NumInitializers);
2297 CXXCtorInitializer **baseOrMemberInitializers =
2298 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002299 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002300 NumInitializers * sizeof(CXXCtorInitializer*));
2301 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002302 }
2303
2304 return false;
2305 }
2306
John McCallf1860e52010-05-20 23:23:51 +00002307 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002308
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002309 // We need to build the initializer AST according to order of construction
2310 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002311 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002312 if (!ClassDecl)
2313 return true;
2314
Eli Friedman80c30da2009-11-09 19:20:36 +00002315 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002317 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002318 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002319
2320 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002321 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002322 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002323 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002324 }
2325
Anders Carlsson711f34a2010-04-21 19:52:01 +00002326 // Keep track of the direct virtual bases.
2327 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2328 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2329 E = ClassDecl->bases_end(); I != E; ++I) {
2330 if (I->isVirtual())
2331 DirectVBases.insert(I);
2332 }
2333
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002334 // Push virtual bases before others.
2335 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2336 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2337
Sean Huntcbb67482011-01-08 20:30:50 +00002338 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002339 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2340 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002341 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002342 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002343 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002344 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002345 VBase, IsInheritedVirtualBase,
2346 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002347 HadError = true;
2348 continue;
2349 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002350
John McCallf1860e52010-05-20 23:23:51 +00002351 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002352 }
2353 }
Mike Stump1eb44332009-09-09 15:08:12 +00002354
John McCallf1860e52010-05-20 23:23:51 +00002355 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002356 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2357 E = ClassDecl->bases_end(); Base != E; ++Base) {
2358 // Virtuals are in the virtual base list and already constructed.
2359 if (Base->isVirtual())
2360 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Sean Huntcbb67482011-01-08 20:30:50 +00002362 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002363 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2364 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002365 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002366 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002367 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002368 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002369 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002370 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002371 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002372 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002373
John McCallf1860e52010-05-20 23:23:51 +00002374 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002375 }
2376 }
Mike Stump1eb44332009-09-09 15:08:12 +00002377
John McCallf1860e52010-05-20 23:23:51 +00002378 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002379 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2380 MemEnd = ClassDecl->decls_end();
2381 Mem != MemEnd; ++Mem) {
2382 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2383 if (F->getType()->isIncompleteArrayType()) {
2384 assert(ClassDecl->hasFlexibleArrayMember() &&
2385 "Incomplete array type is not valid");
2386 continue;
2387 }
2388
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002389 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002390 // handle anonymous struct/union fields based on their individual
2391 // indirect fields.
2392 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2393 continue;
2394
2395 if (CollectFieldInitializer(*this, Info, F))
2396 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002397 continue;
2398 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002399
2400 // Beyond this point, we only consider default initialization.
2401 if (Info.IIK != IIK_Default)
2402 continue;
2403
2404 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2405 if (F->getType()->isIncompleteArrayType()) {
2406 assert(ClassDecl->hasFlexibleArrayMember() &&
2407 "Incomplete array type is not valid");
2408 continue;
2409 }
2410
2411 // If this field is somewhere within an anonymous union, we only
2412 // initialize it if there's an explicit initializer.
2413 if (isWithinAnonymousUnion(F)) {
2414 if (CXXCtorInitializer *Init
2415 = Info.AllBaseFields.lookup(F->getAnonField())) {
2416 Info.AllToInit.push_back(Init);
2417 }
2418
2419 continue;
2420 }
2421
2422 // Initialize each field of an anonymous struct individually.
2423 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2424 HadError = true;
2425
2426 continue;
2427 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002428 }
Mike Stump1eb44332009-09-09 15:08:12 +00002429
John McCallf1860e52010-05-20 23:23:51 +00002430 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002431 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002432 Constructor->setNumCtorInitializers(NumInitializers);
2433 CXXCtorInitializer **baseOrMemberInitializers =
2434 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002435 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002436 NumInitializers * sizeof(CXXCtorInitializer*));
2437 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002438
John McCallef027fe2010-03-16 21:39:52 +00002439 // Constructors implicitly reference the base and member
2440 // destructors.
2441 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2442 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002443 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002444
2445 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002446}
2447
Eli Friedman6347f422009-07-21 19:28:10 +00002448static void *GetKeyForTopLevelField(FieldDecl *Field) {
2449 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002450 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002451 if (RT->getDecl()->isAnonymousStructOrUnion())
2452 return static_cast<void *>(RT->getDecl());
2453 }
2454 return static_cast<void *>(Field);
2455}
2456
Anders Carlssonea356fb2010-04-02 05:42:15 +00002457static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002458 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002459}
2460
Anders Carlssonea356fb2010-04-02 05:42:15 +00002461static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002462 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002463 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002464 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002465
Eli Friedman6347f422009-07-21 19:28:10 +00002466 // For fields injected into the class via declaration of an anonymous union,
2467 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002468 FieldDecl *Field = Member->getAnyMember();
2469
John McCall3c3ccdb2010-04-10 09:28:51 +00002470 // If the field is a member of an anonymous struct or union, our key
2471 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002472 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002473 if (RD->isAnonymousStructOrUnion()) {
2474 while (true) {
2475 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2476 if (Parent->isAnonymousStructOrUnion())
2477 RD = Parent;
2478 else
2479 break;
2480 }
2481
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002482 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002483 }
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002485 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002486}
2487
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002488static void
2489DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002490 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002491 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002492 unsigned NumInits) {
2493 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002494 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002496 // Don't check initializers order unless the warning is enabled at the
2497 // location of at least one initializer.
2498 bool ShouldCheckOrder = false;
2499 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002500 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002501 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2502 Init->getSourceLocation())
2503 != Diagnostic::Ignored) {
2504 ShouldCheckOrder = true;
2505 break;
2506 }
2507 }
2508 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002509 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002510
John McCalld6ca8da2010-04-10 07:37:23 +00002511 // Build the list of bases and members in the order that they'll
2512 // actually be initialized. The explicit initializers should be in
2513 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002514 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002515
Anders Carlsson071d6102010-04-02 03:38:04 +00002516 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2517
John McCalld6ca8da2010-04-10 07:37:23 +00002518 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002519 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002520 ClassDecl->vbases_begin(),
2521 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002522 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002523
John McCalld6ca8da2010-04-10 07:37:23 +00002524 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002525 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002526 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002527 if (Base->isVirtual())
2528 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002529 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002530 }
Mike Stump1eb44332009-09-09 15:08:12 +00002531
John McCalld6ca8da2010-04-10 07:37:23 +00002532 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002533 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2534 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002535 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002536
John McCalld6ca8da2010-04-10 07:37:23 +00002537 unsigned NumIdealInits = IdealInitKeys.size();
2538 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002539
Sean Huntcbb67482011-01-08 20:30:50 +00002540 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002541 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002542 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002543 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002544
2545 // Scan forward to try to find this initializer in the idealized
2546 // initializers list.
2547 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2548 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002549 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002550
2551 // If we didn't find this initializer, it must be because we
2552 // scanned past it on a previous iteration. That can only
2553 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002554 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002555 Sema::SemaDiagnosticBuilder D =
2556 SemaRef.Diag(PrevInit->getSourceLocation(),
2557 diag::warn_initializer_out_of_order);
2558
Francois Pichet00eb3f92010-12-04 09:14:42 +00002559 if (PrevInit->isAnyMemberInitializer())
2560 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002561 else
2562 D << 1 << PrevInit->getBaseClassInfo()->getType();
2563
Francois Pichet00eb3f92010-12-04 09:14:42 +00002564 if (Init->isAnyMemberInitializer())
2565 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002566 else
2567 D << 1 << Init->getBaseClassInfo()->getType();
2568
2569 // Move back to the initializer's location in the ideal list.
2570 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2571 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002572 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002573
2574 assert(IdealIndex != NumIdealInits &&
2575 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002576 }
John McCalld6ca8da2010-04-10 07:37:23 +00002577
2578 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002579 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002580}
2581
John McCall3c3ccdb2010-04-10 09:28:51 +00002582namespace {
2583bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002584 CXXCtorInitializer *Init,
2585 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002586 if (!PrevInit) {
2587 PrevInit = Init;
2588 return false;
2589 }
2590
2591 if (FieldDecl *Field = Init->getMember())
2592 S.Diag(Init->getSourceLocation(),
2593 diag::err_multiple_mem_initialization)
2594 << Field->getDeclName()
2595 << Init->getSourceRange();
2596 else {
John McCallf4c73712011-01-19 06:33:43 +00002597 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002598 assert(BaseClass && "neither field nor base");
2599 S.Diag(Init->getSourceLocation(),
2600 diag::err_multiple_base_initialization)
2601 << QualType(BaseClass, 0)
2602 << Init->getSourceRange();
2603 }
2604 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2605 << 0 << PrevInit->getSourceRange();
2606
2607 return true;
2608}
2609
Sean Huntcbb67482011-01-08 20:30:50 +00002610typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002611typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2612
2613bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002614 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002615 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002616 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002617 RecordDecl *Parent = Field->getParent();
2618 if (!Parent->isAnonymousStructOrUnion())
2619 return false;
2620
2621 NamedDecl *Child = Field;
2622 do {
2623 if (Parent->isUnion()) {
2624 UnionEntry &En = Unions[Parent];
2625 if (En.first && En.first != Child) {
2626 S.Diag(Init->getSourceLocation(),
2627 diag::err_multiple_mem_union_initialization)
2628 << Field->getDeclName()
2629 << Init->getSourceRange();
2630 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2631 << 0 << En.second->getSourceRange();
2632 return true;
2633 } else if (!En.first) {
2634 En.first = Child;
2635 En.second = Init;
2636 }
2637 }
2638
2639 Child = Parent;
2640 Parent = cast<RecordDecl>(Parent->getDeclContext());
2641 } while (Parent->isAnonymousStructOrUnion());
2642
2643 return false;
2644}
2645}
2646
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002647/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002648void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002649 SourceLocation ColonLoc,
2650 MemInitTy **meminits, unsigned NumMemInits,
2651 bool AnyErrors) {
2652 if (!ConstructorDecl)
2653 return;
2654
2655 AdjustDeclIfTemplate(ConstructorDecl);
2656
2657 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002658 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002659
2660 if (!Constructor) {
2661 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2662 return;
2663 }
2664
Sean Huntcbb67482011-01-08 20:30:50 +00002665 CXXCtorInitializer **MemInits =
2666 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002667
2668 // Mapping for the duplicate initializers check.
2669 // For member initializers, this is keyed with a FieldDecl*.
2670 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002671 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002672
2673 // Mapping for the inconsistent anonymous-union initializers check.
2674 RedundantUnionMap MemberUnions;
2675
Anders Carlssonea356fb2010-04-02 05:42:15 +00002676 bool HadError = false;
2677 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002678 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002679
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002680 // Set the source order index.
2681 Init->setSourceOrder(i);
2682
Francois Pichet00eb3f92010-12-04 09:14:42 +00002683 if (Init->isAnyMemberInitializer()) {
2684 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002685 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2686 CheckRedundantUnionInit(*this, Init, MemberUnions))
2687 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002688 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002689 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2690 if (CheckRedundantInit(*this, Init, Members[Key]))
2691 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002692 } else {
2693 assert(Init->isDelegatingInitializer());
2694 // This must be the only initializer
2695 if (i != 0 || NumMemInits > 1) {
2696 Diag(MemInits[0]->getSourceLocation(),
2697 diag::err_delegating_initializer_alone)
2698 << MemInits[0]->getSourceRange();
2699 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002700 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002701 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002702 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002703 // Return immediately as the initializer is set.
2704 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002705 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002706 }
2707
Anders Carlssonea356fb2010-04-02 05:42:15 +00002708 if (HadError)
2709 return;
2710
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002711 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002712
Sean Huntcbb67482011-01-08 20:30:50 +00002713 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002714}
2715
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002716void
John McCallef027fe2010-03-16 21:39:52 +00002717Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2718 CXXRecordDecl *ClassDecl) {
2719 // Ignore dependent contexts.
2720 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002721 return;
John McCall58e6f342010-03-16 05:22:47 +00002722
2723 // FIXME: all the access-control diagnostics are positioned on the
2724 // field/base declaration. That's probably good; that said, the
2725 // user might reasonably want to know why the destructor is being
2726 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002727
Anders Carlsson9f853df2009-11-17 04:44:12 +00002728 // Non-static data members.
2729 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2730 E = ClassDecl->field_end(); I != E; ++I) {
2731 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002732 if (Field->isInvalidDecl())
2733 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002734 QualType FieldType = Context.getBaseElementType(Field->getType());
2735
2736 const RecordType* RT = FieldType->getAs<RecordType>();
2737 if (!RT)
2738 continue;
2739
2740 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002741 if (FieldClassDecl->isInvalidDecl())
2742 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002743 if (FieldClassDecl->hasTrivialDestructor())
2744 continue;
2745
Douglas Gregordb89f282010-07-01 22:47:18 +00002746 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002747 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002748 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002749 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002750 << Field->getDeclName()
2751 << FieldType);
2752
John McCallef027fe2010-03-16 21:39:52 +00002753 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002754 }
2755
John McCall58e6f342010-03-16 05:22:47 +00002756 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2757
Anders Carlsson9f853df2009-11-17 04:44:12 +00002758 // Bases.
2759 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2760 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002761 // Bases are always records in a well-formed non-dependent class.
2762 const RecordType *RT = Base->getType()->getAs<RecordType>();
2763
2764 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002765 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002766 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002767
John McCall58e6f342010-03-16 05:22:47 +00002768 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002769 // If our base class is invalid, we probably can't get its dtor anyway.
2770 if (BaseClassDecl->isInvalidDecl())
2771 continue;
2772 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002773 if (BaseClassDecl->hasTrivialDestructor())
2774 continue;
John McCall58e6f342010-03-16 05:22:47 +00002775
Douglas Gregordb89f282010-07-01 22:47:18 +00002776 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002777 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002778
2779 // FIXME: caret should be on the start of the class name
2780 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002781 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002782 << Base->getType()
2783 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002784
John McCallef027fe2010-03-16 21:39:52 +00002785 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002786 }
2787
2788 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002789 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2790 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002791
2792 // Bases are always records in a well-formed non-dependent class.
2793 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2794
2795 // Ignore direct virtual bases.
2796 if (DirectVirtualBases.count(RT))
2797 continue;
2798
John McCall58e6f342010-03-16 05:22:47 +00002799 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002800 // If our base class is invalid, we probably can't get its dtor anyway.
2801 if (BaseClassDecl->isInvalidDecl())
2802 continue;
2803 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002804 if (BaseClassDecl->hasTrivialDestructor())
2805 continue;
John McCall58e6f342010-03-16 05:22:47 +00002806
Douglas Gregordb89f282010-07-01 22:47:18 +00002807 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002808 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002809 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002810 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002811 << VBase->getType());
2812
John McCallef027fe2010-03-16 21:39:52 +00002813 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002814 }
2815}
2816
John McCalld226f652010-08-21 09:40:31 +00002817void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002818 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002819 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Mike Stump1eb44332009-09-09 15:08:12 +00002821 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002822 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002823 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002824}
2825
Mike Stump1eb44332009-09-09 15:08:12 +00002826bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002827 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002828 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002829 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002830 else
John McCall94c3b562010-08-18 09:41:07 +00002831 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002832}
2833
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002834bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002835 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002836 if (!getLangOptions().CPlusPlus)
2837 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002838
Anders Carlsson11f21a02009-03-23 19:10:31 +00002839 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002840 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Ted Kremenek6217b802009-07-29 21:53:49 +00002842 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002843 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002844 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002845 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002847 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002848 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002849 }
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Ted Kremenek6217b802009-07-29 21:53:49 +00002851 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002852 if (!RT)
2853 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002854
John McCall86ff3082010-02-04 22:26:26 +00002855 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002856
John McCall94c3b562010-08-18 09:41:07 +00002857 // We can't answer whether something is abstract until it has a
2858 // definition. If it's currently being defined, we'll walk back
2859 // over all the declarations when we have a full definition.
2860 const CXXRecordDecl *Def = RD->getDefinition();
2861 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002862 return false;
2863
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002864 if (!RD->isAbstract())
2865 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002866
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002867 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002868 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002869
John McCall94c3b562010-08-18 09:41:07 +00002870 return true;
2871}
2872
2873void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2874 // Check if we've already emitted the list of pure virtual functions
2875 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002876 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002877 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002879 CXXFinalOverriderMap FinalOverriders;
2880 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002881
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002882 // Keep a set of seen pure methods so we won't diagnose the same method
2883 // more than once.
2884 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2885
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002886 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2887 MEnd = FinalOverriders.end();
2888 M != MEnd;
2889 ++M) {
2890 for (OverridingMethods::iterator SO = M->second.begin(),
2891 SOEnd = M->second.end();
2892 SO != SOEnd; ++SO) {
2893 // C++ [class.abstract]p4:
2894 // A class is abstract if it contains or inherits at least one
2895 // pure virtual function for which the final overrider is pure
2896 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002898 //
2899 if (SO->second.size() != 1)
2900 continue;
2901
2902 if (!SO->second.front().Method->isPure())
2903 continue;
2904
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002905 if (!SeenPureMethods.insert(SO->second.front().Method))
2906 continue;
2907
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002908 Diag(SO->second.front().Method->getLocation(),
2909 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002910 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002911 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002912 }
2913
2914 if (!PureVirtualClassDiagSet)
2915 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2916 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002917}
2918
Anders Carlsson8211eff2009-03-24 01:19:16 +00002919namespace {
John McCall94c3b562010-08-18 09:41:07 +00002920struct AbstractUsageInfo {
2921 Sema &S;
2922 CXXRecordDecl *Record;
2923 CanQualType AbstractType;
2924 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002925
John McCall94c3b562010-08-18 09:41:07 +00002926 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2927 : S(S), Record(Record),
2928 AbstractType(S.Context.getCanonicalType(
2929 S.Context.getTypeDeclType(Record))),
2930 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002931
John McCall94c3b562010-08-18 09:41:07 +00002932 void DiagnoseAbstractType() {
2933 if (Invalid) return;
2934 S.DiagnoseAbstractType(Record);
2935 Invalid = true;
2936 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002937
John McCall94c3b562010-08-18 09:41:07 +00002938 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2939};
2940
2941struct CheckAbstractUsage {
2942 AbstractUsageInfo &Info;
2943 const NamedDecl *Ctx;
2944
2945 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2946 : Info(Info), Ctx(Ctx) {}
2947
2948 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2949 switch (TL.getTypeLocClass()) {
2950#define ABSTRACT_TYPELOC(CLASS, PARENT)
2951#define TYPELOC(CLASS, PARENT) \
2952 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2953#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002954 }
John McCall94c3b562010-08-18 09:41:07 +00002955 }
Mike Stump1eb44332009-09-09 15:08:12 +00002956
John McCall94c3b562010-08-18 09:41:07 +00002957 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2958 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2959 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002960 if (!TL.getArg(I))
2961 continue;
2962
John McCall94c3b562010-08-18 09:41:07 +00002963 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2964 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002965 }
John McCall94c3b562010-08-18 09:41:07 +00002966 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002967
John McCall94c3b562010-08-18 09:41:07 +00002968 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2969 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2970 }
Mike Stump1eb44332009-09-09 15:08:12 +00002971
John McCall94c3b562010-08-18 09:41:07 +00002972 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2973 // Visit the type parameters from a permissive context.
2974 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2975 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2976 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2977 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2978 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2979 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002980 }
John McCall94c3b562010-08-18 09:41:07 +00002981 }
Mike Stump1eb44332009-09-09 15:08:12 +00002982
John McCall94c3b562010-08-18 09:41:07 +00002983 // Visit pointee types from a permissive context.
2984#define CheckPolymorphic(Type) \
2985 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2986 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2987 }
2988 CheckPolymorphic(PointerTypeLoc)
2989 CheckPolymorphic(ReferenceTypeLoc)
2990 CheckPolymorphic(MemberPointerTypeLoc)
2991 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002992
John McCall94c3b562010-08-18 09:41:07 +00002993 /// Handle all the types we haven't given a more specific
2994 /// implementation for above.
2995 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2996 // Every other kind of type that we haven't called out already
2997 // that has an inner type is either (1) sugar or (2) contains that
2998 // inner type in some way as a subobject.
2999 if (TypeLoc Next = TL.getNextTypeLoc())
3000 return Visit(Next, Sel);
3001
3002 // If there's no inner type and we're in a permissive context,
3003 // don't diagnose.
3004 if (Sel == Sema::AbstractNone) return;
3005
3006 // Check whether the type matches the abstract type.
3007 QualType T = TL.getType();
3008 if (T->isArrayType()) {
3009 Sel = Sema::AbstractArrayType;
3010 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003011 }
John McCall94c3b562010-08-18 09:41:07 +00003012 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3013 if (CT != Info.AbstractType) return;
3014
3015 // It matched; do some magic.
3016 if (Sel == Sema::AbstractArrayType) {
3017 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3018 << T << TL.getSourceRange();
3019 } else {
3020 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3021 << Sel << T << TL.getSourceRange();
3022 }
3023 Info.DiagnoseAbstractType();
3024 }
3025};
3026
3027void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3028 Sema::AbstractDiagSelID Sel) {
3029 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3030}
3031
3032}
3033
3034/// Check for invalid uses of an abstract type in a method declaration.
3035static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3036 CXXMethodDecl *MD) {
3037 // No need to do the check on definitions, which require that
3038 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003039 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003040 return;
3041
3042 // For safety's sake, just ignore it if we don't have type source
3043 // information. This should never happen for non-implicit methods,
3044 // but...
3045 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3046 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3047}
3048
3049/// Check for invalid uses of an abstract type within a class definition.
3050static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3051 CXXRecordDecl *RD) {
3052 for (CXXRecordDecl::decl_iterator
3053 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3054 Decl *D = *I;
3055 if (D->isImplicit()) continue;
3056
3057 // Methods and method templates.
3058 if (isa<CXXMethodDecl>(D)) {
3059 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3060 } else if (isa<FunctionTemplateDecl>(D)) {
3061 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3062 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3063
3064 // Fields and static variables.
3065 } else if (isa<FieldDecl>(D)) {
3066 FieldDecl *FD = cast<FieldDecl>(D);
3067 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3068 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3069 } else if (isa<VarDecl>(D)) {
3070 VarDecl *VD = cast<VarDecl>(D);
3071 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3072 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3073
3074 // Nested classes and class templates.
3075 } else if (isa<CXXRecordDecl>(D)) {
3076 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3077 } else if (isa<ClassTemplateDecl>(D)) {
3078 CheckAbstractClassUsage(Info,
3079 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3080 }
3081 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003082}
3083
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003084/// \brief Perform semantic checks on a class definition that has been
3085/// completing, introducing implicitly-declared members, checking for
3086/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003087void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003088 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003089 return;
3090
John McCall94c3b562010-08-18 09:41:07 +00003091 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3092 AbstractUsageInfo Info(*this, Record);
3093 CheckAbstractClassUsage(Info, Record);
3094 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003095
3096 // If this is not an aggregate type and has no user-declared constructor,
3097 // complain about any non-static data members of reference or const scalar
3098 // type, since they will never get initializers.
3099 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3100 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3101 bool Complained = false;
3102 for (RecordDecl::field_iterator F = Record->field_begin(),
3103 FEnd = Record->field_end();
3104 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003105 if (F->hasInClassInitializer())
3106 continue;
3107
Douglas Gregor325e5932010-04-15 00:00:53 +00003108 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003109 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003110 if (!Complained) {
3111 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3112 << Record->getTagKind() << Record;
3113 Complained = true;
3114 }
3115
3116 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3117 << F->getType()->isReferenceType()
3118 << F->getDeclName();
3119 }
3120 }
3121 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003122
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003123 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003124 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003125
3126 if (Record->getIdentifier()) {
3127 // C++ [class.mem]p13:
3128 // If T is the name of a class, then each of the following shall have a
3129 // name different from T:
3130 // - every member of every anonymous union that is a member of class T.
3131 //
3132 // C++ [class.mem]p14:
3133 // In addition, if class T has a user-declared constructor (12.1), every
3134 // non-static data member of class T shall have a name different from T.
3135 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003136 R.first != R.second; ++R.first) {
3137 NamedDecl *D = *R.first;
3138 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3139 isa<IndirectFieldDecl>(D)) {
3140 Diag(D->getLocation(), diag::err_member_name_of_class)
3141 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003142 break;
3143 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003144 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003145 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003146
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003147 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003148 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003149 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003150 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003151 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3152 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3153 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003154
3155 // See if a method overloads virtual methods in a base
3156 /// class without overriding any.
3157 if (!Record->isDependentType()) {
3158 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3159 MEnd = Record->method_end();
3160 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003161 if (!(*M)->isStatic())
3162 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003163 }
3164 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003165
3166 // Declare inherited constructors. We do this eagerly here because:
3167 // - The standard requires an eager diagnostic for conflicting inherited
3168 // constructors from different classes.
3169 // - The lazy declaration of the other implicit constructors is so as to not
3170 // waste space and performance on classes that are not meant to be
3171 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3172 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003173 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003174
Sean Hunteb88ae52011-05-23 21:07:59 +00003175 if (!Record->isDependentType())
3176 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003177}
3178
3179void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003180 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3181 ME = Record->method_end();
3182 MI != ME; ++MI) {
3183 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3184 switch (getSpecialMember(*MI)) {
3185 case CXXDefaultConstructor:
3186 CheckExplicitlyDefaultedDefaultConstructor(
3187 cast<CXXConstructorDecl>(*MI));
3188 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003189
Sean Huntcb45a0f2011-05-12 22:46:25 +00003190 case CXXDestructor:
3191 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3192 break;
3193
3194 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003195 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3196 break;
3197
Sean Huntcb45a0f2011-05-12 22:46:25 +00003198 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003199 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003200 break;
3201
Sean Hunt82713172011-05-25 23:16:36 +00003202 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003203 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003204 break;
3205
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003206 case CXXMoveAssignment:
3207 CheckExplicitlyDefaultedMoveAssignment(*MI);
3208 break;
3209
3210 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003211 llvm_unreachable("non-special member explicitly defaulted!");
3212 }
Sean Hunt001cad92011-05-10 00:49:42 +00003213 }
3214 }
3215
Sean Hunt001cad92011-05-10 00:49:42 +00003216}
3217
3218void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3219 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3220
3221 // Whether this was the first-declared instance of the constructor.
3222 // This affects whether we implicitly add an exception spec (and, eventually,
3223 // constexpr). It is also ill-formed to explicitly default a constructor such
3224 // that it would be deleted. (C++0x [decl.fct.def.default])
3225 bool First = CD == CD->getCanonicalDecl();
3226
Sean Hunt49634cf2011-05-13 06:10:58 +00003227 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003228 if (CD->getNumParams() != 0) {
3229 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3230 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003231 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003232 }
3233
3234 ImplicitExceptionSpecification Spec
3235 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3236 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003237 if (EPI.ExceptionSpecType == EST_Delayed) {
3238 // Exception specification depends on some deferred part of the class. We'll
3239 // try again when the class's definition has been fully processed.
3240 return;
3241 }
Sean Hunt001cad92011-05-10 00:49:42 +00003242 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3243 *ExceptionType = Context.getFunctionType(
3244 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3245
3246 if (CtorType->hasExceptionSpec()) {
3247 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003248 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003249 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003250 PDiag(),
3251 ExceptionType, SourceLocation(),
3252 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003253 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003254 }
3255 } else if (First) {
3256 // We set the declaration to have the computed exception spec here.
3257 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003258 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003259 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3260 }
Sean Huntca46d132011-05-12 03:51:48 +00003261
Sean Hunt49634cf2011-05-13 06:10:58 +00003262 if (HadError) {
3263 CD->setInvalidDecl();
3264 return;
3265 }
3266
Sean Huntca46d132011-05-12 03:51:48 +00003267 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003268 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003269 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003270 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003271 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003272 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003273 CD->setInvalidDecl();
3274 }
3275 }
3276}
3277
3278void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3279 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3280
3281 // Whether this was the first-declared instance of the constructor.
3282 bool First = CD == CD->getCanonicalDecl();
3283
3284 bool HadError = false;
3285 if (CD->getNumParams() != 1) {
3286 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3287 << CD->getSourceRange();
3288 HadError = true;
3289 }
3290
3291 ImplicitExceptionSpecification Spec(Context);
3292 bool Const;
3293 llvm::tie(Spec, Const) =
3294 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3295
3296 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3297 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3298 *ExceptionType = Context.getFunctionType(
3299 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3300
3301 // Check for parameter type matching.
3302 // This is a copy ctor so we know it's a cv-qualified reference to T.
3303 QualType ArgType = CtorType->getArgType(0);
3304 if (ArgType->getPointeeType().isVolatileQualified()) {
3305 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3306 HadError = true;
3307 }
3308 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3309 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3310 HadError = true;
3311 }
3312
3313 if (CtorType->hasExceptionSpec()) {
3314 if (CheckEquivalentExceptionSpec(
3315 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003316 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003317 PDiag(),
3318 ExceptionType, SourceLocation(),
3319 CtorType, CD->getLocation())) {
3320 HadError = true;
3321 }
3322 } else if (First) {
3323 // We set the declaration to have the computed exception spec here.
3324 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003325 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003326 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3327 }
3328
3329 if (HadError) {
3330 CD->setInvalidDecl();
3331 return;
3332 }
3333
3334 if (ShouldDeleteCopyConstructor(CD)) {
3335 if (First) {
3336 CD->setDeletedAsWritten();
3337 } else {
3338 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003339 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003340 CD->setInvalidDecl();
3341 }
Sean Huntca46d132011-05-12 03:51:48 +00003342 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003343}
Sean Hunt001cad92011-05-10 00:49:42 +00003344
Sean Hunt2b188082011-05-14 05:23:28 +00003345void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3346 assert(MD->isExplicitlyDefaulted());
3347
3348 // Whether this was the first-declared instance of the operator
3349 bool First = MD == MD->getCanonicalDecl();
3350
3351 bool HadError = false;
3352 if (MD->getNumParams() != 1) {
3353 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3354 << MD->getSourceRange();
3355 HadError = true;
3356 }
3357
3358 QualType ReturnType =
3359 MD->getType()->getAs<FunctionType>()->getResultType();
3360 if (!ReturnType->isLValueReferenceType() ||
3361 !Context.hasSameType(
3362 Context.getCanonicalType(ReturnType->getPointeeType()),
3363 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3364 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3365 HadError = true;
3366 }
3367
3368 ImplicitExceptionSpecification Spec(Context);
3369 bool Const;
3370 llvm::tie(Spec, Const) =
3371 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3372
3373 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3374 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3375 *ExceptionType = Context.getFunctionType(
3376 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3377
Sean Hunt2b188082011-05-14 05:23:28 +00003378 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003379 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003380 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003381 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003382 } else {
3383 if (ArgType->getPointeeType().isVolatileQualified()) {
3384 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3385 HadError = true;
3386 }
3387 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3388 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3389 HadError = true;
3390 }
Sean Hunt2b188082011-05-14 05:23:28 +00003391 }
Sean Huntbe631222011-05-17 20:44:43 +00003392
Sean Hunt2b188082011-05-14 05:23:28 +00003393 if (OperType->getTypeQuals()) {
3394 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3395 HadError = true;
3396 }
3397
3398 if (OperType->hasExceptionSpec()) {
3399 if (CheckEquivalentExceptionSpec(
3400 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003401 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003402 PDiag(),
3403 ExceptionType, SourceLocation(),
3404 OperType, MD->getLocation())) {
3405 HadError = true;
3406 }
3407 } else if (First) {
3408 // We set the declaration to have the computed exception spec here.
3409 // We duplicate the one parameter type.
3410 EPI.RefQualifier = OperType->getRefQualifier();
3411 EPI.ExtInfo = OperType->getExtInfo();
3412 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3413 }
3414
3415 if (HadError) {
3416 MD->setInvalidDecl();
3417 return;
3418 }
3419
3420 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3421 if (First) {
3422 MD->setDeletedAsWritten();
3423 } else {
3424 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003425 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003426 MD->setInvalidDecl();
3427 }
3428 }
3429}
3430
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003431void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3432 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3433
3434 // Whether this was the first-declared instance of the constructor.
3435 bool First = CD == CD->getCanonicalDecl();
3436
3437 bool HadError = false;
3438 if (CD->getNumParams() != 1) {
3439 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3440 << CD->getSourceRange();
3441 HadError = true;
3442 }
3443
3444 ImplicitExceptionSpecification Spec(
3445 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3446
3447 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3448 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3449 *ExceptionType = Context.getFunctionType(
3450 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3451
3452 // Check for parameter type matching.
3453 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3454 QualType ArgType = CtorType->getArgType(0);
3455 if (ArgType->getPointeeType().isVolatileQualified()) {
3456 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3457 HadError = true;
3458 }
3459 if (ArgType->getPointeeType().isConstQualified()) {
3460 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3461 HadError = true;
3462 }
3463
3464 if (CtorType->hasExceptionSpec()) {
3465 if (CheckEquivalentExceptionSpec(
3466 PDiag(diag::err_incorrect_defaulted_exception_spec)
3467 << CXXMoveConstructor,
3468 PDiag(),
3469 ExceptionType, SourceLocation(),
3470 CtorType, CD->getLocation())) {
3471 HadError = true;
3472 }
3473 } else if (First) {
3474 // We set the declaration to have the computed exception spec here.
3475 // We duplicate the one parameter type.
3476 EPI.ExtInfo = CtorType->getExtInfo();
3477 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3478 }
3479
3480 if (HadError) {
3481 CD->setInvalidDecl();
3482 return;
3483 }
3484
3485 if (ShouldDeleteMoveConstructor(CD)) {
3486 if (First) {
3487 CD->setDeletedAsWritten();
3488 } else {
3489 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3490 << CXXMoveConstructor;
3491 CD->setInvalidDecl();
3492 }
3493 }
3494}
3495
3496void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3497 assert(MD->isExplicitlyDefaulted());
3498
3499 // Whether this was the first-declared instance of the operator
3500 bool First = MD == MD->getCanonicalDecl();
3501
3502 bool HadError = false;
3503 if (MD->getNumParams() != 1) {
3504 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3505 << MD->getSourceRange();
3506 HadError = true;
3507 }
3508
3509 QualType ReturnType =
3510 MD->getType()->getAs<FunctionType>()->getResultType();
3511 if (!ReturnType->isLValueReferenceType() ||
3512 !Context.hasSameType(
3513 Context.getCanonicalType(ReturnType->getPointeeType()),
3514 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3515 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3516 HadError = true;
3517 }
3518
3519 ImplicitExceptionSpecification Spec(
3520 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3521
3522 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3523 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3524 *ExceptionType = Context.getFunctionType(
3525 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3526
3527 QualType ArgType = OperType->getArgType(0);
3528 if (!ArgType->isRValueReferenceType()) {
3529 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3530 HadError = true;
3531 } else {
3532 if (ArgType->getPointeeType().isVolatileQualified()) {
3533 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3534 HadError = true;
3535 }
3536 if (ArgType->getPointeeType().isConstQualified()) {
3537 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3538 HadError = true;
3539 }
3540 }
3541
3542 if (OperType->getTypeQuals()) {
3543 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3544 HadError = true;
3545 }
3546
3547 if (OperType->hasExceptionSpec()) {
3548 if (CheckEquivalentExceptionSpec(
3549 PDiag(diag::err_incorrect_defaulted_exception_spec)
3550 << CXXMoveAssignment,
3551 PDiag(),
3552 ExceptionType, SourceLocation(),
3553 OperType, MD->getLocation())) {
3554 HadError = true;
3555 }
3556 } else if (First) {
3557 // We set the declaration to have the computed exception spec here.
3558 // We duplicate the one parameter type.
3559 EPI.RefQualifier = OperType->getRefQualifier();
3560 EPI.ExtInfo = OperType->getExtInfo();
3561 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3562 }
3563
3564 if (HadError) {
3565 MD->setInvalidDecl();
3566 return;
3567 }
3568
3569 if (ShouldDeleteMoveAssignmentOperator(MD)) {
3570 if (First) {
3571 MD->setDeletedAsWritten();
3572 } else {
3573 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3574 << CXXMoveAssignment;
3575 MD->setInvalidDecl();
3576 }
3577 }
3578}
3579
Sean Huntcb45a0f2011-05-12 22:46:25 +00003580void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3581 assert(DD->isExplicitlyDefaulted());
3582
3583 // Whether this was the first-declared instance of the destructor.
3584 bool First = DD == DD->getCanonicalDecl();
3585
3586 ImplicitExceptionSpecification Spec
3587 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3588 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3589 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3590 *ExceptionType = Context.getFunctionType(
3591 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3592
3593 if (DtorType->hasExceptionSpec()) {
3594 if (CheckEquivalentExceptionSpec(
3595 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003596 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003597 PDiag(),
3598 ExceptionType, SourceLocation(),
3599 DtorType, DD->getLocation())) {
3600 DD->setInvalidDecl();
3601 return;
3602 }
3603 } else if (First) {
3604 // We set the declaration to have the computed exception spec here.
3605 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003606 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003607 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3608 }
3609
3610 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003611 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003612 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003613 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003614 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003615 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003616 DD->setInvalidDecl();
3617 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003618 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003619}
3620
Sean Huntcdee3fe2011-05-11 22:34:38 +00003621bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3622 CXXRecordDecl *RD = CD->getParent();
3623 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003624 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003625 return false;
3626
Sean Hunt71a682f2011-05-18 03:41:58 +00003627 SourceLocation Loc = CD->getLocation();
3628
Sean Huntcdee3fe2011-05-11 22:34:38 +00003629 // Do access control from the constructor
3630 ContextRAII CtorContext(*this, CD);
3631
3632 bool Union = RD->isUnion();
3633 bool AllConst = true;
3634
Sean Huntcdee3fe2011-05-11 22:34:38 +00003635 // We do this because we should never actually use an anonymous
3636 // union's constructor.
3637 if (Union && RD->isAnonymousStructOrUnion())
3638 return false;
3639
3640 // FIXME: We should put some diagnostic logic right into this function.
3641
3642 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003643 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003644
3645 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3646 BE = RD->bases_end();
3647 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003648 // We'll handle this one later
3649 if (BI->isVirtual())
3650 continue;
3651
Sean Huntcdee3fe2011-05-11 22:34:38 +00003652 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3653 assert(BaseDecl && "base isn't a CXXRecordDecl");
3654
3655 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003656 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003657 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3658 if (BaseDtor->isDeleted())
3659 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003660 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003661 AR_accessible)
3662 return true;
3663
Sean Huntcdee3fe2011-05-11 22:34:38 +00003664 // -- any [direct base class either] has no default constructor or
3665 // overload resolution as applied to [its] default constructor
3666 // results in an ambiguity or in a function that is deleted or
3667 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003668 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3669 if (!BaseDefault || BaseDefault->isDeleted())
3670 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003671
Sean Huntb320e0c2011-06-10 03:50:41 +00003672 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3673 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003674 return true;
3675 }
3676
3677 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3678 BE = RD->vbases_end();
3679 BI != BE; ++BI) {
3680 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3681 assert(BaseDecl && "base isn't a CXXRecordDecl");
3682
3683 // -- any [virtual base class] has a type with a destructor that is
3684 // delete or inaccessible from the defaulted default constructor
3685 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3686 if (BaseDtor->isDeleted())
3687 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003688 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003689 AR_accessible)
3690 return true;
3691
3692 // -- any [virtual base class either] has no default constructor or
3693 // overload resolution as applied to [its] default constructor
3694 // results in an ambiguity or in a function that is deleted or
3695 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003696 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3697 if (!BaseDefault || BaseDefault->isDeleted())
3698 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003699
Sean Huntb320e0c2011-06-10 03:50:41 +00003700 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3701 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003702 return true;
3703 }
3704
3705 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3706 FE = RD->field_end();
3707 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003708 if (FI->isInvalidDecl())
3709 continue;
3710
Sean Huntcdee3fe2011-05-11 22:34:38 +00003711 QualType FieldType = Context.getBaseElementType(FI->getType());
3712 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003713
Sean Huntcdee3fe2011-05-11 22:34:38 +00003714 // -- any non-static data member with no brace-or-equal-initializer is of
3715 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003716 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003717 return true;
3718
3719 // -- X is a union and all its variant members are of const-qualified type
3720 // (or array thereof)
3721 if (Union && !FieldType.isConstQualified())
3722 AllConst = false;
3723
3724 if (FieldRecord) {
3725 // -- X is a union-like class that has a variant member with a non-trivial
3726 // default constructor
3727 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3728 return true;
3729
3730 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3731 if (FieldDtor->isDeleted())
3732 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003733 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003734 AR_accessible)
3735 return true;
3736
3737 // -- any non-variant non-static data member of const-qualified type (or
3738 // array thereof) with no brace-or-equal-initializer does not have a
3739 // user-provided default constructor
3740 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003741 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003742 !FieldRecord->hasUserProvidedDefaultConstructor())
3743 return true;
3744
3745 if (!Union && FieldRecord->isUnion() &&
3746 FieldRecord->isAnonymousStructOrUnion()) {
3747 // We're okay to reuse AllConst here since we only care about the
3748 // value otherwise if we're in a union.
3749 AllConst = true;
3750
3751 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3752 UE = FieldRecord->field_end();
3753 UI != UE; ++UI) {
3754 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3755 CXXRecordDecl *UnionFieldRecord =
3756 UnionFieldType->getAsCXXRecordDecl();
3757
3758 if (!UnionFieldType.isConstQualified())
3759 AllConst = false;
3760
3761 if (UnionFieldRecord &&
3762 !UnionFieldRecord->hasTrivialDefaultConstructor())
3763 return true;
3764 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003765
Sean Huntcdee3fe2011-05-11 22:34:38 +00003766 if (AllConst)
3767 return true;
3768
3769 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003770 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003771 continue;
3772 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003773
Richard Smith7a614d82011-06-11 17:19:42 +00003774 // -- any non-static data member with no brace-or-equal-initializer has
3775 // class type M (or array thereof) and either M has no default
3776 // constructor or overload resolution as applied to M's default
3777 // constructor results in an ambiguity or in a function that is deleted
3778 // or inaccessible from the defaulted default constructor.
3779 if (!FI->hasInClassInitializer()) {
3780 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3781 if (!FieldDefault || FieldDefault->isDeleted())
3782 return true;
3783 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3784 PDiag()) != AR_accessible)
3785 return true;
3786 }
3787 } else if (!Union && FieldType.isConstQualified() &&
3788 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003789 // -- any non-variant non-static data member of const-qualified type (or
3790 // array thereof) with no brace-or-equal-initializer does not have a
3791 // user-provided default constructor
3792 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003793 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003794 }
3795
3796 if (Union && AllConst)
3797 return true;
3798
3799 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003800}
3801
Sean Hunt49634cf2011-05-13 06:10:58 +00003802bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003803 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003804 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003805 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt49634cf2011-05-13 06:10:58 +00003806 return false;
3807
Sean Hunt71a682f2011-05-18 03:41:58 +00003808 SourceLocation Loc = CD->getLocation();
3809
Sean Hunt49634cf2011-05-13 06:10:58 +00003810 // Do access control from the constructor
3811 ContextRAII CtorContext(*this, CD);
3812
Sean Huntc530d172011-06-10 04:44:37 +00003813 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003814
Sean Hunt2b188082011-05-14 05:23:28 +00003815 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3816 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003817 unsigned ArgQuals =
3818 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3819 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003820
3821 // We do this because we should never actually use an anonymous
3822 // union's constructor.
3823 if (Union && RD->isAnonymousStructOrUnion())
3824 return false;
3825
3826 // FIXME: We should put some diagnostic logic right into this function.
3827
3828 // C++0x [class.copy]/11
3829 // A defaulted [copy] constructor for class X is defined as delete if X has:
3830
3831 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3832 BE = RD->bases_end();
3833 BI != BE; ++BI) {
3834 // We'll handle this one later
3835 if (BI->isVirtual())
3836 continue;
3837
3838 QualType BaseType = BI->getType();
3839 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3840 assert(BaseDecl && "base isn't a CXXRecordDecl");
3841
3842 // -- any [direct base class] of a type with a destructor that is deleted or
3843 // inaccessible from the defaulted constructor
3844 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3845 if (BaseDtor->isDeleted())
3846 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003847 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003848 AR_accessible)
3849 return true;
3850
3851 // -- a [direct base class] B that cannot be [copied] because overload
3852 // resolution, as applied to B's [copy] constructor, results in an
3853 // ambiguity or a function that is deleted or inaccessible from the
3854 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003855 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003856 if (!BaseCtor || BaseCtor->isDeleted())
3857 return true;
3858 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3859 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003860 return true;
3861 }
3862
3863 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3864 BE = RD->vbases_end();
3865 BI != BE; ++BI) {
3866 QualType BaseType = BI->getType();
3867 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3868 assert(BaseDecl && "base isn't a CXXRecordDecl");
3869
Sean Huntb320e0c2011-06-10 03:50:41 +00003870 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003871 // inaccessible from the defaulted constructor
3872 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3873 if (BaseDtor->isDeleted())
3874 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003875 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003876 AR_accessible)
3877 return true;
3878
3879 // -- a [virtual base class] B that cannot be [copied] because overload
3880 // resolution, as applied to B's [copy] constructor, results in an
3881 // ambiguity or a function that is deleted or inaccessible from the
3882 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003883 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003884 if (!BaseCtor || BaseCtor->isDeleted())
3885 return true;
3886 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3887 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003888 return true;
3889 }
3890
3891 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3892 FE = RD->field_end();
3893 FI != FE; ++FI) {
3894 QualType FieldType = Context.getBaseElementType(FI->getType());
3895
3896 // -- for a copy constructor, a non-static data member of rvalue reference
3897 // type
3898 if (FieldType->isRValueReferenceType())
3899 return true;
3900
3901 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3902
3903 if (FieldRecord) {
3904 // This is an anonymous union
3905 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3906 // Anonymous unions inside unions do not variant members create
3907 if (!Union) {
3908 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3909 UE = FieldRecord->field_end();
3910 UI != UE; ++UI) {
3911 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3912 CXXRecordDecl *UnionFieldRecord =
3913 UnionFieldType->getAsCXXRecordDecl();
3914
3915 // -- a variant member with a non-trivial [copy] constructor and X
3916 // is a union-like class
3917 if (UnionFieldRecord &&
3918 !UnionFieldRecord->hasTrivialCopyConstructor())
3919 return true;
3920 }
3921 }
3922
3923 // Don't try to initalize an anonymous union
3924 continue;
3925 } else {
3926 // -- a variant member with a non-trivial [copy] constructor and X is a
3927 // union-like class
3928 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3929 return true;
3930
3931 // -- any [non-static data member] of a type with a destructor that is
3932 // deleted or inaccessible from the defaulted constructor
3933 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3934 if (FieldDtor->isDeleted())
3935 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003936 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003937 AR_accessible)
3938 return true;
3939 }
Sean Huntc530d172011-06-10 04:44:37 +00003940
3941 // -- a [non-static data member of class type (or array thereof)] B that
3942 // cannot be [copied] because overload resolution, as applied to B's
3943 // [copy] constructor, results in an ambiguity or a function that is
3944 // deleted or inaccessible from the defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003945 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3946 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003947 if (!FieldCtor || FieldCtor->isDeleted())
3948 return true;
3949 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3950 PDiag()) != AR_accessible)
3951 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00003952 }
Sean Hunt49634cf2011-05-13 06:10:58 +00003953 }
3954
3955 return false;
3956}
3957
Sean Hunt7f410192011-05-14 05:23:24 +00003958bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3959 CXXRecordDecl *RD = MD->getParent();
3960 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003961 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00003962 return false;
3963
Sean Hunt71a682f2011-05-18 03:41:58 +00003964 SourceLocation Loc = MD->getLocation();
3965
Sean Hunt7f410192011-05-14 05:23:24 +00003966 // Do access control from the constructor
3967 ContextRAII MethodContext(*this, MD);
3968
3969 bool Union = RD->isUnion();
3970
Sean Hunt661c67a2011-06-21 23:42:56 +00003971 unsigned ArgQuals =
3972 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3973 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00003974
3975 // We do this because we should never actually use an anonymous
3976 // union's constructor.
3977 if (Union && RD->isAnonymousStructOrUnion())
3978 return false;
3979
Sean Hunt7f410192011-05-14 05:23:24 +00003980 // FIXME: We should put some diagnostic logic right into this function.
3981
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003982 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00003983 // A defaulted [copy] assignment operator for class X is defined as deleted
3984 // if X has:
3985
3986 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3987 BE = RD->bases_end();
3988 BI != BE; ++BI) {
3989 // We'll handle this one later
3990 if (BI->isVirtual())
3991 continue;
3992
3993 QualType BaseType = BI->getType();
3994 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3995 assert(BaseDecl && "base isn't a CXXRecordDecl");
3996
3997 // -- a [direct base class] B that cannot be [copied] because overload
3998 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00003999 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004000 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004001 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4002 0);
4003 if (!CopyOper || CopyOper->isDeleted())
4004 return true;
4005 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004006 return true;
4007 }
4008
4009 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4010 BE = RD->vbases_end();
4011 BI != BE; ++BI) {
4012 QualType BaseType = BI->getType();
4013 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4014 assert(BaseDecl && "base isn't a CXXRecordDecl");
4015
Sean Hunt7f410192011-05-14 05:23:24 +00004016 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004017 // resolution, as applied to B's [copy] assignment operator, results in
4018 // an ambiguity or a function that is deleted or inaccessible from the
4019 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004020 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4021 0);
4022 if (!CopyOper || CopyOper->isDeleted())
4023 return true;
4024 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004025 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004026 }
4027
4028 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4029 FE = RD->field_end();
4030 FI != FE; ++FI) {
4031 QualType FieldType = Context.getBaseElementType(FI->getType());
4032
4033 // -- a non-static data member of reference type
4034 if (FieldType->isReferenceType())
4035 return true;
4036
4037 // -- a non-static data member of const non-class type (or array thereof)
4038 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4039 return true;
4040
4041 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4042
4043 if (FieldRecord) {
4044 // This is an anonymous union
4045 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4046 // Anonymous unions inside unions do not variant members create
4047 if (!Union) {
4048 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4049 UE = FieldRecord->field_end();
4050 UI != UE; ++UI) {
4051 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4052 CXXRecordDecl *UnionFieldRecord =
4053 UnionFieldType->getAsCXXRecordDecl();
4054
4055 // -- a variant member with a non-trivial [copy] assignment operator
4056 // and X is a union-like class
4057 if (UnionFieldRecord &&
4058 !UnionFieldRecord->hasTrivialCopyAssignment())
4059 return true;
4060 }
4061 }
4062
4063 // Don't try to initalize an anonymous union
4064 continue;
4065 // -- a variant member with a non-trivial [copy] assignment operator
4066 // and X is a union-like class
4067 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4068 return true;
4069 }
Sean Hunt7f410192011-05-14 05:23:24 +00004070
Sean Hunt661c67a2011-06-21 23:42:56 +00004071 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4072 false, 0);
4073 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004074 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004075 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004076 return true;
4077 }
4078 }
4079
4080 return false;
4081}
4082
4083bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4084 CXXRecordDecl *RD = CD->getParent();
4085 assert(!RD->isDependentType() && "do deletion after instantiation");
4086 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4087 return false;
4088
4089 SourceLocation Loc = CD->getLocation();
4090
4091 // Do access control from the constructor
4092 ContextRAII CtorContext(*this, CD);
4093
4094 bool Union = RD->isUnion();
4095
4096 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4097 "copy assignment arg has no pointee type");
4098
4099 // We do this because we should never actually use an anonymous
4100 // union's constructor.
4101 if (Union && RD->isAnonymousStructOrUnion())
4102 return false;
4103
4104 // C++0x [class.copy]/11
4105 // A defaulted [move] constructor for class X is defined as deleted
4106 // if X has:
4107
4108 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4109 BE = RD->bases_end();
4110 BI != BE; ++BI) {
4111 // We'll handle this one later
4112 if (BI->isVirtual())
4113 continue;
4114
4115 QualType BaseType = BI->getType();
4116 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4117 assert(BaseDecl && "base isn't a CXXRecordDecl");
4118
4119 // -- any [direct base class] of a type with a destructor that is deleted or
4120 // inaccessible from the defaulted constructor
4121 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4122 if (BaseDtor->isDeleted())
4123 return true;
4124 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4125 AR_accessible)
4126 return true;
4127
4128 // -- a [direct base class] B that cannot be [moved] because overload
4129 // resolution, as applied to B's [move] constructor, results in an
4130 // ambiguity or a function that is deleted or inaccessible from the
4131 // defaulted constructor
4132 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4133 if (!BaseCtor || BaseCtor->isDeleted())
4134 return true;
4135 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4136 AR_accessible)
4137 return true;
4138
4139 // -- for a move constructor, a [direct base class] with a type that
4140 // does not have a move constructor and is not trivially copyable.
4141 // If the field isn't a record, it's always trivially copyable.
4142 // A moving constructor could be a copy constructor instead.
4143 if (!BaseCtor->isMoveConstructor() &&
4144 !BaseDecl->isTriviallyCopyable())
4145 return true;
4146 }
4147
4148 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4149 BE = RD->vbases_end();
4150 BI != BE; ++BI) {
4151 QualType BaseType = BI->getType();
4152 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4153 assert(BaseDecl && "base isn't a CXXRecordDecl");
4154
4155 // -- any [virtual base class] of a type with a destructor that is deleted
4156 // or inaccessible from the defaulted constructor
4157 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4158 if (BaseDtor->isDeleted())
4159 return true;
4160 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4161 AR_accessible)
4162 return true;
4163
4164 // -- a [virtual base class] B that cannot be [moved] because overload
4165 // resolution, as applied to B's [move] constructor, results in an
4166 // ambiguity or a function that is deleted or inaccessible from the
4167 // defaulted constructor
4168 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4169 if (!BaseCtor || BaseCtor->isDeleted())
4170 return true;
4171 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4172 AR_accessible)
4173 return true;
4174
4175 // -- for a move constructor, a [virtual base class] with a type that
4176 // does not have a move constructor and is not trivially copyable.
4177 // If the field isn't a record, it's always trivially copyable.
4178 // A moving constructor could be a copy constructor instead.
4179 if (!BaseCtor->isMoveConstructor() &&
4180 !BaseDecl->isTriviallyCopyable())
4181 return true;
4182 }
4183
4184 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4185 FE = RD->field_end();
4186 FI != FE; ++FI) {
4187 QualType FieldType = Context.getBaseElementType(FI->getType());
4188
4189 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4190 // This is an anonymous union
4191 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4192 // Anonymous unions inside unions do not variant members create
4193 if (!Union) {
4194 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4195 UE = FieldRecord->field_end();
4196 UI != UE; ++UI) {
4197 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4198 CXXRecordDecl *UnionFieldRecord =
4199 UnionFieldType->getAsCXXRecordDecl();
4200
4201 // -- a variant member with a non-trivial [move] constructor and X
4202 // is a union-like class
4203 if (UnionFieldRecord &&
4204 !UnionFieldRecord->hasTrivialMoveConstructor())
4205 return true;
4206 }
4207 }
4208
4209 // Don't try to initalize an anonymous union
4210 continue;
4211 } else {
4212 // -- a variant member with a non-trivial [move] constructor and X is a
4213 // union-like class
4214 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4215 return true;
4216
4217 // -- any [non-static data member] of a type with a destructor that is
4218 // deleted or inaccessible from the defaulted constructor
4219 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4220 if (FieldDtor->isDeleted())
4221 return true;
4222 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4223 AR_accessible)
4224 return true;
4225 }
4226
4227 // -- a [non-static data member of class type (or array thereof)] B that
4228 // cannot be [moved] because overload resolution, as applied to B's
4229 // [move] constructor, results in an ambiguity or a function that is
4230 // deleted or inaccessible from the defaulted constructor
4231 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4232 if (!FieldCtor || FieldCtor->isDeleted())
4233 return true;
4234 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4235 PDiag()) != AR_accessible)
4236 return true;
4237
4238 // -- for a move constructor, a [non-static data member] with a type that
4239 // does not have a move constructor and is not trivially copyable.
4240 // If the field isn't a record, it's always trivially copyable.
4241 // A moving constructor could be a copy constructor instead.
4242 if (!FieldCtor->isMoveConstructor() &&
4243 !FieldRecord->isTriviallyCopyable())
4244 return true;
4245 }
4246 }
4247
4248 return false;
4249}
4250
4251bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4252 CXXRecordDecl *RD = MD->getParent();
4253 assert(!RD->isDependentType() && "do deletion after instantiation");
4254 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4255 return false;
4256
4257 SourceLocation Loc = MD->getLocation();
4258
4259 // Do access control from the constructor
4260 ContextRAII MethodContext(*this, MD);
4261
4262 bool Union = RD->isUnion();
4263
4264 // We do this because we should never actually use an anonymous
4265 // union's constructor.
4266 if (Union && RD->isAnonymousStructOrUnion())
4267 return false;
4268
4269 // C++0x [class.copy]/20
4270 // A defaulted [move] assignment operator for class X is defined as deleted
4271 // if X has:
4272
4273 // -- for the move constructor, [...] any direct or indirect virtual base
4274 // class.
4275 if (RD->getNumVBases() != 0)
4276 return true;
4277
4278 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4279 BE = RD->bases_end();
4280 BI != BE; ++BI) {
4281
4282 QualType BaseType = BI->getType();
4283 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4284 assert(BaseDecl && "base isn't a CXXRecordDecl");
4285
4286 // -- a [direct base class] B that cannot be [moved] because overload
4287 // resolution, as applied to B's [move] assignment operator, results in
4288 // an ambiguity or a function that is deleted or inaccessible from the
4289 // assignment operator
4290 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4291 if (!MoveOper || MoveOper->isDeleted())
4292 return true;
4293 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4294 return true;
4295
4296 // -- for the move assignment operator, a [direct base class] with a type
4297 // that does not have a move assignment operator and is not trivially
4298 // copyable.
4299 if (!MoveOper->isMoveAssignmentOperator() &&
4300 !BaseDecl->isTriviallyCopyable())
4301 return true;
4302 }
4303
4304 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4305 FE = RD->field_end();
4306 FI != FE; ++FI) {
4307 QualType FieldType = Context.getBaseElementType(FI->getType());
4308
4309 // -- a non-static data member of reference type
4310 if (FieldType->isReferenceType())
4311 return true;
4312
4313 // -- a non-static data member of const non-class type (or array thereof)
4314 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4315 return true;
4316
4317 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4318
4319 if (FieldRecord) {
4320 // This is an anonymous union
4321 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4322 // Anonymous unions inside unions do not variant members create
4323 if (!Union) {
4324 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4325 UE = FieldRecord->field_end();
4326 UI != UE; ++UI) {
4327 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4328 CXXRecordDecl *UnionFieldRecord =
4329 UnionFieldType->getAsCXXRecordDecl();
4330
4331 // -- a variant member with a non-trivial [move] assignment operator
4332 // and X is a union-like class
4333 if (UnionFieldRecord &&
4334 !UnionFieldRecord->hasTrivialMoveAssignment())
4335 return true;
4336 }
4337 }
4338
4339 // Don't try to initalize an anonymous union
4340 continue;
4341 // -- a variant member with a non-trivial [move] assignment operator
4342 // and X is a union-like class
4343 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4344 return true;
4345 }
4346
4347 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4348 if (!MoveOper || MoveOper->isDeleted())
4349 return true;
4350 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4351 return true;
4352
4353 // -- for the move assignment operator, a [non-static data member] with a
4354 // type that does not have a move assignment operator and is not
4355 // trivially copyable.
4356 if (!MoveOper->isMoveAssignmentOperator() &&
4357 !FieldRecord->isTriviallyCopyable())
4358 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004359 }
Sean Hunt7f410192011-05-14 05:23:24 +00004360 }
4361
4362 return false;
4363}
4364
Sean Huntcb45a0f2011-05-12 22:46:25 +00004365bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4366 CXXRecordDecl *RD = DD->getParent();
4367 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004368 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004369 return false;
4370
Sean Hunt71a682f2011-05-18 03:41:58 +00004371 SourceLocation Loc = DD->getLocation();
4372
Sean Huntcb45a0f2011-05-12 22:46:25 +00004373 // Do access control from the destructor
4374 ContextRAII CtorContext(*this, DD);
4375
4376 bool Union = RD->isUnion();
4377
Sean Hunt49634cf2011-05-13 06:10:58 +00004378 // We do this because we should never actually use an anonymous
4379 // union's destructor.
4380 if (Union && RD->isAnonymousStructOrUnion())
4381 return false;
4382
Sean Huntcb45a0f2011-05-12 22:46:25 +00004383 // C++0x [class.dtor]p5
4384 // A defaulted destructor for a class X is defined as deleted if:
4385 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4386 BE = RD->bases_end();
4387 BI != BE; ++BI) {
4388 // We'll handle this one later
4389 if (BI->isVirtual())
4390 continue;
4391
4392 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4393 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4394 assert(BaseDtor && "base has no destructor");
4395
4396 // -- any direct or virtual base class has a deleted destructor or
4397 // a destructor that is inaccessible from the defaulted destructor
4398 if (BaseDtor->isDeleted())
4399 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004400 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004401 AR_accessible)
4402 return true;
4403 }
4404
4405 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4406 BE = RD->vbases_end();
4407 BI != BE; ++BI) {
4408 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4409 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4410 assert(BaseDtor && "base has no destructor");
4411
4412 // -- any direct or virtual base class has a deleted destructor or
4413 // a destructor that is inaccessible from the defaulted destructor
4414 if (BaseDtor->isDeleted())
4415 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004416 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004417 AR_accessible)
4418 return true;
4419 }
4420
4421 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4422 FE = RD->field_end();
4423 FI != FE; ++FI) {
4424 QualType FieldType = Context.getBaseElementType(FI->getType());
4425 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4426 if (FieldRecord) {
4427 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4428 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4429 UE = FieldRecord->field_end();
4430 UI != UE; ++UI) {
4431 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4432 CXXRecordDecl *UnionFieldRecord =
4433 UnionFieldType->getAsCXXRecordDecl();
4434
4435 // -- X is a union-like class that has a variant member with a non-
4436 // trivial destructor.
4437 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4438 return true;
4439 }
4440 // Technically we are supposed to do this next check unconditionally.
4441 // But that makes absolutely no sense.
4442 } else {
4443 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4444
4445 // -- any of the non-static data members has class type M (or array
4446 // thereof) and M has a deleted destructor or a destructor that is
4447 // inaccessible from the defaulted destructor
4448 if (FieldDtor->isDeleted())
4449 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004450 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004451 AR_accessible)
4452 return true;
4453
4454 // -- X is a union-like class that has a variant member with a non-
4455 // trivial destructor.
4456 if (Union && !FieldDtor->isTrivial())
4457 return true;
4458 }
4459 }
4460 }
4461
4462 if (DD->isVirtual()) {
4463 FunctionDecl *OperatorDelete = 0;
4464 DeclarationName Name =
4465 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004466 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004467 false))
4468 return true;
4469 }
4470
4471
4472 return false;
4473}
4474
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004475/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004476namespace {
4477 struct FindHiddenVirtualMethodData {
4478 Sema *S;
4479 CXXMethodDecl *Method;
4480 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004481 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004482 };
4483}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004484
4485/// \brief Member lookup function that determines whether a given C++
4486/// method overloads virtual methods in a base class without overriding any,
4487/// to be used with CXXRecordDecl::lookupInBases().
4488static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4489 CXXBasePath &Path,
4490 void *UserData) {
4491 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4492
4493 FindHiddenVirtualMethodData &Data
4494 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4495
4496 DeclarationName Name = Data.Method->getDeclName();
4497 assert(Name.getNameKind() == DeclarationName::Identifier);
4498
4499 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004500 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004501 for (Path.Decls = BaseRecord->lookup(Name);
4502 Path.Decls.first != Path.Decls.second;
4503 ++Path.Decls.first) {
4504 NamedDecl *D = *Path.Decls.first;
4505 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004506 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004507 foundSameNameMethod = true;
4508 // Interested only in hidden virtual methods.
4509 if (!MD->isVirtual())
4510 continue;
4511 // If the method we are checking overrides a method from its base
4512 // don't warn about the other overloaded methods.
4513 if (!Data.S->IsOverload(Data.Method, MD, false))
4514 return true;
4515 // Collect the overload only if its hidden.
4516 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4517 overloadedMethods.push_back(MD);
4518 }
4519 }
4520
4521 if (foundSameNameMethod)
4522 Data.OverloadedMethods.append(overloadedMethods.begin(),
4523 overloadedMethods.end());
4524 return foundSameNameMethod;
4525}
4526
4527/// \brief See if a method overloads virtual methods in a base class without
4528/// overriding any.
4529void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4530 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4531 MD->getLocation()) == Diagnostic::Ignored)
4532 return;
4533 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4534 return;
4535
4536 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4537 /*bool RecordPaths=*/false,
4538 /*bool DetectVirtual=*/false);
4539 FindHiddenVirtualMethodData Data;
4540 Data.Method = MD;
4541 Data.S = this;
4542
4543 // Keep the base methods that were overriden or introduced in the subclass
4544 // by 'using' in a set. A base method not in this set is hidden.
4545 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4546 res.first != res.second; ++res.first) {
4547 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4548 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4549 E = MD->end_overridden_methods();
4550 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004551 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004552 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4553 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004554 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004555 }
4556
4557 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4558 !Data.OverloadedMethods.empty()) {
4559 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4560 << MD << (Data.OverloadedMethods.size() > 1);
4561
4562 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4563 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4564 Diag(overloadedMD->getLocation(),
4565 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4566 }
4567 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004568}
4569
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004570void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004571 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004572 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004573 SourceLocation RBrac,
4574 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004575 if (!TagDecl)
4576 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004577
Douglas Gregor42af25f2009-05-11 19:58:34 +00004578 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004579
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004580 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004581 // strict aliasing violation!
4582 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004583 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004584
Douglas Gregor23c94db2010-07-02 17:43:08 +00004585 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004586 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004587}
4588
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004589/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4590/// special functions, such as the default constructor, copy
4591/// constructor, or destructor, to the given C++ class (C++
4592/// [special]p1). This routine can only be executed just before the
4593/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004594void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004595 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004596 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004597
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004598 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004599 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004600
Douglas Gregora376d102010-07-02 21:50:04 +00004601 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4602 ++ASTContext::NumImplicitCopyAssignmentOperators;
4603
4604 // If we have a dynamic class, then the copy assignment operator may be
4605 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4606 // it shows up in the right place in the vtable and that we diagnose
4607 // problems with the implicit exception specification.
4608 if (ClassDecl->isDynamicClass())
4609 DeclareImplicitCopyAssignment(ClassDecl);
4610 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004611
Douglas Gregor4923aa22010-07-02 20:37:36 +00004612 if (!ClassDecl->hasUserDeclaredDestructor()) {
4613 ++ASTContext::NumImplicitDestructors;
4614
4615 // If we have a dynamic class, then the destructor may be virtual, so we
4616 // have to declare the destructor immediately. This ensures that, e.g., it
4617 // shows up in the right place in the vtable and that we diagnose problems
4618 // with the implicit exception specification.
4619 if (ClassDecl->isDynamicClass())
4620 DeclareImplicitDestructor(ClassDecl);
4621 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004622}
4623
Francois Pichet8387e2a2011-04-22 22:18:13 +00004624void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4625 if (!D)
4626 return;
4627
4628 int NumParamList = D->getNumTemplateParameterLists();
4629 for (int i = 0; i < NumParamList; i++) {
4630 TemplateParameterList* Params = D->getTemplateParameterList(i);
4631 for (TemplateParameterList::iterator Param = Params->begin(),
4632 ParamEnd = Params->end();
4633 Param != ParamEnd; ++Param) {
4634 NamedDecl *Named = cast<NamedDecl>(*Param);
4635 if (Named->getDeclName()) {
4636 S->AddDecl(Named);
4637 IdResolver.AddDecl(Named);
4638 }
4639 }
4640 }
4641}
4642
John McCalld226f652010-08-21 09:40:31 +00004643void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004644 if (!D)
4645 return;
4646
4647 TemplateParameterList *Params = 0;
4648 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4649 Params = Template->getTemplateParameters();
4650 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4651 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4652 Params = PartialSpec->getTemplateParameters();
4653 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004654 return;
4655
Douglas Gregor6569d682009-05-27 23:11:45 +00004656 for (TemplateParameterList::iterator Param = Params->begin(),
4657 ParamEnd = Params->end();
4658 Param != ParamEnd; ++Param) {
4659 NamedDecl *Named = cast<NamedDecl>(*Param);
4660 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004661 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004662 IdResolver.AddDecl(Named);
4663 }
4664 }
4665}
4666
John McCalld226f652010-08-21 09:40:31 +00004667void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004668 if (!RecordD) return;
4669 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004670 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004671 PushDeclContext(S, Record);
4672}
4673
John McCalld226f652010-08-21 09:40:31 +00004674void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004675 if (!RecordD) return;
4676 PopDeclContext();
4677}
4678
Douglas Gregor72b505b2008-12-16 21:30:33 +00004679/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4680/// parsing a top-level (non-nested) C++ class, and we are now
4681/// parsing those parts of the given Method declaration that could
4682/// not be parsed earlier (C++ [class.mem]p2), such as default
4683/// arguments. This action should enter the scope of the given
4684/// Method declaration as if we had just parsed the qualified method
4685/// name. However, it should not bring the parameters into scope;
4686/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004687void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004688}
4689
4690/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4691/// C++ method declaration. We're (re-)introducing the given
4692/// function parameter into scope for use in parsing later parts of
4693/// the method declaration. For example, we could see an
4694/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004695void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004696 if (!ParamD)
4697 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004698
John McCalld226f652010-08-21 09:40:31 +00004699 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004700
4701 // If this parameter has an unparsed default argument, clear it out
4702 // to make way for the parsed default argument.
4703 if (Param->hasUnparsedDefaultArg())
4704 Param->setDefaultArg(0);
4705
John McCalld226f652010-08-21 09:40:31 +00004706 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004707 if (Param->getDeclName())
4708 IdResolver.AddDecl(Param);
4709}
4710
4711/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4712/// processing the delayed method declaration for Method. The method
4713/// declaration is now considered finished. There may be a separate
4714/// ActOnStartOfFunctionDef action later (not necessarily
4715/// immediately!) for this method, if it was also defined inside the
4716/// class body.
John McCalld226f652010-08-21 09:40:31 +00004717void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004718 if (!MethodD)
4719 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004720
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004721 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004722
John McCalld226f652010-08-21 09:40:31 +00004723 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004724
4725 // Now that we have our default arguments, check the constructor
4726 // again. It could produce additional diagnostics or affect whether
4727 // the class has implicitly-declared destructors, among other
4728 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004729 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4730 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004731
4732 // Check the default arguments, which we may have added.
4733 if (!Method->isInvalidDecl())
4734 CheckCXXDefaultArguments(Method);
4735}
4736
Douglas Gregor42a552f2008-11-05 20:51:48 +00004737/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004738/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004739/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004740/// emit diagnostics and set the invalid bit to true. In any case, the type
4741/// will be updated to reflect a well-formed type for the constructor and
4742/// returned.
4743QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004744 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004745 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004746
4747 // C++ [class.ctor]p3:
4748 // A constructor shall not be virtual (10.3) or static (9.4). A
4749 // constructor can be invoked for a const, volatile or const
4750 // volatile object. A constructor shall not be declared const,
4751 // volatile, or const volatile (9.3.2).
4752 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004753 if (!D.isInvalidType())
4754 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4755 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4756 << SourceRange(D.getIdentifierLoc());
4757 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004758 }
John McCalld931b082010-08-26 03:08:43 +00004759 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004760 if (!D.isInvalidType())
4761 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4762 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4763 << SourceRange(D.getIdentifierLoc());
4764 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004765 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004766 }
Mike Stump1eb44332009-09-09 15:08:12 +00004767
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004768 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004769 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004770 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004771 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4772 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004773 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004774 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4775 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004776 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004777 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4778 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004779 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004780 }
Mike Stump1eb44332009-09-09 15:08:12 +00004781
Douglas Gregorc938c162011-01-26 05:01:58 +00004782 // C++0x [class.ctor]p4:
4783 // A constructor shall not be declared with a ref-qualifier.
4784 if (FTI.hasRefQualifier()) {
4785 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4786 << FTI.RefQualifierIsLValueRef
4787 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4788 D.setInvalidType();
4789 }
4790
Douglas Gregor42a552f2008-11-05 20:51:48 +00004791 // Rebuild the function type "R" without any type qualifiers (in
4792 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004793 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004794 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004795 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4796 return R;
4797
4798 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4799 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004800 EPI.RefQualifier = RQ_None;
4801
Chris Lattner65401802009-04-25 08:28:21 +00004802 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004803 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004804}
4805
Douglas Gregor72b505b2008-12-16 21:30:33 +00004806/// CheckConstructor - Checks a fully-formed constructor for
4807/// well-formedness, issuing any diagnostics required. Returns true if
4808/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004809void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004810 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004811 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4812 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004813 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004814
4815 // C++ [class.copy]p3:
4816 // A declaration of a constructor for a class X is ill-formed if
4817 // its first parameter is of type (optionally cv-qualified) X and
4818 // either there are no other parameters or else all other
4819 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004820 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004821 ((Constructor->getNumParams() == 1) ||
4822 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004823 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4824 Constructor->getTemplateSpecializationKind()
4825 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004826 QualType ParamType = Constructor->getParamDecl(0)->getType();
4827 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4828 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004829 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004830 const char *ConstRef
4831 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4832 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004833 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004834 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004835
4836 // FIXME: Rather that making the constructor invalid, we should endeavor
4837 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004838 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004839 }
4840 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004841}
4842
John McCall15442822010-08-04 01:04:25 +00004843/// CheckDestructor - Checks a fully-formed destructor definition for
4844/// well-formedness, issuing any diagnostics required. Returns true
4845/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004846bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004847 CXXRecordDecl *RD = Destructor->getParent();
4848
4849 if (Destructor->isVirtual()) {
4850 SourceLocation Loc;
4851
4852 if (!Destructor->isImplicit())
4853 Loc = Destructor->getLocation();
4854 else
4855 Loc = RD->getLocation();
4856
4857 // If we have a virtual destructor, look up the deallocation function
4858 FunctionDecl *OperatorDelete = 0;
4859 DeclarationName Name =
4860 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004861 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004862 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004863
4864 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004865
4866 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004867 }
Anders Carlsson37909802009-11-30 21:24:50 +00004868
4869 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004870}
4871
Mike Stump1eb44332009-09-09 15:08:12 +00004872static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004873FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4874 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4875 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004876 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004877}
4878
Douglas Gregor42a552f2008-11-05 20:51:48 +00004879/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4880/// the well-formednes of the destructor declarator @p D with type @p
4881/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004882/// emit diagnostics and set the declarator to invalid. Even if this happens,
4883/// will be updated to reflect a well-formed type for the destructor and
4884/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004885QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004886 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004887 // C++ [class.dtor]p1:
4888 // [...] A typedef-name that names a class is a class-name
4889 // (7.1.3); however, a typedef-name that names a class shall not
4890 // be used as the identifier in the declarator for a destructor
4891 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004892 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004893 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004894 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004895 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004896 else if (const TemplateSpecializationType *TST =
4897 DeclaratorType->getAs<TemplateSpecializationType>())
4898 if (TST->isTypeAlias())
4899 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4900 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004901
4902 // C++ [class.dtor]p2:
4903 // A destructor is used to destroy objects of its class type. A
4904 // destructor takes no parameters, and no return type can be
4905 // specified for it (not even void). The address of a destructor
4906 // shall not be taken. A destructor shall not be static. A
4907 // destructor can be invoked for a const, volatile or const
4908 // volatile object. A destructor shall not be declared const,
4909 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004910 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004911 if (!D.isInvalidType())
4912 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4913 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004914 << SourceRange(D.getIdentifierLoc())
4915 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4916
John McCalld931b082010-08-26 03:08:43 +00004917 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004918 }
Chris Lattner65401802009-04-25 08:28:21 +00004919 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004920 // Destructors don't have return types, but the parser will
4921 // happily parse something like:
4922 //
4923 // class X {
4924 // float ~X();
4925 // };
4926 //
4927 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004928 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4929 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4930 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004931 }
Mike Stump1eb44332009-09-09 15:08:12 +00004932
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004933 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004934 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004935 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004936 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4937 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004938 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004939 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4940 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004941 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004942 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4943 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00004944 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004945 }
4946
Douglas Gregorc938c162011-01-26 05:01:58 +00004947 // C++0x [class.dtor]p2:
4948 // A destructor shall not be declared with a ref-qualifier.
4949 if (FTI.hasRefQualifier()) {
4950 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4951 << FTI.RefQualifierIsLValueRef
4952 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4953 D.setInvalidType();
4954 }
4955
Douglas Gregor42a552f2008-11-05 20:51:48 +00004956 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004957 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004958 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4959
4960 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00004961 FTI.freeArgs();
4962 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004963 }
4964
Mike Stump1eb44332009-09-09 15:08:12 +00004965 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00004966 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004967 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00004968 D.setInvalidType();
4969 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00004970
4971 // Rebuild the function type "R" without any type qualifiers or
4972 // parameters (in case any of the errors above fired) and with
4973 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00004974 // types.
John McCalle23cf432010-12-14 08:05:40 +00004975 if (!D.isInvalidType())
4976 return R;
4977
Douglas Gregord92ec472010-07-01 05:10:53 +00004978 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004979 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4980 EPI.Variadic = false;
4981 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004982 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00004983 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004984}
4985
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004986/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4987/// well-formednes of the conversion function declarator @p D with
4988/// type @p R. If there are any errors in the declarator, this routine
4989/// will emit diagnostics and return true. Otherwise, it will return
4990/// false. Either way, the type @p R will be updated to reflect a
4991/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00004992void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00004993 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004994 // C++ [class.conv.fct]p1:
4995 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00004996 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00004997 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00004998 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00004999 if (!D.isInvalidType())
5000 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5001 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5002 << SourceRange(D.getIdentifierLoc());
5003 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005004 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005005 }
John McCalla3f81372010-04-13 00:04:31 +00005006
5007 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5008
Chris Lattner6e475012009-04-25 08:35:12 +00005009 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005010 // Conversion functions don't have return types, but the parser will
5011 // happily parse something like:
5012 //
5013 // class X {
5014 // float operator bool();
5015 // };
5016 //
5017 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005018 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5019 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5020 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005021 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005022 }
5023
John McCalla3f81372010-04-13 00:04:31 +00005024 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5025
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005026 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005027 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005028 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5029
5030 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005031 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005032 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005033 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005034 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005035 D.setInvalidType();
5036 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005037
John McCalla3f81372010-04-13 00:04:31 +00005038 // Diagnose "&operator bool()" and other such nonsense. This
5039 // is actually a gcc extension which we don't support.
5040 if (Proto->getResultType() != ConvType) {
5041 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5042 << Proto->getResultType();
5043 D.setInvalidType();
5044 ConvType = Proto->getResultType();
5045 }
5046
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005047 // C++ [class.conv.fct]p4:
5048 // The conversion-type-id shall not represent a function type nor
5049 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005050 if (ConvType->isArrayType()) {
5051 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5052 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005053 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005054 } else if (ConvType->isFunctionType()) {
5055 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5056 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005057 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005058 }
5059
5060 // Rebuild the function type "R" without any parameters (in case any
5061 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005062 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005063 if (D.isInvalidType())
5064 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005065
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005066 // C++0x explicit conversion operators.
5067 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00005068 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005069 diag::warn_explicit_conversion_functions)
5070 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005071}
5072
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005073/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5074/// the declaration of the given C++ conversion function. This routine
5075/// is responsible for recording the conversion function in the C++
5076/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005077Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005078 assert(Conversion && "Expected to receive a conversion function declaration");
5079
Douglas Gregor9d350972008-12-12 08:25:50 +00005080 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005081
5082 // Make sure we aren't redeclaring the conversion function.
5083 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005084
5085 // C++ [class.conv.fct]p1:
5086 // [...] A conversion function is never used to convert a
5087 // (possibly cv-qualified) object to the (possibly cv-qualified)
5088 // same object type (or a reference to it), to a (possibly
5089 // cv-qualified) base class of that type (or a reference to it),
5090 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005091 // FIXME: Suppress this warning if the conversion function ends up being a
5092 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005093 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005094 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005095 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005096 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005097 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5098 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005099 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005100 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005101 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5102 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005103 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005104 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005105 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005106 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005107 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005108 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005109 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005110 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005111 }
5112
Douglas Gregore80622f2010-09-29 04:25:11 +00005113 if (FunctionTemplateDecl *ConversionTemplate
5114 = Conversion->getDescribedFunctionTemplate())
5115 return ConversionTemplate;
5116
John McCalld226f652010-08-21 09:40:31 +00005117 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005118}
5119
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005120//===----------------------------------------------------------------------===//
5121// Namespace Handling
5122//===----------------------------------------------------------------------===//
5123
John McCallea318642010-08-26 09:15:37 +00005124
5125
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005126/// ActOnStartNamespaceDef - This is called at the start of a namespace
5127/// definition.
John McCalld226f652010-08-21 09:40:31 +00005128Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005129 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005130 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005131 SourceLocation IdentLoc,
5132 IdentifierInfo *II,
5133 SourceLocation LBrace,
5134 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005135 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5136 // For anonymous namespace, take the location of the left brace.
5137 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00005138 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005139 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005140 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005141
5142 Scope *DeclRegionScope = NamespcScope->getParent();
5143
Anders Carlsson2a3503d2010-02-07 01:09:23 +00005144 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5145
John McCall90f14502010-12-10 02:59:44 +00005146 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5147 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005148
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005149 if (II) {
5150 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005151 // The identifier in an original-namespace-definition shall not
5152 // have been previously defined in the declarative region in
5153 // which the original-namespace-definition appears. The
5154 // identifier in an original-namespace-definition is the name of
5155 // the namespace. Subsequently in that declarative region, it is
5156 // treated as an original-namespace-name.
5157 //
5158 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005159 // look through using directives, just look for any ordinary names.
5160
5161 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5162 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5163 Decl::IDNS_Namespace;
5164 NamedDecl *PrevDecl = 0;
5165 for (DeclContext::lookup_result R
5166 = CurContext->getRedeclContext()->lookup(II);
5167 R.first != R.second; ++R.first) {
5168 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5169 PrevDecl = *R.first;
5170 break;
5171 }
5172 }
5173
Douglas Gregor44b43212008-12-11 16:49:14 +00005174 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5175 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005176 if (Namespc->isInline() != OrigNS->isInline()) {
5177 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005178 if (OrigNS->isInline()) {
5179 // The user probably just forgot the 'inline', so suggest that it
5180 // be added back.
5181 Diag(Namespc->getLocation(),
5182 diag::warn_inline_namespace_reopened_noninline)
5183 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5184 } else {
5185 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5186 << Namespc->isInline();
5187 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005188 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005189
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005190 // Recover by ignoring the new namespace's inline status.
5191 Namespc->setInline(OrigNS->isInline());
5192 }
5193
Douglas Gregor44b43212008-12-11 16:49:14 +00005194 // Attach this namespace decl to the chain of extended namespace
5195 // definitions.
5196 OrigNS->setNextNamespace(Namespc);
5197 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005198
Mike Stump1eb44332009-09-09 15:08:12 +00005199 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00005200 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00005201 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00005202 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005203 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005204 } else if (PrevDecl) {
5205 // This is an invalid name redefinition.
5206 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5207 << Namespc->getDeclName();
5208 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5209 Namespc->setInvalidDecl();
5210 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005211 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005212 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005213 // This is the first "real" definition of the namespace "std", so update
5214 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005215 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005216 // We had already defined a dummy namespace "std". Link this new
5217 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005218 StdNS->setNextNamespace(Namespc);
5219 StdNS->setLocation(IdentLoc);
5220 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005221 }
5222
5223 // Make our StdNamespace cache point at the first real definition of the
5224 // "std" namespace.
5225 StdNamespace = Namespc;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005226
5227 // Add this instance of "std" to the set of known namespaces
5228 KnownNamespaces[Namespc] = false;
5229 } else if (!Namespc->isInline()) {
5230 // Since this is an "original" namespace, add it to the known set of
5231 // namespaces if it is not an inline namespace.
5232 KnownNamespaces[Namespc] = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005233 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005234
5235 PushOnScopeChains(Namespc, DeclRegionScope);
5236 } else {
John McCall9aeed322009-10-01 00:25:31 +00005237 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00005238 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00005239
5240 // Link the anonymous namespace into its parent.
5241 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005242 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005243 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5244 PrevDecl = TU->getAnonymousNamespace();
5245 TU->setAnonymousNamespace(Namespc);
5246 } else {
5247 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5248 PrevDecl = ND->getAnonymousNamespace();
5249 ND->setAnonymousNamespace(Namespc);
5250 }
5251
5252 // Link the anonymous namespace with its previous declaration.
5253 if (PrevDecl) {
5254 assert(PrevDecl->isAnonymousNamespace());
5255 assert(!PrevDecl->getNextNamespace());
5256 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5257 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005258
5259 if (Namespc->isInline() != PrevDecl->isInline()) {
5260 // inline-ness must match
5261 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5262 << Namespc->isInline();
5263 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5264 Namespc->setInvalidDecl();
5265 // Recover by ignoring the new namespace's inline status.
5266 Namespc->setInline(PrevDecl->isInline());
5267 }
John McCall5fdd7642009-12-16 02:06:49 +00005268 }
John McCall9aeed322009-10-01 00:25:31 +00005269
Douglas Gregora4181472010-03-24 00:46:35 +00005270 CurContext->addDecl(Namespc);
5271
John McCall9aeed322009-10-01 00:25:31 +00005272 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5273 // behaves as if it were replaced by
5274 // namespace unique { /* empty body */ }
5275 // using namespace unique;
5276 // namespace unique { namespace-body }
5277 // where all occurrences of 'unique' in a translation unit are
5278 // replaced by the same identifier and this identifier differs
5279 // from all other identifiers in the entire program.
5280
5281 // We just create the namespace with an empty name and then add an
5282 // implicit using declaration, just like the standard suggests.
5283 //
5284 // CodeGen enforces the "universally unique" aspect by giving all
5285 // declarations semantically contained within an anonymous
5286 // namespace internal linkage.
5287
John McCall5fdd7642009-12-16 02:06:49 +00005288 if (!PrevDecl) {
5289 UsingDirectiveDecl* UD
5290 = UsingDirectiveDecl::Create(Context, CurContext,
5291 /* 'using' */ LBrace,
5292 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005293 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005294 /* identifier */ SourceLocation(),
5295 Namespc,
5296 /* Ancestor */ CurContext);
5297 UD->setImplicit();
5298 CurContext->addDecl(UD);
5299 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005300 }
5301
5302 // Although we could have an invalid decl (i.e. the namespace name is a
5303 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005304 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5305 // for the namespace has the declarations that showed up in that particular
5306 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005307 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005308 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005309}
5310
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005311/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5312/// is a namespace alias, returns the namespace it points to.
5313static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5314 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5315 return AD->getNamespace();
5316 return dyn_cast_or_null<NamespaceDecl>(D);
5317}
5318
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005319/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5320/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005321void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005322 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5323 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005324 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005325 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005326 if (Namespc->hasAttr<VisibilityAttr>())
5327 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005328}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005329
John McCall384aff82010-08-25 07:42:41 +00005330CXXRecordDecl *Sema::getStdBadAlloc() const {
5331 return cast_or_null<CXXRecordDecl>(
5332 StdBadAlloc.get(Context.getExternalSource()));
5333}
5334
5335NamespaceDecl *Sema::getStdNamespace() const {
5336 return cast_or_null<NamespaceDecl>(
5337 StdNamespace.get(Context.getExternalSource()));
5338}
5339
Douglas Gregor66992202010-06-29 17:53:46 +00005340/// \brief Retrieve the special "std" namespace, which may require us to
5341/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005342NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005343 if (!StdNamespace) {
5344 // The "std" namespace has not yet been defined, so build one implicitly.
5345 StdNamespace = NamespaceDecl::Create(Context,
5346 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005347 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00005348 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005349 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005350 }
5351
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005352 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005353}
5354
Douglas Gregor9172aa62011-03-26 22:25:30 +00005355/// \brief Determine whether a using statement is in a context where it will be
5356/// apply in all contexts.
5357static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5358 switch (CurContext->getDeclKind()) {
5359 case Decl::TranslationUnit:
5360 return true;
5361 case Decl::LinkageSpec:
5362 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5363 default:
5364 return false;
5365 }
5366}
5367
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005368static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5369 CXXScopeSpec &SS,
5370 SourceLocation IdentLoc,
5371 IdentifierInfo *Ident) {
5372 R.clear();
5373 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5374 R.getLookupKind(), Sc, &SS, NULL,
5375 false, S.CTC_NoKeywords, NULL)) {
5376 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5377 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5378 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5379 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5380 if (DeclContext *DC = S.computeDeclContext(SS, false))
5381 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5382 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5383 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5384 else
5385 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5386 << Ident << CorrectedQuotedStr
5387 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5388
5389 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5390 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5391
5392 Ident = Corrected.getCorrectionAsIdentifierInfo();
5393 R.addDecl(Corrected.getCorrectionDecl());
5394 return true;
5395 }
5396 R.setLookupName(Ident);
5397 }
5398 return false;
5399}
5400
John McCalld226f652010-08-21 09:40:31 +00005401Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005402 SourceLocation UsingLoc,
5403 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005404 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005405 SourceLocation IdentLoc,
5406 IdentifierInfo *NamespcName,
5407 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005408 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5409 assert(NamespcName && "Invalid NamespcName.");
5410 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005411
5412 // This can only happen along a recovery path.
5413 while (S->getFlags() & Scope::TemplateParamScope)
5414 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005415 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005416
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005417 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005418 NestedNameSpecifier *Qualifier = 0;
5419 if (SS.isSet())
5420 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5421
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005422 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005423 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5424 LookupParsedName(R, S, &SS);
5425 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005426 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005427
Douglas Gregor66992202010-06-29 17:53:46 +00005428 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005429 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005430 // Allow "using namespace std;" or "using namespace ::std;" even if
5431 // "std" hasn't been defined yet, for GCC compatibility.
5432 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5433 NamespcName->isStr("std")) {
5434 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005435 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005436 R.resolveKind();
5437 }
5438 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005439 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005440 }
5441
John McCallf36e02d2009-10-09 21:13:30 +00005442 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005443 NamedDecl *Named = R.getFoundDecl();
5444 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5445 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005446 // C++ [namespace.udir]p1:
5447 // A using-directive specifies that the names in the nominated
5448 // namespace can be used in the scope in which the
5449 // using-directive appears after the using-directive. During
5450 // unqualified name lookup (3.4.1), the names appear as if they
5451 // were declared in the nearest enclosing namespace which
5452 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005453 // namespace. [Note: in this context, "contains" means "contains
5454 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005455
5456 // Find enclosing context containing both using-directive and
5457 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005458 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005459 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5460 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5461 CommonAncestor = CommonAncestor->getParent();
5462
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005463 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005464 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005465 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005466
Douglas Gregor9172aa62011-03-26 22:25:30 +00005467 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005468 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005469 Diag(IdentLoc, diag::warn_using_directive_in_header);
5470 }
5471
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005472 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005473 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005474 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005475 }
5476
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005477 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005478 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005479}
5480
5481void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5482 // If scope has associated entity, then using directive is at namespace
5483 // or translation unit scope. We add UsingDirectiveDecls, into
5484 // it's lookup structure.
5485 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005486 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005487 else
5488 // Otherwise it is block-sope. using-directives will affect lookup
5489 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005490 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005491}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005492
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005493
John McCalld226f652010-08-21 09:40:31 +00005494Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005495 AccessSpecifier AS,
5496 bool HasUsingKeyword,
5497 SourceLocation UsingLoc,
5498 CXXScopeSpec &SS,
5499 UnqualifiedId &Name,
5500 AttributeList *AttrList,
5501 bool IsTypeName,
5502 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005503 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005504
Douglas Gregor12c118a2009-11-04 16:30:06 +00005505 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005506 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005507 case UnqualifiedId::IK_Identifier:
5508 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005509 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005510 case UnqualifiedId::IK_ConversionFunctionId:
5511 break;
5512
5513 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005514 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005515 // C++0x inherited constructors.
5516 if (getLangOptions().CPlusPlus0x) break;
5517
Douglas Gregor12c118a2009-11-04 16:30:06 +00005518 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5519 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005520 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005521
5522 case UnqualifiedId::IK_DestructorName:
5523 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5524 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005525 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005526
5527 case UnqualifiedId::IK_TemplateId:
5528 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5529 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005530 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005531 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005532
5533 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5534 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005535 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005536 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005537
John McCall60fa3cf2009-12-11 02:10:03 +00005538 // Warn about using declarations.
5539 // TODO: store that the declaration was written without 'using' and
5540 // talk about access decls instead of using decls in the
5541 // diagnostics.
5542 if (!HasUsingKeyword) {
5543 UsingLoc = Name.getSourceRange().getBegin();
5544
5545 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005546 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005547 }
5548
Douglas Gregor56c04582010-12-16 00:46:58 +00005549 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5550 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5551 return 0;
5552
John McCall9488ea12009-11-17 05:59:44 +00005553 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005554 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005555 /* IsInstantiation */ false,
5556 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005557 if (UD)
5558 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005559
John McCalld226f652010-08-21 09:40:31 +00005560 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005561}
5562
Douglas Gregor09acc982010-07-07 23:08:52 +00005563/// \brief Determine whether a using declaration considers the given
5564/// declarations as "equivalent", e.g., if they are redeclarations of
5565/// the same entity or are both typedefs of the same type.
5566static bool
5567IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5568 bool &SuppressRedeclaration) {
5569 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5570 SuppressRedeclaration = false;
5571 return true;
5572 }
5573
Richard Smith162e1c12011-04-15 14:24:37 +00005574 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5575 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005576 SuppressRedeclaration = true;
5577 return Context.hasSameType(TD1->getUnderlyingType(),
5578 TD2->getUnderlyingType());
5579 }
5580
5581 return false;
5582}
5583
5584
John McCall9f54ad42009-12-10 09:41:52 +00005585/// Determines whether to create a using shadow decl for a particular
5586/// decl, given the set of decls existing prior to this using lookup.
5587bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5588 const LookupResult &Previous) {
5589 // Diagnose finding a decl which is not from a base class of the
5590 // current class. We do this now because there are cases where this
5591 // function will silently decide not to build a shadow decl, which
5592 // will pre-empt further diagnostics.
5593 //
5594 // We don't need to do this in C++0x because we do the check once on
5595 // the qualifier.
5596 //
5597 // FIXME: diagnose the following if we care enough:
5598 // struct A { int foo; };
5599 // struct B : A { using A::foo; };
5600 // template <class T> struct C : A {};
5601 // template <class T> struct D : C<T> { using B::foo; } // <---
5602 // This is invalid (during instantiation) in C++03 because B::foo
5603 // resolves to the using decl in B, which is not a base class of D<T>.
5604 // We can't diagnose it immediately because C<T> is an unknown
5605 // specialization. The UsingShadowDecl in D<T> then points directly
5606 // to A::foo, which will look well-formed when we instantiate.
5607 // The right solution is to not collapse the shadow-decl chain.
5608 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5609 DeclContext *OrigDC = Orig->getDeclContext();
5610
5611 // Handle enums and anonymous structs.
5612 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5613 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5614 while (OrigRec->isAnonymousStructOrUnion())
5615 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5616
5617 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5618 if (OrigDC == CurContext) {
5619 Diag(Using->getLocation(),
5620 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005621 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005622 Diag(Orig->getLocation(), diag::note_using_decl_target);
5623 return true;
5624 }
5625
Douglas Gregordc355712011-02-25 00:36:19 +00005626 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005627 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005628 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005629 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005630 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005631 Diag(Orig->getLocation(), diag::note_using_decl_target);
5632 return true;
5633 }
5634 }
5635
5636 if (Previous.empty()) return false;
5637
5638 NamedDecl *Target = Orig;
5639 if (isa<UsingShadowDecl>(Target))
5640 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5641
John McCalld7533ec2009-12-11 02:33:26 +00005642 // If the target happens to be one of the previous declarations, we
5643 // don't have a conflict.
5644 //
5645 // FIXME: but we might be increasing its access, in which case we
5646 // should redeclare it.
5647 NamedDecl *NonTag = 0, *Tag = 0;
5648 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5649 I != E; ++I) {
5650 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005651 bool Result;
5652 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5653 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005654
5655 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5656 }
5657
John McCall9f54ad42009-12-10 09:41:52 +00005658 if (Target->isFunctionOrFunctionTemplate()) {
5659 FunctionDecl *FD;
5660 if (isa<FunctionTemplateDecl>(Target))
5661 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5662 else
5663 FD = cast<FunctionDecl>(Target);
5664
5665 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005666 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005667 case Ovl_Overload:
5668 return false;
5669
5670 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005671 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005672 break;
5673
5674 // We found a decl with the exact signature.
5675 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005676 // If we're in a record, we want to hide the target, so we
5677 // return true (without a diagnostic) to tell the caller not to
5678 // build a shadow decl.
5679 if (CurContext->isRecord())
5680 return true;
5681
5682 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005683 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005684 break;
5685 }
5686
5687 Diag(Target->getLocation(), diag::note_using_decl_target);
5688 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5689 return true;
5690 }
5691
5692 // Target is not a function.
5693
John McCall9f54ad42009-12-10 09:41:52 +00005694 if (isa<TagDecl>(Target)) {
5695 // No conflict between a tag and a non-tag.
5696 if (!Tag) return false;
5697
John McCall41ce66f2009-12-10 19:51:03 +00005698 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005699 Diag(Target->getLocation(), diag::note_using_decl_target);
5700 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5701 return true;
5702 }
5703
5704 // No conflict between a tag and a non-tag.
5705 if (!NonTag) return false;
5706
John McCall41ce66f2009-12-10 19:51:03 +00005707 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005708 Diag(Target->getLocation(), diag::note_using_decl_target);
5709 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5710 return true;
5711}
5712
John McCall9488ea12009-11-17 05:59:44 +00005713/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005714UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005715 UsingDecl *UD,
5716 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005717
5718 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005719 NamedDecl *Target = Orig;
5720 if (isa<UsingShadowDecl>(Target)) {
5721 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5722 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005723 }
5724
5725 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005726 = UsingShadowDecl::Create(Context, CurContext,
5727 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005728 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005729
5730 Shadow->setAccess(UD->getAccess());
5731 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5732 Shadow->setInvalidDecl();
5733
John McCall9488ea12009-11-17 05:59:44 +00005734 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005735 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005736 else
John McCall604e7f12009-12-08 07:46:18 +00005737 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005738
John McCall604e7f12009-12-08 07:46:18 +00005739
John McCall9f54ad42009-12-10 09:41:52 +00005740 return Shadow;
5741}
John McCall604e7f12009-12-08 07:46:18 +00005742
John McCall9f54ad42009-12-10 09:41:52 +00005743/// Hides a using shadow declaration. This is required by the current
5744/// using-decl implementation when a resolvable using declaration in a
5745/// class is followed by a declaration which would hide or override
5746/// one or more of the using decl's targets; for example:
5747///
5748/// struct Base { void foo(int); };
5749/// struct Derived : Base {
5750/// using Base::foo;
5751/// void foo(int);
5752/// };
5753///
5754/// The governing language is C++03 [namespace.udecl]p12:
5755///
5756/// When a using-declaration brings names from a base class into a
5757/// derived class scope, member functions in the derived class
5758/// override and/or hide member functions with the same name and
5759/// parameter types in a base class (rather than conflicting).
5760///
5761/// There are two ways to implement this:
5762/// (1) optimistically create shadow decls when they're not hidden
5763/// by existing declarations, or
5764/// (2) don't create any shadow decls (or at least don't make them
5765/// visible) until we've fully parsed/instantiated the class.
5766/// The problem with (1) is that we might have to retroactively remove
5767/// a shadow decl, which requires several O(n) operations because the
5768/// decl structures are (very reasonably) not designed for removal.
5769/// (2) avoids this but is very fiddly and phase-dependent.
5770void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005771 if (Shadow->getDeclName().getNameKind() ==
5772 DeclarationName::CXXConversionFunctionName)
5773 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5774
John McCall9f54ad42009-12-10 09:41:52 +00005775 // Remove it from the DeclContext...
5776 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005777
John McCall9f54ad42009-12-10 09:41:52 +00005778 // ...and the scope, if applicable...
5779 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005780 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005781 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005782 }
5783
John McCall9f54ad42009-12-10 09:41:52 +00005784 // ...and the using decl.
5785 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5786
5787 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005788 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005789}
5790
John McCall7ba107a2009-11-18 02:36:19 +00005791/// Builds a using declaration.
5792///
5793/// \param IsInstantiation - Whether this call arises from an
5794/// instantiation of an unresolved using declaration. We treat
5795/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005796NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5797 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005798 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005799 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005800 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005801 bool IsInstantiation,
5802 bool IsTypeName,
5803 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005804 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005805 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005806 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005807
Anders Carlsson550b14b2009-08-28 05:49:21 +00005808 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005809
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005810 if (SS.isEmpty()) {
5811 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005812 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005813 }
Mike Stump1eb44332009-09-09 15:08:12 +00005814
John McCall9f54ad42009-12-10 09:41:52 +00005815 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005816 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005817 ForRedeclaration);
5818 Previous.setHideTags(false);
5819 if (S) {
5820 LookupName(Previous, S);
5821
5822 // It is really dumb that we have to do this.
5823 LookupResult::Filter F = Previous.makeFilter();
5824 while (F.hasNext()) {
5825 NamedDecl *D = F.next();
5826 if (!isDeclInScope(D, CurContext, S))
5827 F.erase();
5828 }
5829 F.done();
5830 } else {
5831 assert(IsInstantiation && "no scope in non-instantiation");
5832 assert(CurContext->isRecord() && "scope not record in instantiation");
5833 LookupQualifiedName(Previous, CurContext);
5834 }
5835
John McCall9f54ad42009-12-10 09:41:52 +00005836 // Check for invalid redeclarations.
5837 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5838 return 0;
5839
5840 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005841 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5842 return 0;
5843
John McCallaf8e6ed2009-11-12 03:15:40 +00005844 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005845 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005846 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005847 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005848 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005849 // FIXME: not all declaration name kinds are legal here
5850 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5851 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005852 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005853 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005854 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005855 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5856 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005857 }
John McCalled976492009-12-04 22:46:56 +00005858 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005859 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5860 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005861 }
John McCalled976492009-12-04 22:46:56 +00005862 D->setAccess(AS);
5863 CurContext->addDecl(D);
5864
5865 if (!LookupContext) return D;
5866 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005867
John McCall77bb1aa2010-05-01 00:40:08 +00005868 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005869 UD->setInvalidDecl();
5870 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005871 }
5872
Sebastian Redlf677ea32011-02-05 19:23:19 +00005873 // Constructor inheriting using decls get special treatment.
5874 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005875 if (CheckInheritedConstructorUsingDecl(UD))
5876 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005877 return UD;
5878 }
5879
5880 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005881
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005882 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetb2ee8302011-05-23 03:43:44 +00005883 R.setUsingDeclaration(true);
John McCall7ba107a2009-11-18 02:36:19 +00005884
John McCall604e7f12009-12-08 07:46:18 +00005885 // Unlike most lookups, we don't always want to hide tag
5886 // declarations: tag names are visible through the using declaration
5887 // even if hidden by ordinary names, *except* in a dependent context
5888 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005889 if (!IsInstantiation)
5890 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005891
John McCalla24dc2e2009-11-17 02:14:36 +00005892 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005893
John McCallf36e02d2009-10-09 21:13:30 +00005894 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005895 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005896 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005897 UD->setInvalidDecl();
5898 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005899 }
5900
John McCalled976492009-12-04 22:46:56 +00005901 if (R.isAmbiguous()) {
5902 UD->setInvalidDecl();
5903 return UD;
5904 }
Mike Stump1eb44332009-09-09 15:08:12 +00005905
John McCall7ba107a2009-11-18 02:36:19 +00005906 if (IsTypeName) {
5907 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005908 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005909 Diag(IdentLoc, diag::err_using_typename_non_type);
5910 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5911 Diag((*I)->getUnderlyingDecl()->getLocation(),
5912 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005913 UD->setInvalidDecl();
5914 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005915 }
5916 } else {
5917 // If we asked for a non-typename and we got a type, error out,
5918 // but only if this is an instantiation of an unresolved using
5919 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005920 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005921 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5922 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005923 UD->setInvalidDecl();
5924 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005925 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005926 }
5927
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005928 // C++0x N2914 [namespace.udecl]p6:
5929 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005930 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005931 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5932 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005933 UD->setInvalidDecl();
5934 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005935 }
Mike Stump1eb44332009-09-09 15:08:12 +00005936
John McCall9f54ad42009-12-10 09:41:52 +00005937 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5938 if (!CheckUsingShadowDecl(UD, *I, Previous))
5939 BuildUsingShadowDecl(S, UD, *I);
5940 }
John McCall9488ea12009-11-17 05:59:44 +00005941
5942 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005943}
5944
Sebastian Redlf677ea32011-02-05 19:23:19 +00005945/// Additional checks for a using declaration referring to a constructor name.
5946bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5947 if (UD->isTypeName()) {
5948 // FIXME: Cannot specify typename when specifying constructor
5949 return true;
5950 }
5951
Douglas Gregordc355712011-02-25 00:36:19 +00005952 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005953 assert(SourceType &&
5954 "Using decl naming constructor doesn't have type in scope spec.");
5955 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5956
5957 // Check whether the named type is a direct base class.
5958 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5959 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5960 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5961 BaseIt != BaseE; ++BaseIt) {
5962 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5963 if (CanonicalSourceType == BaseType)
5964 break;
5965 }
5966
5967 if (BaseIt == BaseE) {
5968 // Did not find SourceType in the bases.
5969 Diag(UD->getUsingLocation(),
5970 diag::err_using_decl_constructor_not_in_direct_base)
5971 << UD->getNameInfo().getSourceRange()
5972 << QualType(SourceType, 0) << TargetClass;
5973 return true;
5974 }
5975
5976 BaseIt->setInheritConstructors();
5977
5978 return false;
5979}
5980
John McCall9f54ad42009-12-10 09:41:52 +00005981/// Checks that the given using declaration is not an invalid
5982/// redeclaration. Note that this is checking only for the using decl
5983/// itself, not for any ill-formedness among the UsingShadowDecls.
5984bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5985 bool isTypeName,
5986 const CXXScopeSpec &SS,
5987 SourceLocation NameLoc,
5988 const LookupResult &Prev) {
5989 // C++03 [namespace.udecl]p8:
5990 // C++0x [namespace.udecl]p10:
5991 // A using-declaration is a declaration and can therefore be used
5992 // repeatedly where (and only where) multiple declarations are
5993 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00005994 //
John McCall8a726212010-11-29 18:01:58 +00005995 // That's in non-member contexts.
5996 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00005997 return false;
5998
5999 NestedNameSpecifier *Qual
6000 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6001
6002 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6003 NamedDecl *D = *I;
6004
6005 bool DTypename;
6006 NestedNameSpecifier *DQual;
6007 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6008 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006009 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006010 } else if (UnresolvedUsingValueDecl *UD
6011 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6012 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006013 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006014 } else if (UnresolvedUsingTypenameDecl *UD
6015 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6016 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006017 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006018 } else continue;
6019
6020 // using decls differ if one says 'typename' and the other doesn't.
6021 // FIXME: non-dependent using decls?
6022 if (isTypeName != DTypename) continue;
6023
6024 // using decls differ if they name different scopes (but note that
6025 // template instantiation can cause this check to trigger when it
6026 // didn't before instantiation).
6027 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6028 Context.getCanonicalNestedNameSpecifier(DQual))
6029 continue;
6030
6031 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006032 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006033 return true;
6034 }
6035
6036 return false;
6037}
6038
John McCall604e7f12009-12-08 07:46:18 +00006039
John McCalled976492009-12-04 22:46:56 +00006040/// Checks that the given nested-name qualifier used in a using decl
6041/// in the current context is appropriately related to the current
6042/// scope. If an error is found, diagnoses it and returns true.
6043bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6044 const CXXScopeSpec &SS,
6045 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006046 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006047
John McCall604e7f12009-12-08 07:46:18 +00006048 if (!CurContext->isRecord()) {
6049 // C++03 [namespace.udecl]p3:
6050 // C++0x [namespace.udecl]p8:
6051 // A using-declaration for a class member shall be a member-declaration.
6052
6053 // If we weren't able to compute a valid scope, it must be a
6054 // dependent class scope.
6055 if (!NamedContext || NamedContext->isRecord()) {
6056 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6057 << SS.getRange();
6058 return true;
6059 }
6060
6061 // Otherwise, everything is known to be fine.
6062 return false;
6063 }
6064
6065 // The current scope is a record.
6066
6067 // If the named context is dependent, we can't decide much.
6068 if (!NamedContext) {
6069 // FIXME: in C++0x, we can diagnose if we can prove that the
6070 // nested-name-specifier does not refer to a base class, which is
6071 // still possible in some cases.
6072
6073 // Otherwise we have to conservatively report that things might be
6074 // okay.
6075 return false;
6076 }
6077
6078 if (!NamedContext->isRecord()) {
6079 // Ideally this would point at the last name in the specifier,
6080 // but we don't have that level of source info.
6081 Diag(SS.getRange().getBegin(),
6082 diag::err_using_decl_nested_name_specifier_is_not_class)
6083 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6084 return true;
6085 }
6086
Douglas Gregor6fb07292010-12-21 07:41:49 +00006087 if (!NamedContext->isDependentContext() &&
6088 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6089 return true;
6090
John McCall604e7f12009-12-08 07:46:18 +00006091 if (getLangOptions().CPlusPlus0x) {
6092 // C++0x [namespace.udecl]p3:
6093 // In a using-declaration used as a member-declaration, the
6094 // nested-name-specifier shall name a base class of the class
6095 // being defined.
6096
6097 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6098 cast<CXXRecordDecl>(NamedContext))) {
6099 if (CurContext == NamedContext) {
6100 Diag(NameLoc,
6101 diag::err_using_decl_nested_name_specifier_is_current_class)
6102 << SS.getRange();
6103 return true;
6104 }
6105
6106 Diag(SS.getRange().getBegin(),
6107 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6108 << (NestedNameSpecifier*) SS.getScopeRep()
6109 << cast<CXXRecordDecl>(CurContext)
6110 << SS.getRange();
6111 return true;
6112 }
6113
6114 return false;
6115 }
6116
6117 // C++03 [namespace.udecl]p4:
6118 // A using-declaration used as a member-declaration shall refer
6119 // to a member of a base class of the class being defined [etc.].
6120
6121 // Salient point: SS doesn't have to name a base class as long as
6122 // lookup only finds members from base classes. Therefore we can
6123 // diagnose here only if we can prove that that can't happen,
6124 // i.e. if the class hierarchies provably don't intersect.
6125
6126 // TODO: it would be nice if "definitely valid" results were cached
6127 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6128 // need to be repeated.
6129
6130 struct UserData {
6131 llvm::DenseSet<const CXXRecordDecl*> Bases;
6132
6133 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6134 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6135 Data->Bases.insert(Base);
6136 return true;
6137 }
6138
6139 bool hasDependentBases(const CXXRecordDecl *Class) {
6140 return !Class->forallBases(collect, this);
6141 }
6142
6143 /// Returns true if the base is dependent or is one of the
6144 /// accumulated base classes.
6145 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6146 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6147 return !Data->Bases.count(Base);
6148 }
6149
6150 bool mightShareBases(const CXXRecordDecl *Class) {
6151 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6152 }
6153 };
6154
6155 UserData Data;
6156
6157 // Returns false if we find a dependent base.
6158 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6159 return false;
6160
6161 // Returns false if the class has a dependent base or if it or one
6162 // of its bases is present in the base set of the current context.
6163 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6164 return false;
6165
6166 Diag(SS.getRange().getBegin(),
6167 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6168 << (NestedNameSpecifier*) SS.getScopeRep()
6169 << cast<CXXRecordDecl>(CurContext)
6170 << SS.getRange();
6171
6172 return true;
John McCalled976492009-12-04 22:46:56 +00006173}
6174
Richard Smith162e1c12011-04-15 14:24:37 +00006175Decl *Sema::ActOnAliasDeclaration(Scope *S,
6176 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006177 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006178 SourceLocation UsingLoc,
6179 UnqualifiedId &Name,
6180 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006181 // Skip up to the relevant declaration scope.
6182 while (S->getFlags() & Scope::TemplateParamScope)
6183 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006184 assert((S->getFlags() & Scope::DeclScope) &&
6185 "got alias-declaration outside of declaration scope");
6186
6187 if (Type.isInvalid())
6188 return 0;
6189
6190 bool Invalid = false;
6191 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6192 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006193 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006194
6195 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6196 return 0;
6197
6198 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006199 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006200 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006201 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6202 TInfo->getTypeLoc().getBeginLoc());
6203 }
Richard Smith162e1c12011-04-15 14:24:37 +00006204
6205 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6206 LookupName(Previous, S);
6207
6208 // Warn about shadowing the name of a template parameter.
6209 if (Previous.isSingleResult() &&
6210 Previous.getFoundDecl()->isTemplateParameter()) {
6211 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6212 Previous.getFoundDecl()))
6213 Invalid = true;
6214 Previous.clear();
6215 }
6216
6217 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6218 "name in alias declaration must be an identifier");
6219 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6220 Name.StartLocation,
6221 Name.Identifier, TInfo);
6222
6223 NewTD->setAccess(AS);
6224
6225 if (Invalid)
6226 NewTD->setInvalidDecl();
6227
Richard Smith3e4c6c42011-05-05 21:57:07 +00006228 CheckTypedefForVariablyModifiedType(S, NewTD);
6229 Invalid |= NewTD->isInvalidDecl();
6230
Richard Smith162e1c12011-04-15 14:24:37 +00006231 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006232
6233 NamedDecl *NewND;
6234 if (TemplateParamLists.size()) {
6235 TypeAliasTemplateDecl *OldDecl = 0;
6236 TemplateParameterList *OldTemplateParams = 0;
6237
6238 if (TemplateParamLists.size() != 1) {
6239 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6240 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6241 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6242 }
6243 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6244
6245 // Only consider previous declarations in the same scope.
6246 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6247 /*ExplicitInstantiationOrSpecialization*/false);
6248 if (!Previous.empty()) {
6249 Redeclaration = true;
6250
6251 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6252 if (!OldDecl && !Invalid) {
6253 Diag(UsingLoc, diag::err_redefinition_different_kind)
6254 << Name.Identifier;
6255
6256 NamedDecl *OldD = Previous.getRepresentativeDecl();
6257 if (OldD->getLocation().isValid())
6258 Diag(OldD->getLocation(), diag::note_previous_definition);
6259
6260 Invalid = true;
6261 }
6262
6263 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6264 if (TemplateParameterListsAreEqual(TemplateParams,
6265 OldDecl->getTemplateParameters(),
6266 /*Complain=*/true,
6267 TPL_TemplateMatch))
6268 OldTemplateParams = OldDecl->getTemplateParameters();
6269 else
6270 Invalid = true;
6271
6272 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6273 if (!Invalid &&
6274 !Context.hasSameType(OldTD->getUnderlyingType(),
6275 NewTD->getUnderlyingType())) {
6276 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6277 // but we can't reasonably accept it.
6278 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6279 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6280 if (OldTD->getLocation().isValid())
6281 Diag(OldTD->getLocation(), diag::note_previous_definition);
6282 Invalid = true;
6283 }
6284 }
6285 }
6286
6287 // Merge any previous default template arguments into our parameters,
6288 // and check the parameter list.
6289 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6290 TPC_TypeAliasTemplate))
6291 return 0;
6292
6293 TypeAliasTemplateDecl *NewDecl =
6294 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6295 Name.Identifier, TemplateParams,
6296 NewTD);
6297
6298 NewDecl->setAccess(AS);
6299
6300 if (Invalid)
6301 NewDecl->setInvalidDecl();
6302 else if (OldDecl)
6303 NewDecl->setPreviousDeclaration(OldDecl);
6304
6305 NewND = NewDecl;
6306 } else {
6307 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6308 NewND = NewTD;
6309 }
Richard Smith162e1c12011-04-15 14:24:37 +00006310
6311 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006312 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006313
Richard Smith3e4c6c42011-05-05 21:57:07 +00006314 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006315}
6316
John McCalld226f652010-08-21 09:40:31 +00006317Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006318 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006319 SourceLocation AliasLoc,
6320 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006321 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006322 SourceLocation IdentLoc,
6323 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006324
Anders Carlsson81c85c42009-03-28 23:53:49 +00006325 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006326 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6327 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006328
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006329 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006330 NamedDecl *PrevDecl
6331 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6332 ForRedeclaration);
6333 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6334 PrevDecl = 0;
6335
6336 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006337 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006338 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006339 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006340 // FIXME: At some point, we'll want to create the (redundant)
6341 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006342 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006343 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006344 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006345 }
Mike Stump1eb44332009-09-09 15:08:12 +00006346
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006347 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6348 diag::err_redefinition_different_kind;
6349 Diag(AliasLoc, DiagID) << Alias;
6350 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006351 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006352 }
6353
John McCalla24dc2e2009-11-17 02:14:36 +00006354 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006355 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006356
John McCallf36e02d2009-10-09 21:13:30 +00006357 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006358 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006359 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006360 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006361 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006362 }
Mike Stump1eb44332009-09-09 15:08:12 +00006363
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006364 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006365 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006366 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006367 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006368
John McCall3dbd3d52010-02-16 06:53:13 +00006369 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006370 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006371}
6372
Douglas Gregor39957dc2010-05-01 15:04:51 +00006373namespace {
6374 /// \brief Scoped object used to handle the state changes required in Sema
6375 /// to implicitly define the body of a C++ member function;
6376 class ImplicitlyDefinedFunctionScope {
6377 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006378 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006379
6380 public:
6381 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006382 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006383 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006384 S.PushFunctionScope();
6385 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6386 }
6387
6388 ~ImplicitlyDefinedFunctionScope() {
6389 S.PopExpressionEvaluationContext();
6390 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006391 }
6392 };
6393}
6394
Sean Hunt001cad92011-05-10 00:49:42 +00006395Sema::ImplicitExceptionSpecification
6396Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006397 // C++ [except.spec]p14:
6398 // An implicitly declared special member function (Clause 12) shall have an
6399 // exception-specification. [...]
6400 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006401 if (ClassDecl->isInvalidDecl())
6402 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006403
Sebastian Redl60618fa2011-03-12 11:50:43 +00006404 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006405 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6406 BEnd = ClassDecl->bases_end();
6407 B != BEnd; ++B) {
6408 if (B->isVirtual()) // Handled below.
6409 continue;
6410
Douglas Gregor18274032010-07-03 00:47:00 +00006411 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6412 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006413 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6414 // If this is a deleted function, add it anyway. This might be conformant
6415 // with the standard. This might not. I'm not sure. It might not matter.
6416 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006417 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006418 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006419 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006420
6421 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006422 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6423 BEnd = ClassDecl->vbases_end();
6424 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006425 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6426 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006427 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6428 // If this is a deleted function, add it anyway. This might be conformant
6429 // with the standard. This might not. I'm not sure. It might not matter.
6430 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006431 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006432 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006433 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006434
6435 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006436 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6437 FEnd = ClassDecl->field_end();
6438 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006439 if (F->hasInClassInitializer()) {
6440 if (Expr *E = F->getInClassInitializer())
6441 ExceptSpec.CalledExpr(E);
6442 else if (!F->isInvalidDecl())
6443 ExceptSpec.SetDelayed();
6444 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006445 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006446 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6447 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6448 // If this is a deleted function, add it anyway. This might be conformant
6449 // with the standard. This might not. I'm not sure. It might not matter.
6450 // In particular, the problem is that this function never gets called. It
6451 // might just be ill-formed because this function attempts to refer to
6452 // a deleted function here.
6453 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006454 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006455 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006456 }
John McCalle23cf432010-12-14 08:05:40 +00006457
Sean Hunt001cad92011-05-10 00:49:42 +00006458 return ExceptSpec;
6459}
6460
6461CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6462 CXXRecordDecl *ClassDecl) {
6463 // C++ [class.ctor]p5:
6464 // A default constructor for a class X is a constructor of class X
6465 // that can be called without an argument. If there is no
6466 // user-declared constructor for class X, a default constructor is
6467 // implicitly declared. An implicitly-declared default constructor
6468 // is an inline public member of its class.
6469 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6470 "Should not build implicit default constructor!");
6471
6472 ImplicitExceptionSpecification Spec =
6473 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6474 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006475
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006476 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006477 CanQualType ClassType
6478 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006479 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006480 DeclarationName Name
6481 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006482 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006483 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006484 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00006485 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006486 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00006487 /*TInfo=*/0,
6488 /*isExplicit=*/false,
6489 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006490 /*isImplicitlyDeclared=*/true,
6491 // FIXME: apply the rules for definitions here
6492 /*isConstexpr=*/false);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006493 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006494 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006495 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006496 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006497
6498 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006499 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6500
Douglas Gregor23c94db2010-07-02 17:43:08 +00006501 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006502 PushOnScopeChains(DefaultCon, S, false);
6503 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006504
6505 if (ShouldDeleteDefaultConstructor(DefaultCon))
6506 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006507
Douglas Gregor32df23e2010-07-01 22:02:46 +00006508 return DefaultCon;
6509}
6510
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006511void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6512 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006513 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006514 !Constructor->doesThisDeclarationHaveABody() &&
6515 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006516 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006517
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006518 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006519 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006520
Douglas Gregor39957dc2010-05-01 15:04:51 +00006521 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006522 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006523 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006524 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006525 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006526 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006527 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006528 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006529 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006530
6531 SourceLocation Loc = Constructor->getLocation();
6532 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6533
6534 Constructor->setUsed();
6535 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006536
6537 if (ASTMutationListener *L = getASTMutationListener()) {
6538 L->CompletedImplicitDefinition(Constructor);
6539 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006540}
6541
Richard Smith7a614d82011-06-11 17:19:42 +00006542/// Get any existing defaulted default constructor for the given class. Do not
6543/// implicitly define one if it does not exist.
6544static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6545 CXXRecordDecl *D) {
6546 ASTContext &Context = Self.Context;
6547 QualType ClassType = Context.getTypeDeclType(D);
6548 DeclarationName ConstructorName
6549 = Context.DeclarationNames.getCXXConstructorName(
6550 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6551
6552 DeclContext::lookup_const_iterator Con, ConEnd;
6553 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6554 Con != ConEnd; ++Con) {
6555 // A function template cannot be defaulted.
6556 if (isa<FunctionTemplateDecl>(*Con))
6557 continue;
6558
6559 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6560 if (Constructor->isDefaultConstructor())
6561 return Constructor->isDefaulted() ? Constructor : 0;
6562 }
6563 return 0;
6564}
6565
6566void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6567 if (!D) return;
6568 AdjustDeclIfTemplate(D);
6569
6570 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6571 CXXConstructorDecl *CtorDecl
6572 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6573
6574 if (!CtorDecl) return;
6575
6576 // Compute the exception specification for the default constructor.
6577 const FunctionProtoType *CtorTy =
6578 CtorDecl->getType()->castAs<FunctionProtoType>();
6579 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6580 ImplicitExceptionSpecification Spec =
6581 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6582 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6583 assert(EPI.ExceptionSpecType != EST_Delayed);
6584
6585 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6586 }
6587
6588 // If the default constructor is explicitly defaulted, checking the exception
6589 // specification is deferred until now.
6590 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6591 !ClassDecl->isDependentType())
6592 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6593}
6594
Sebastian Redlf677ea32011-02-05 19:23:19 +00006595void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6596 // We start with an initial pass over the base classes to collect those that
6597 // inherit constructors from. If there are none, we can forgo all further
6598 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006599 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006600 BasesVector BasesToInheritFrom;
6601 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6602 BaseE = ClassDecl->bases_end();
6603 BaseIt != BaseE; ++BaseIt) {
6604 if (BaseIt->getInheritConstructors()) {
6605 QualType Base = BaseIt->getType();
6606 if (Base->isDependentType()) {
6607 // If we inherit constructors from anything that is dependent, just
6608 // abort processing altogether. We'll get another chance for the
6609 // instantiations.
6610 return;
6611 }
6612 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6613 }
6614 }
6615 if (BasesToInheritFrom.empty())
6616 return;
6617
6618 // Now collect the constructors that we already have in the current class.
6619 // Those take precedence over inherited constructors.
6620 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6621 // unless there is a user-declared constructor with the same signature in
6622 // the class where the using-declaration appears.
6623 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6624 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6625 CtorE = ClassDecl->ctor_end();
6626 CtorIt != CtorE; ++CtorIt) {
6627 ExistingConstructors.insert(
6628 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6629 }
6630
6631 Scope *S = getScopeForContext(ClassDecl);
6632 DeclarationName CreatedCtorName =
6633 Context.DeclarationNames.getCXXConstructorName(
6634 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6635
6636 // Now comes the true work.
6637 // First, we keep a map from constructor types to the base that introduced
6638 // them. Needed for finding conflicting constructors. We also keep the
6639 // actually inserted declarations in there, for pretty diagnostics.
6640 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6641 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6642 ConstructorToSourceMap InheritedConstructors;
6643 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6644 BaseE = BasesToInheritFrom.end();
6645 BaseIt != BaseE; ++BaseIt) {
6646 const RecordType *Base = *BaseIt;
6647 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6648 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6649 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6650 CtorE = BaseDecl->ctor_end();
6651 CtorIt != CtorE; ++CtorIt) {
6652 // Find the using declaration for inheriting this base's constructors.
6653 DeclarationName Name =
6654 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6655 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6656 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6657 SourceLocation UsingLoc = UD ? UD->getLocation() :
6658 ClassDecl->getLocation();
6659
6660 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6661 // from the class X named in the using-declaration consists of actual
6662 // constructors and notional constructors that result from the
6663 // transformation of defaulted parameters as follows:
6664 // - all non-template default constructors of X, and
6665 // - for each non-template constructor of X that has at least one
6666 // parameter with a default argument, the set of constructors that
6667 // results from omitting any ellipsis parameter specification and
6668 // successively omitting parameters with a default argument from the
6669 // end of the parameter-type-list.
6670 CXXConstructorDecl *BaseCtor = *CtorIt;
6671 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6672 const FunctionProtoType *BaseCtorType =
6673 BaseCtor->getType()->getAs<FunctionProtoType>();
6674
6675 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6676 maxParams = BaseCtor->getNumParams();
6677 params <= maxParams; ++params) {
6678 // Skip default constructors. They're never inherited.
6679 if (params == 0)
6680 continue;
6681 // Skip copy and move constructors for the same reason.
6682 if (CanBeCopyOrMove && params == 1)
6683 continue;
6684
6685 // Build up a function type for this particular constructor.
6686 // FIXME: The working paper does not consider that the exception spec
6687 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006688 // source. This code doesn't yet, either. When it does, this code will
6689 // need to be delayed until after exception specifications and in-class
6690 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006691 const Type *NewCtorType;
6692 if (params == maxParams)
6693 NewCtorType = BaseCtorType;
6694 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006695 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006696 for (unsigned i = 0; i < params; ++i) {
6697 Args.push_back(BaseCtorType->getArgType(i));
6698 }
6699 FunctionProtoType::ExtProtoInfo ExtInfo =
6700 BaseCtorType->getExtProtoInfo();
6701 ExtInfo.Variadic = false;
6702 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6703 Args.data(), params, ExtInfo)
6704 .getTypePtr();
6705 }
6706 const Type *CanonicalNewCtorType =
6707 Context.getCanonicalType(NewCtorType);
6708
6709 // Now that we have the type, first check if the class already has a
6710 // constructor with this signature.
6711 if (ExistingConstructors.count(CanonicalNewCtorType))
6712 continue;
6713
6714 // Then we check if we have already declared an inherited constructor
6715 // with this signature.
6716 std::pair<ConstructorToSourceMap::iterator, bool> result =
6717 InheritedConstructors.insert(std::make_pair(
6718 CanonicalNewCtorType,
6719 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6720 if (!result.second) {
6721 // Already in the map. If it came from a different class, that's an
6722 // error. Not if it's from the same.
6723 CanQualType PreviousBase = result.first->second.first;
6724 if (CanonicalBase != PreviousBase) {
6725 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6726 const CXXConstructorDecl *PrevBaseCtor =
6727 PrevCtor->getInheritedConstructor();
6728 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6729
6730 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6731 Diag(BaseCtor->getLocation(),
6732 diag::note_using_decl_constructor_conflict_current_ctor);
6733 Diag(PrevBaseCtor->getLocation(),
6734 diag::note_using_decl_constructor_conflict_previous_ctor);
6735 Diag(PrevCtor->getLocation(),
6736 diag::note_using_decl_constructor_conflict_previous_using);
6737 }
6738 continue;
6739 }
6740
6741 // OK, we're there, now add the constructor.
6742 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006743 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00006744 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6745 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006746 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6747 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006748 /*ImplicitlyDeclared=*/true,
6749 // FIXME: Due to a defect in the standard, we treat inherited
6750 // constructors as constexpr even if that makes them ill-formed.
6751 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00006752 NewCtor->setAccess(BaseCtor->getAccess());
6753
6754 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006755 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006756 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006757 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6758 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006759 /*IdentifierInfo=*/0,
6760 BaseCtorType->getArgType(i),
6761 /*TInfo=*/0, SC_None,
6762 SC_None, /*DefaultArg=*/0));
6763 }
6764 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6765 NewCtor->setInheritedConstructor(BaseCtor);
6766
6767 PushOnScopeChains(NewCtor, S, false);
6768 ClassDecl->addDecl(NewCtor);
6769 result.first->second.second = NewCtor;
6770 }
6771 }
6772 }
6773}
6774
Sean Huntcb45a0f2011-05-12 22:46:25 +00006775Sema::ImplicitExceptionSpecification
6776Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006777 // C++ [except.spec]p14:
6778 // An implicitly declared special member function (Clause 12) shall have
6779 // an exception-specification.
6780 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006781 if (ClassDecl->isInvalidDecl())
6782 return ExceptSpec;
6783
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006784 // Direct base-class destructors.
6785 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6786 BEnd = ClassDecl->bases_end();
6787 B != BEnd; ++B) {
6788 if (B->isVirtual()) // Handled below.
6789 continue;
6790
6791 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6792 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006793 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006794 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006795
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006796 // Virtual base-class destructors.
6797 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6798 BEnd = ClassDecl->vbases_end();
6799 B != BEnd; ++B) {
6800 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6801 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006802 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006803 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006804
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006805 // Field destructors.
6806 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6807 FEnd = ClassDecl->field_end();
6808 F != FEnd; ++F) {
6809 if (const RecordType *RecordTy
6810 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6811 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006812 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006813 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006814
Sean Huntcb45a0f2011-05-12 22:46:25 +00006815 return ExceptSpec;
6816}
6817
6818CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6819 // C++ [class.dtor]p2:
6820 // If a class has no user-declared destructor, a destructor is
6821 // declared implicitly. An implicitly-declared destructor is an
6822 // inline public member of its class.
6823
6824 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006825 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006826 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6827
Douglas Gregor4923aa22010-07-02 20:37:36 +00006828 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006829 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006830
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006831 CanQualType ClassType
6832 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006833 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006834 DeclarationName Name
6835 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006836 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006837 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006838 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6839 /*isInline=*/true,
6840 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006841 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006842 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006843 Destructor->setImplicit();
6844 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006845
6846 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006847 ++ASTContext::NumImplicitDestructorsDeclared;
6848
6849 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006850 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006851 PushOnScopeChains(Destructor, S, false);
6852 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006853
6854 // This could be uniqued if it ever proves significant.
6855 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006856
6857 if (ShouldDeleteDestructor(Destructor))
6858 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006859
6860 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006861
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006862 return Destructor;
6863}
6864
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006865void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006866 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006867 assert((Destructor->isDefaulted() &&
6868 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006869 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006870 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006871 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006872
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006873 if (Destructor->isInvalidDecl())
6874 return;
6875
Douglas Gregor39957dc2010-05-01 15:04:51 +00006876 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006877
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006878 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006879 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6880 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006881
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006882 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006883 Diag(CurrentLocation, diag::note_member_synthesized_at)
6884 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6885
6886 Destructor->setInvalidDecl();
6887 return;
6888 }
6889
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006890 SourceLocation Loc = Destructor->getLocation();
6891 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6892
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006893 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006894 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006895
6896 if (ASTMutationListener *L = getASTMutationListener()) {
6897 L->CompletedImplicitDefinition(Destructor);
6898 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006899}
6900
Sebastian Redl0ee33912011-05-19 05:13:44 +00006901void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6902 CXXDestructorDecl *destructor) {
6903 // C++11 [class.dtor]p3:
6904 // A declaration of a destructor that does not have an exception-
6905 // specification is implicitly considered to have the same exception-
6906 // specification as an implicit declaration.
6907 const FunctionProtoType *dtorType = destructor->getType()->
6908 getAs<FunctionProtoType>();
6909 if (dtorType->hasExceptionSpec())
6910 return;
6911
6912 ImplicitExceptionSpecification exceptSpec =
6913 ComputeDefaultedDtorExceptionSpec(classDecl);
6914
6915 // Replace the destructor's type.
6916 FunctionProtoType::ExtProtoInfo epi;
6917 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6918 epi.NumExceptions = exceptSpec.size();
6919 epi.Exceptions = exceptSpec.data();
6920 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6921
6922 destructor->setType(ty);
6923
6924 // FIXME: If the destructor has a body that could throw, and the newly created
6925 // spec doesn't allow exceptions, we should emit a warning, because this
6926 // change in behavior can break conforming C++03 programs at runtime.
6927 // However, we don't have a body yet, so it needs to be done somewhere else.
6928}
6929
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006930/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00006931/// \c To.
6932///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006933/// This routine is used to copy/move the members of a class with an
6934/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00006935/// copied are arrays, this routine builds for loops to copy them.
6936///
6937/// \param S The Sema object used for type-checking.
6938///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006939/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006940///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006941/// \param T The type of the expressions being copied/moved. Both expressions
6942/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006943///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006944/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006945///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006946/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006947///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006948/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006949/// Otherwise, it's a non-static member subobject.
6950///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006951/// \param Copying Whether we're copying or moving.
6952///
Douglas Gregor06a9f362010-05-01 20:49:11 +00006953/// \param Depth Internal parameter recording the depth of the recursion.
6954///
6955/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006956static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00006957BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00006958 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006959 bool CopyingBaseSubobject, bool Copying,
6960 unsigned Depth = 0) {
6961 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00006962 // Each subobject is assigned in the manner appropriate to its type:
6963 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006964 // - if the subobject is of class type, as if by a call to operator= with
6965 // the subobject as the object expression and the corresponding
6966 // subobject of x as a single function argument (as if by explicit
6967 // qualification; that is, ignoring any possible virtual overriding
6968 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006969 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6970 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6971
6972 // Look for operator=.
6973 DeclarationName Name
6974 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6975 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6976 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6977
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006978 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00006979 LookupResult::Filter F = OpLookup.makeFilter();
6980 while (F.hasNext()) {
6981 NamedDecl *D = F.next();
6982 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006983 if (Copying ? Method->isCopyAssignmentOperator() :
6984 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00006985 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00006986
Douglas Gregor06a9f362010-05-01 20:49:11 +00006987 F.erase();
John McCallb0207482010-03-16 06:11:48 +00006988 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006989 F.done();
6990
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006991 // Suppress the protected check (C++ [class.protected]) for each of the
6992 // assignment operators we found. This strange dance is required when
6993 // we're assigning via a base classes's copy-assignment operator. To
6994 // ensure that we're getting the right base class subobject (without
6995 // ambiguities), we need to cast "this" to that subobject type; to
6996 // ensure that we don't go through the virtual call mechanism, we need
6997 // to qualify the operator= name with the base class (see below). However,
6998 // this means that if the base class has a protected copy assignment
6999 // operator, the protected member access check will fail. So, we
7000 // rewrite "protected" access to "public" access in this case, since we
7001 // know by construction that we're calling from a derived class.
7002 if (CopyingBaseSubobject) {
7003 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7004 L != LEnd; ++L) {
7005 if (L.getAccess() == AS_protected)
7006 L.setAccess(AS_public);
7007 }
7008 }
7009
Douglas Gregor06a9f362010-05-01 20:49:11 +00007010 // Create the nested-name-specifier that will be used to qualify the
7011 // reference to operator=; this is required to suppress the virtual
7012 // call mechanism.
7013 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007014 SS.MakeTrivial(S.Context,
7015 NestedNameSpecifier::Create(S.Context, 0, false,
7016 T.getTypePtr()),
7017 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007018
7019 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007020 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007021 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007022 /*FirstQualifierInScope=*/0, OpLookup,
7023 /*TemplateArgs=*/0,
7024 /*SuppressQualifierCheck=*/true);
7025 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007026 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007027
7028 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007029
John McCall60d7b3a2010-08-24 06:29:42 +00007030 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007031 OpEqualRef.takeAs<Expr>(),
7032 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007033 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007034 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007035
7036 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007037 }
John McCallb0207482010-03-16 06:11:48 +00007038
Douglas Gregor06a9f362010-05-01 20:49:11 +00007039 // - if the subobject is of scalar type, the built-in assignment
7040 // operator is used.
7041 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7042 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007043 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007044 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007045 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007046
7047 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007048 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007049
7050 // - if the subobject is an array, each element is assigned, in the
7051 // manner appropriate to the element type;
7052
7053 // Construct a loop over the array bounds, e.g.,
7054 //
7055 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7056 //
7057 // that will copy each of the array elements.
7058 QualType SizeType = S.Context.getSizeType();
7059
7060 // Create the iteration variable.
7061 IdentifierInfo *IterationVarName = 0;
7062 {
7063 llvm::SmallString<8> Str;
7064 llvm::raw_svector_ostream OS(Str);
7065 OS << "__i" << Depth;
7066 IterationVarName = &S.Context.Idents.get(OS.str());
7067 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007068 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007069 IterationVarName, SizeType,
7070 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007071 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007072
7073 // Initialize the iteration variable to zero.
7074 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007075 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007076
7077 // Create a reference to the iteration variable; we'll use this several
7078 // times throughout.
7079 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00007080 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007081 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7082
7083 // Create the DeclStmt that holds the iteration variable.
7084 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7085
7086 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007087 llvm::APInt Upper
7088 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007089 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00007090 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00007091 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7092 BO_NE, S.Context.BoolTy,
7093 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007094
7095 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007096 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007097 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7098 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007099
7100 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007101 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7102 IterationVarRef, Loc));
7103 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7104 IterationVarRef, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007105 if (!Copying) // Cast to rvalue
7106 From = CastForMoving(S, From);
7107
7108 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007109 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7110 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007111 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007112 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007113 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007114
7115 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007116 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007117 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007118 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007119 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007120}
7121
Sean Hunt30de05c2011-05-14 05:23:20 +00007122std::pair<Sema::ImplicitExceptionSpecification, bool>
7123Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7124 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007125 if (ClassDecl->isInvalidDecl())
7126 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7127
Douglas Gregord3c35902010-07-01 16:36:15 +00007128 // C++ [class.copy]p10:
7129 // If the class definition does not explicitly declare a copy
7130 // assignment operator, one is declared implicitly.
7131 // The implicitly-defined copy assignment operator for a class X
7132 // will have the form
7133 //
7134 // X& X::operator=(const X&)
7135 //
7136 // if
7137 bool HasConstCopyAssignment = true;
7138
7139 // -- each direct base class B of X has a copy assignment operator
7140 // whose parameter is of type const B&, const volatile B& or B,
7141 // and
7142 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7143 BaseEnd = ClassDecl->bases_end();
7144 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007145 // We'll handle this below
7146 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7147 continue;
7148
Douglas Gregord3c35902010-07-01 16:36:15 +00007149 assert(!Base->getType()->isDependentType() &&
7150 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007151 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7152 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7153 &HasConstCopyAssignment);
7154 }
7155
7156 // In C++0x, the above citation has "or virtual added"
7157 if (LangOpts.CPlusPlus0x) {
7158 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7159 BaseEnd = ClassDecl->vbases_end();
7160 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7161 assert(!Base->getType()->isDependentType() &&
7162 "Cannot generate implicit members for class with dependent bases.");
7163 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7164 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7165 &HasConstCopyAssignment);
7166 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007167 }
7168
7169 // -- for all the nonstatic data members of X that are of a class
7170 // type M (or array thereof), each such class type has a copy
7171 // assignment operator whose parameter is of type const M&,
7172 // const volatile M& or M.
7173 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7174 FieldEnd = ClassDecl->field_end();
7175 HasConstCopyAssignment && Field != FieldEnd;
7176 ++Field) {
7177 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007178 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7179 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7180 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007181 }
7182 }
7183
7184 // Otherwise, the implicitly declared copy assignment operator will
7185 // have the form
7186 //
7187 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007188
Douglas Gregorb87786f2010-07-01 17:48:08 +00007189 // C++ [except.spec]p14:
7190 // An implicitly declared special member function (Clause 12) shall have an
7191 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007192
7193 // It is unspecified whether or not an implicit copy assignment operator
7194 // attempts to deduplicate calls to assignment operators of virtual bases are
7195 // made. As such, this exception specification is effectively unspecified.
7196 // Based on a similar decision made for constness in C++0x, we're erring on
7197 // the side of assuming such calls to be made regardless of whether they
7198 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007199 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007200 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007201 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7202 BaseEnd = ClassDecl->bases_end();
7203 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007204 if (Base->isVirtual())
7205 continue;
7206
Douglas Gregora376d102010-07-02 21:50:04 +00007207 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007208 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007209 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7210 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007211 ExceptSpec.CalledDecl(CopyAssign);
7212 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007213
7214 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7215 BaseEnd = ClassDecl->vbases_end();
7216 Base != BaseEnd; ++Base) {
7217 CXXRecordDecl *BaseClassDecl
7218 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7219 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7220 ArgQuals, false, 0))
7221 ExceptSpec.CalledDecl(CopyAssign);
7222 }
7223
Douglas Gregorb87786f2010-07-01 17:48:08 +00007224 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7225 FieldEnd = ClassDecl->field_end();
7226 Field != FieldEnd;
7227 ++Field) {
7228 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007229 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7230 if (CXXMethodDecl *CopyAssign =
7231 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7232 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007233 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007234 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007235
Sean Hunt30de05c2011-05-14 05:23:20 +00007236 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7237}
7238
7239CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7240 // Note: The following rules are largely analoguous to the copy
7241 // constructor rules. Note that virtual bases are not taken into account
7242 // for determining the argument type of the operator. Note also that
7243 // operators taking an object instead of a reference are allowed.
7244
7245 ImplicitExceptionSpecification Spec(Context);
7246 bool Const;
7247 llvm::tie(Spec, Const) =
7248 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7249
7250 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7251 QualType RetType = Context.getLValueReferenceType(ArgType);
7252 if (Const)
7253 ArgType = ArgType.withConst();
7254 ArgType = Context.getLValueReferenceType(ArgType);
7255
Douglas Gregord3c35902010-07-01 16:36:15 +00007256 // An implicitly-declared copy assignment operator is an inline public
7257 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007258 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007259 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007260 SourceLocation ClassLoc = ClassDecl->getLocation();
7261 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007262 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007263 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007264 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007265 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007266 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007267 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007268 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007269 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007270 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007271 CopyAssignment->setImplicit();
7272 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007273
7274 // Add the parameter to the operator.
7275 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007276 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007277 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007278 SC_None,
7279 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00007280 CopyAssignment->setParams(&FromParam, 1);
7281
Douglas Gregora376d102010-07-02 21:50:04 +00007282 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007283 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007284
Douglas Gregor23c94db2010-07-02 17:43:08 +00007285 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007286 PushOnScopeChains(CopyAssignment, S, false);
7287 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007288
Sean Hunt1ccbc542011-06-22 01:05:13 +00007289 // C++0x [class.copy]p18:
7290 // ... If the class definition declares a move constructor or move
7291 // assignment operator, the implicitly declared copy assignment operator is
7292 // defined as deleted; ...
7293 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7294 ClassDecl->hasUserDeclaredMoveAssignment() ||
7295 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007296 CopyAssignment->setDeletedAsWritten();
7297
Douglas Gregord3c35902010-07-01 16:36:15 +00007298 AddOverriddenMethods(ClassDecl, CopyAssignment);
7299 return CopyAssignment;
7300}
7301
Douglas Gregor06a9f362010-05-01 20:49:11 +00007302void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7303 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007304 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007305 CopyAssignOperator->isOverloadedOperator() &&
7306 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007307 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007308 "DefineImplicitCopyAssignment called for wrong function");
7309
7310 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7311
7312 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7313 CopyAssignOperator->setInvalidDecl();
7314 return;
7315 }
7316
7317 CopyAssignOperator->setUsed();
7318
7319 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007320 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007321
7322 // C++0x [class.copy]p30:
7323 // The implicitly-defined or explicitly-defaulted copy assignment operator
7324 // for a non-union class X performs memberwise copy assignment of its
7325 // subobjects. The direct base classes of X are assigned first, in the
7326 // order of their declaration in the base-specifier-list, and then the
7327 // immediate non-static data members of X are assigned, in the order in
7328 // which they were declared in the class definition.
7329
7330 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007331 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007332
7333 // The parameter for the "other" object, which we are copying from.
7334 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7335 Qualifiers OtherQuals = Other->getType().getQualifiers();
7336 QualType OtherRefType = Other->getType();
7337 if (const LValueReferenceType *OtherRef
7338 = OtherRefType->getAs<LValueReferenceType>()) {
7339 OtherRefType = OtherRef->getPointeeType();
7340 OtherQuals = OtherRefType.getQualifiers();
7341 }
7342
7343 // Our location for everything implicitly-generated.
7344 SourceLocation Loc = CopyAssignOperator->getLocation();
7345
7346 // Construct a reference to the "other" object. We'll be using this
7347 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007348 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007349 assert(OtherRef && "Reference to parameter cannot fail!");
7350
7351 // Construct the "this" pointer. We'll be using this throughout the generated
7352 // ASTs.
7353 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7354 assert(This && "Reference to this cannot fail!");
7355
7356 // Assign base classes.
7357 bool Invalid = false;
7358 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7359 E = ClassDecl->bases_end(); Base != E; ++Base) {
7360 // Form the assignment:
7361 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7362 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007363 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007364 Invalid = true;
7365 continue;
7366 }
7367
John McCallf871d0c2010-08-07 06:22:56 +00007368 CXXCastPath BasePath;
7369 BasePath.push_back(Base);
7370
Douglas Gregor06a9f362010-05-01 20:49:11 +00007371 // Construct the "from" expression, which is an implicit cast to the
7372 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007373 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007374 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7375 CK_UncheckedDerivedToBase,
7376 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007377
7378 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007379 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007380
7381 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007382 To = ImpCastExprToType(To.take(),
7383 Context.getCVRQualifiedType(BaseType,
7384 CopyAssignOperator->getTypeQualifiers()),
7385 CK_UncheckedDerivedToBase,
7386 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007387
7388 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007389 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007390 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007391 /*CopyingBaseSubobject=*/true,
7392 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007393 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007394 Diag(CurrentLocation, diag::note_member_synthesized_at)
7395 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7396 CopyAssignOperator->setInvalidDecl();
7397 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007398 }
7399
7400 // Success! Record the copy.
7401 Statements.push_back(Copy.takeAs<Expr>());
7402 }
7403
7404 // \brief Reference to the __builtin_memcpy function.
7405 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007406 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007407 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007408
7409 // Assign non-static members.
7410 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7411 FieldEnd = ClassDecl->field_end();
7412 Field != FieldEnd; ++Field) {
7413 // Check for members of reference type; we can't copy those.
7414 if (Field->getType()->isReferenceType()) {
7415 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7416 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7417 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007418 Diag(CurrentLocation, diag::note_member_synthesized_at)
7419 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007420 Invalid = true;
7421 continue;
7422 }
7423
7424 // Check for members of const-qualified, non-class type.
7425 QualType BaseType = Context.getBaseElementType(Field->getType());
7426 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7427 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7428 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7429 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007430 Diag(CurrentLocation, diag::note_member_synthesized_at)
7431 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007432 Invalid = true;
7433 continue;
7434 }
John McCallb77115d2011-06-17 00:18:42 +00007435
7436 // Suppress assigning zero-width bitfields.
7437 if (const Expr *Width = Field->getBitWidth())
7438 if (Width->EvaluateAsInt(Context) == 0)
7439 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007440
7441 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007442 if (FieldType->isIncompleteArrayType()) {
7443 assert(ClassDecl->hasFlexibleArrayMember() &&
7444 "Incomplete array type is not valid");
7445 continue;
7446 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007447
7448 // Build references to the field in the object we're copying from and to.
7449 CXXScopeSpec SS; // Intentionally empty
7450 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7451 LookupMemberName);
7452 MemberLookup.addDecl(*Field);
7453 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007454 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007455 Loc, /*IsArrow=*/false,
7456 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007457 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007458 Loc, /*IsArrow=*/true,
7459 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007460 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7461 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7462
7463 // If the field should be copied with __builtin_memcpy rather than via
7464 // explicit assignments, do so. This optimization only applies for arrays
7465 // of scalars and arrays of class type with trivial copy-assignment
7466 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007467 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007468 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007469 // Compute the size of the memory buffer to be copied.
7470 QualType SizeType = Context.getSizeType();
7471 llvm::APInt Size(Context.getTypeSize(SizeType),
7472 Context.getTypeSizeInChars(BaseType).getQuantity());
7473 for (const ConstantArrayType *Array
7474 = Context.getAsConstantArrayType(FieldType);
7475 Array;
7476 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007477 llvm::APInt ArraySize
7478 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007479 Size *= ArraySize;
7480 }
7481
7482 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007483 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7484 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007485
7486 bool NeedsCollectableMemCpy =
7487 (BaseType->isRecordType() &&
7488 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7489
7490 if (NeedsCollectableMemCpy) {
7491 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007492 // Create a reference to the __builtin_objc_memmove_collectable function.
7493 LookupResult R(*this,
7494 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007495 Loc, LookupOrdinaryName);
7496 LookupName(R, TUScope, true);
7497
7498 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7499 if (!CollectableMemCpy) {
7500 // Something went horribly wrong earlier, and we will have
7501 // complained about it.
7502 Invalid = true;
7503 continue;
7504 }
7505
7506 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7507 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007508 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007509 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7510 }
7511 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007512 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007513 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007514 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7515 LookupOrdinaryName);
7516 LookupName(R, TUScope, true);
7517
7518 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7519 if (!BuiltinMemCpy) {
7520 // Something went horribly wrong earlier, and we will have complained
7521 // about it.
7522 Invalid = true;
7523 continue;
7524 }
7525
7526 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7527 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007528 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007529 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7530 }
7531
John McCallca0408f2010-08-23 06:44:23 +00007532 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007533 CallArgs.push_back(To.takeAs<Expr>());
7534 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007535 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007536 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007537 if (NeedsCollectableMemCpy)
7538 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007539 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007540 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007541 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007542 else
7543 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007544 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007545 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007546 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007547
Douglas Gregor06a9f362010-05-01 20:49:11 +00007548 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7549 Statements.push_back(Call.takeAs<Expr>());
7550 continue;
7551 }
7552
7553 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007554 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007555 To.get(), From.get(),
7556 /*CopyingBaseSubobject=*/false,
7557 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007558 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007559 Diag(CurrentLocation, diag::note_member_synthesized_at)
7560 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7561 CopyAssignOperator->setInvalidDecl();
7562 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007563 }
7564
7565 // Success! Record the copy.
7566 Statements.push_back(Copy.takeAs<Stmt>());
7567 }
7568
7569 if (!Invalid) {
7570 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007571 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007572
John McCall60d7b3a2010-08-24 06:29:42 +00007573 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007574 if (Return.isInvalid())
7575 Invalid = true;
7576 else {
7577 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007578
7579 if (Trap.hasErrorOccurred()) {
7580 Diag(CurrentLocation, diag::note_member_synthesized_at)
7581 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7582 Invalid = true;
7583 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007584 }
7585 }
7586
7587 if (Invalid) {
7588 CopyAssignOperator->setInvalidDecl();
7589 return;
7590 }
7591
John McCall60d7b3a2010-08-24 06:29:42 +00007592 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007593 /*isStmtExpr=*/false);
7594 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7595 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007596
7597 if (ASTMutationListener *L = getASTMutationListener()) {
7598 L->CompletedImplicitDefinition(CopyAssignOperator);
7599 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007600}
7601
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007602Sema::ImplicitExceptionSpecification
7603Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7604 ImplicitExceptionSpecification ExceptSpec(Context);
7605
7606 if (ClassDecl->isInvalidDecl())
7607 return ExceptSpec;
7608
7609 // C++0x [except.spec]p14:
7610 // An implicitly declared special member function (Clause 12) shall have an
7611 // exception-specification. [...]
7612
7613 // It is unspecified whether or not an implicit move assignment operator
7614 // attempts to deduplicate calls to assignment operators of virtual bases are
7615 // made. As such, this exception specification is effectively unspecified.
7616 // Based on a similar decision made for constness in C++0x, we're erring on
7617 // the side of assuming such calls to be made regardless of whether they
7618 // actually happen.
7619 // Note that a move constructor is not implicitly declared when there are
7620 // virtual bases, but it can still be user-declared and explicitly defaulted.
7621 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7622 BaseEnd = ClassDecl->bases_end();
7623 Base != BaseEnd; ++Base) {
7624 if (Base->isVirtual())
7625 continue;
7626
7627 CXXRecordDecl *BaseClassDecl
7628 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7629 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7630 false, 0))
7631 ExceptSpec.CalledDecl(MoveAssign);
7632 }
7633
7634 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7635 BaseEnd = ClassDecl->vbases_end();
7636 Base != BaseEnd; ++Base) {
7637 CXXRecordDecl *BaseClassDecl
7638 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7639 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7640 false, 0))
7641 ExceptSpec.CalledDecl(MoveAssign);
7642 }
7643
7644 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7645 FieldEnd = ClassDecl->field_end();
7646 Field != FieldEnd;
7647 ++Field) {
7648 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7649 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7650 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7651 false, 0))
7652 ExceptSpec.CalledDecl(MoveAssign);
7653 }
7654 }
7655
7656 return ExceptSpec;
7657}
7658
7659CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7660 // Note: The following rules are largely analoguous to the move
7661 // constructor rules.
7662
7663 ImplicitExceptionSpecification Spec(
7664 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7665
7666 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7667 QualType RetType = Context.getLValueReferenceType(ArgType);
7668 ArgType = Context.getRValueReferenceType(ArgType);
7669
7670 // An implicitly-declared move assignment operator is an inline public
7671 // member of its class.
7672 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7673 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7674 SourceLocation ClassLoc = ClassDecl->getLocation();
7675 DeclarationNameInfo NameInfo(Name, ClassLoc);
7676 CXXMethodDecl *MoveAssignment
7677 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7678 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7679 /*TInfo=*/0, /*isStatic=*/false,
7680 /*StorageClassAsWritten=*/SC_None,
7681 /*isInline=*/true,
7682 /*isConstexpr=*/false,
7683 SourceLocation());
7684 MoveAssignment->setAccess(AS_public);
7685 MoveAssignment->setDefaulted();
7686 MoveAssignment->setImplicit();
7687 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7688
7689 // Add the parameter to the operator.
7690 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7691 ClassLoc, ClassLoc, /*Id=*/0,
7692 ArgType, /*TInfo=*/0,
7693 SC_None,
7694 SC_None, 0);
7695 MoveAssignment->setParams(&FromParam, 1);
7696
7697 // Note that we have added this copy-assignment operator.
7698 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7699
7700 // C++0x [class.copy]p9:
7701 // If the definition of a class X does not explicitly declare a move
7702 // assignment operator, one will be implicitly declared as defaulted if and
7703 // only if:
7704 // [...]
7705 // - the move assignment operator would not be implicitly defined as
7706 // deleted.
7707 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7708 // Cache this result so that we don't try to generate this over and over
7709 // on every lookup, leaking memory and wasting time.
7710 ClassDecl->setFailedImplicitMoveAssignment();
7711 return 0;
7712 }
7713
7714 if (Scope *S = getScopeForContext(ClassDecl))
7715 PushOnScopeChains(MoveAssignment, S, false);
7716 ClassDecl->addDecl(MoveAssignment);
7717
7718 AddOverriddenMethods(ClassDecl, MoveAssignment);
7719 return MoveAssignment;
7720}
7721
7722void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7723 CXXMethodDecl *MoveAssignOperator) {
7724 assert((MoveAssignOperator->isDefaulted() &&
7725 MoveAssignOperator->isOverloadedOperator() &&
7726 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7727 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7728 "DefineImplicitMoveAssignment called for wrong function");
7729
7730 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7731
7732 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7733 MoveAssignOperator->setInvalidDecl();
7734 return;
7735 }
7736
7737 MoveAssignOperator->setUsed();
7738
7739 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7740 DiagnosticErrorTrap Trap(Diags);
7741
7742 // C++0x [class.copy]p28:
7743 // The implicitly-defined or move assignment operator for a non-union class
7744 // X performs memberwise move assignment of its subobjects. The direct base
7745 // classes of X are assigned first, in the order of their declaration in the
7746 // base-specifier-list, and then the immediate non-static data members of X
7747 // are assigned, in the order in which they were declared in the class
7748 // definition.
7749
7750 // The statements that form the synthesized function body.
7751 ASTOwningVector<Stmt*> Statements(*this);
7752
7753 // The parameter for the "other" object, which we are move from.
7754 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7755 QualType OtherRefType = Other->getType()->
7756 getAs<RValueReferenceType>()->getPointeeType();
7757 assert(OtherRefType.getQualifiers() == 0 &&
7758 "Bad argument type of defaulted move assignment");
7759
7760 // Our location for everything implicitly-generated.
7761 SourceLocation Loc = MoveAssignOperator->getLocation();
7762
7763 // Construct a reference to the "other" object. We'll be using this
7764 // throughout the generated ASTs.
7765 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7766 assert(OtherRef && "Reference to parameter cannot fail!");
7767 // Cast to rvalue.
7768 OtherRef = CastForMoving(*this, OtherRef);
7769
7770 // Construct the "this" pointer. We'll be using this throughout the generated
7771 // ASTs.
7772 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7773 assert(This && "Reference to this cannot fail!");
7774
7775 // Assign base classes.
7776 bool Invalid = false;
7777 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7778 E = ClassDecl->bases_end(); Base != E; ++Base) {
7779 // Form the assignment:
7780 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7781 QualType BaseType = Base->getType().getUnqualifiedType();
7782 if (!BaseType->isRecordType()) {
7783 Invalid = true;
7784 continue;
7785 }
7786
7787 CXXCastPath BasePath;
7788 BasePath.push_back(Base);
7789
7790 // Construct the "from" expression, which is an implicit cast to the
7791 // appropriately-qualified base type.
7792 Expr *From = OtherRef;
7793 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
7794 VK_RValue, &BasePath).take();
7795
7796 // Dereference "this".
7797 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7798
7799 // Implicitly cast "this" to the appropriately-qualified base type.
7800 To = ImpCastExprToType(To.take(),
7801 Context.getCVRQualifiedType(BaseType,
7802 MoveAssignOperator->getTypeQualifiers()),
7803 CK_UncheckedDerivedToBase,
7804 VK_LValue, &BasePath);
7805
7806 // Build the move.
7807 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7808 To.get(), From,
7809 /*CopyingBaseSubobject=*/true,
7810 /*Copying=*/false);
7811 if (Move.isInvalid()) {
7812 Diag(CurrentLocation, diag::note_member_synthesized_at)
7813 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7814 MoveAssignOperator->setInvalidDecl();
7815 return;
7816 }
7817
7818 // Success! Record the move.
7819 Statements.push_back(Move.takeAs<Expr>());
7820 }
7821
7822 // \brief Reference to the __builtin_memcpy function.
7823 Expr *BuiltinMemCpyRef = 0;
7824 // \brief Reference to the __builtin_objc_memmove_collectable function.
7825 Expr *CollectableMemCpyRef = 0;
7826
7827 // Assign non-static members.
7828 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7829 FieldEnd = ClassDecl->field_end();
7830 Field != FieldEnd; ++Field) {
7831 // Check for members of reference type; we can't move those.
7832 if (Field->getType()->isReferenceType()) {
7833 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7834 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7835 Diag(Field->getLocation(), diag::note_declared_at);
7836 Diag(CurrentLocation, diag::note_member_synthesized_at)
7837 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7838 Invalid = true;
7839 continue;
7840 }
7841
7842 // Check for members of const-qualified, non-class type.
7843 QualType BaseType = Context.getBaseElementType(Field->getType());
7844 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7845 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7846 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7847 Diag(Field->getLocation(), diag::note_declared_at);
7848 Diag(CurrentLocation, diag::note_member_synthesized_at)
7849 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7850 Invalid = true;
7851 continue;
7852 }
7853
7854 // Suppress assigning zero-width bitfields.
7855 if (const Expr *Width = Field->getBitWidth())
7856 if (Width->EvaluateAsInt(Context) == 0)
7857 continue;
7858
7859 QualType FieldType = Field->getType().getNonReferenceType();
7860 if (FieldType->isIncompleteArrayType()) {
7861 assert(ClassDecl->hasFlexibleArrayMember() &&
7862 "Incomplete array type is not valid");
7863 continue;
7864 }
7865
7866 // Build references to the field in the object we're copying from and to.
7867 CXXScopeSpec SS; // Intentionally empty
7868 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7869 LookupMemberName);
7870 MemberLookup.addDecl(*Field);
7871 MemberLookup.resolveKind();
7872 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7873 Loc, /*IsArrow=*/false,
7874 SS, 0, MemberLookup, 0);
7875 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7876 Loc, /*IsArrow=*/true,
7877 SS, 0, MemberLookup, 0);
7878 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7879 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7880
7881 assert(!From.get()->isLValue() && // could be xvalue or prvalue
7882 "Member reference with rvalue base must be rvalue except for reference "
7883 "members, which aren't allowed for move assignment.");
7884
7885 // If the field should be copied with __builtin_memcpy rather than via
7886 // explicit assignments, do so. This optimization only applies for arrays
7887 // of scalars and arrays of class type with trivial move-assignment
7888 // operators.
7889 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7890 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7891 // Compute the size of the memory buffer to be copied.
7892 QualType SizeType = Context.getSizeType();
7893 llvm::APInt Size(Context.getTypeSize(SizeType),
7894 Context.getTypeSizeInChars(BaseType).getQuantity());
7895 for (const ConstantArrayType *Array
7896 = Context.getAsConstantArrayType(FieldType);
7897 Array;
7898 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7899 llvm::APInt ArraySize
7900 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7901 Size *= ArraySize;
7902 }
7903
7904 // Take the address of the field references for "from" and "to".
7905 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7906 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7907
7908 bool NeedsCollectableMemCpy =
7909 (BaseType->isRecordType() &&
7910 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7911
7912 if (NeedsCollectableMemCpy) {
7913 if (!CollectableMemCpyRef) {
7914 // Create a reference to the __builtin_objc_memmove_collectable function.
7915 LookupResult R(*this,
7916 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7917 Loc, LookupOrdinaryName);
7918 LookupName(R, TUScope, true);
7919
7920 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7921 if (!CollectableMemCpy) {
7922 // Something went horribly wrong earlier, and we will have
7923 // complained about it.
7924 Invalid = true;
7925 continue;
7926 }
7927
7928 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7929 CollectableMemCpy->getType(),
7930 VK_LValue, Loc, 0).take();
7931 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7932 }
7933 }
7934 // Create a reference to the __builtin_memcpy builtin function.
7935 else if (!BuiltinMemCpyRef) {
7936 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7937 LookupOrdinaryName);
7938 LookupName(R, TUScope, true);
7939
7940 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7941 if (!BuiltinMemCpy) {
7942 // Something went horribly wrong earlier, and we will have complained
7943 // about it.
7944 Invalid = true;
7945 continue;
7946 }
7947
7948 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7949 BuiltinMemCpy->getType(),
7950 VK_LValue, Loc, 0).take();
7951 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7952 }
7953
7954 ASTOwningVector<Expr*> CallArgs(*this);
7955 CallArgs.push_back(To.takeAs<Expr>());
7956 CallArgs.push_back(From.takeAs<Expr>());
7957 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7958 ExprResult Call = ExprError();
7959 if (NeedsCollectableMemCpy)
7960 Call = ActOnCallExpr(/*Scope=*/0,
7961 CollectableMemCpyRef,
7962 Loc, move_arg(CallArgs),
7963 Loc);
7964 else
7965 Call = ActOnCallExpr(/*Scope=*/0,
7966 BuiltinMemCpyRef,
7967 Loc, move_arg(CallArgs),
7968 Loc);
7969
7970 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7971 Statements.push_back(Call.takeAs<Expr>());
7972 continue;
7973 }
7974
7975 // Build the move of this field.
7976 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
7977 To.get(), From.get(),
7978 /*CopyingBaseSubobject=*/false,
7979 /*Copying=*/false);
7980 if (Move.isInvalid()) {
7981 Diag(CurrentLocation, diag::note_member_synthesized_at)
7982 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7983 MoveAssignOperator->setInvalidDecl();
7984 return;
7985 }
7986
7987 // Success! Record the copy.
7988 Statements.push_back(Move.takeAs<Stmt>());
7989 }
7990
7991 if (!Invalid) {
7992 // Add a "return *this;"
7993 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7994
7995 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7996 if (Return.isInvalid())
7997 Invalid = true;
7998 else {
7999 Statements.push_back(Return.takeAs<Stmt>());
8000
8001 if (Trap.hasErrorOccurred()) {
8002 Diag(CurrentLocation, diag::note_member_synthesized_at)
8003 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8004 Invalid = true;
8005 }
8006 }
8007 }
8008
8009 if (Invalid) {
8010 MoveAssignOperator->setInvalidDecl();
8011 return;
8012 }
8013
8014 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8015 /*isStmtExpr=*/false);
8016 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8017 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8018
8019 if (ASTMutationListener *L = getASTMutationListener()) {
8020 L->CompletedImplicitDefinition(MoveAssignOperator);
8021 }
8022}
8023
Sean Hunt49634cf2011-05-13 06:10:58 +00008024std::pair<Sema::ImplicitExceptionSpecification, bool>
8025Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008026 if (ClassDecl->isInvalidDecl())
8027 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8028
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008029 // C++ [class.copy]p5:
8030 // The implicitly-declared copy constructor for a class X will
8031 // have the form
8032 //
8033 // X::X(const X&)
8034 //
8035 // if
Sean Huntc530d172011-06-10 04:44:37 +00008036 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008037 bool HasConstCopyConstructor = true;
8038
8039 // -- each direct or virtual base class B of X has a copy
8040 // constructor whose first parameter is of type const B& or
8041 // const volatile B&, and
8042 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8043 BaseEnd = ClassDecl->bases_end();
8044 HasConstCopyConstructor && Base != BaseEnd;
8045 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008046 // Virtual bases are handled below.
8047 if (Base->isVirtual())
8048 continue;
8049
Douglas Gregor22584312010-07-02 23:41:54 +00008050 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008051 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008052 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8053 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008054 }
8055
8056 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8057 BaseEnd = ClassDecl->vbases_end();
8058 HasConstCopyConstructor && Base != BaseEnd;
8059 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008060 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008061 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008062 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8063 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008064 }
8065
8066 // -- for all the nonstatic data members of X that are of a
8067 // class type M (or array thereof), each such class type
8068 // has a copy constructor whose first parameter is of type
8069 // const M& or const volatile M&.
8070 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8071 FieldEnd = ClassDecl->field_end();
8072 HasConstCopyConstructor && Field != FieldEnd;
8073 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008074 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008075 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008076 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8077 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008078 }
8079 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008080 // Otherwise, the implicitly declared copy constructor will have
8081 // the form
8082 //
8083 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008084
Douglas Gregor0d405db2010-07-01 20:59:04 +00008085 // C++ [except.spec]p14:
8086 // An implicitly declared special member function (Clause 12) shall have an
8087 // exception-specification. [...]
8088 ImplicitExceptionSpecification ExceptSpec(Context);
8089 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8090 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8091 BaseEnd = ClassDecl->bases_end();
8092 Base != BaseEnd;
8093 ++Base) {
8094 // Virtual bases are handled below.
8095 if (Base->isVirtual())
8096 continue;
8097
Douglas Gregor22584312010-07-02 23:41:54 +00008098 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008099 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008100 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008101 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008102 ExceptSpec.CalledDecl(CopyConstructor);
8103 }
8104 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8105 BaseEnd = ClassDecl->vbases_end();
8106 Base != BaseEnd;
8107 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008108 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008109 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008110 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008111 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008112 ExceptSpec.CalledDecl(CopyConstructor);
8113 }
8114 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8115 FieldEnd = ClassDecl->field_end();
8116 Field != FieldEnd;
8117 ++Field) {
8118 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008119 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8120 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008121 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008122 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008123 }
8124 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008125
Sean Hunt49634cf2011-05-13 06:10:58 +00008126 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8127}
8128
8129CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8130 CXXRecordDecl *ClassDecl) {
8131 // C++ [class.copy]p4:
8132 // If the class definition does not explicitly declare a copy
8133 // constructor, one is declared implicitly.
8134
8135 ImplicitExceptionSpecification Spec(Context);
8136 bool Const;
8137 llvm::tie(Spec, Const) =
8138 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8139
8140 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8141 QualType ArgType = ClassType;
8142 if (Const)
8143 ArgType = ArgType.withConst();
8144 ArgType = Context.getLValueReferenceType(ArgType);
8145
8146 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8147
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008148 DeclarationName Name
8149 = Context.DeclarationNames.getCXXConstructorName(
8150 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008151 SourceLocation ClassLoc = ClassDecl->getLocation();
8152 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008153
8154 // An implicitly-declared copy constructor is an inline public
8155 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008156 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008157 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008158 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00008159 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008160 /*TInfo=*/0,
8161 /*isExplicit=*/false,
8162 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008163 /*isImplicitlyDeclared=*/true,
8164 // FIXME: apply the rules for definitions here
8165 /*isConstexpr=*/false);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008166 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008167 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008168 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8169
Douglas Gregor22584312010-07-02 23:41:54 +00008170 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008171 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8172
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008173 // Add the parameter to the constructor.
8174 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008175 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008176 /*IdentifierInfo=*/0,
8177 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008178 SC_None,
8179 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008180 CopyConstructor->setParams(&FromParam, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00008181
Douglas Gregor23c94db2010-07-02 17:43:08 +00008182 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008183 PushOnScopeChains(CopyConstructor, S, false);
8184 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008185
Sean Hunt1ccbc542011-06-22 01:05:13 +00008186 // C++0x [class.copy]p7:
8187 // ... If the class definition declares a move constructor or move
8188 // assignment operator, the implicitly declared constructor is defined as
8189 // deleted; ...
8190 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8191 ClassDecl->hasUserDeclaredMoveAssignment() ||
8192 ShouldDeleteCopyConstructor(CopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008193 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008194
8195 return CopyConstructor;
8196}
8197
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008198void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008199 CXXConstructorDecl *CopyConstructor) {
8200 assert((CopyConstructor->isDefaulted() &&
8201 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008202 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008203 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008204
Anders Carlsson63010a72010-04-23 16:24:12 +00008205 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008206 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008207
Douglas Gregor39957dc2010-05-01 15:04:51 +00008208 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008209 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008210
Sean Huntcbb67482011-01-08 20:30:50 +00008211 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008212 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008213 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008214 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008215 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008216 } else {
8217 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8218 CopyConstructor->getLocation(),
8219 MultiStmtArg(*this, 0, 0),
8220 /*isStmtExpr=*/false)
8221 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008222 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008223
8224 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008225
8226 if (ASTMutationListener *L = getASTMutationListener()) {
8227 L->CompletedImplicitDefinition(CopyConstructor);
8228 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008229}
8230
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008231Sema::ImplicitExceptionSpecification
8232Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8233 // C++ [except.spec]p14:
8234 // An implicitly declared special member function (Clause 12) shall have an
8235 // exception-specification. [...]
8236 ImplicitExceptionSpecification ExceptSpec(Context);
8237 if (ClassDecl->isInvalidDecl())
8238 return ExceptSpec;
8239
8240 // Direct base-class constructors.
8241 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8242 BEnd = ClassDecl->bases_end();
8243 B != BEnd; ++B) {
8244 if (B->isVirtual()) // Handled below.
8245 continue;
8246
8247 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8248 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8249 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8250 // If this is a deleted function, add it anyway. This might be conformant
8251 // with the standard. This might not. I'm not sure. It might not matter.
8252 if (Constructor)
8253 ExceptSpec.CalledDecl(Constructor);
8254 }
8255 }
8256
8257 // Virtual base-class constructors.
8258 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8259 BEnd = ClassDecl->vbases_end();
8260 B != BEnd; ++B) {
8261 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8262 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8263 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8264 // If this is a deleted function, add it anyway. This might be conformant
8265 // with the standard. This might not. I'm not sure. It might not matter.
8266 if (Constructor)
8267 ExceptSpec.CalledDecl(Constructor);
8268 }
8269 }
8270
8271 // Field constructors.
8272 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8273 FEnd = ClassDecl->field_end();
8274 F != FEnd; ++F) {
8275 if (F->hasInClassInitializer()) {
8276 if (Expr *E = F->getInClassInitializer())
8277 ExceptSpec.CalledExpr(E);
8278 else if (!F->isInvalidDecl())
8279 ExceptSpec.SetDelayed();
8280 } else if (const RecordType *RecordTy
8281 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8282 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8283 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8284 // If this is a deleted function, add it anyway. This might be conformant
8285 // with the standard. This might not. I'm not sure. It might not matter.
8286 // In particular, the problem is that this function never gets called. It
8287 // might just be ill-formed because this function attempts to refer to
8288 // a deleted function here.
8289 if (Constructor)
8290 ExceptSpec.CalledDecl(Constructor);
8291 }
8292 }
8293
8294 return ExceptSpec;
8295}
8296
8297CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8298 CXXRecordDecl *ClassDecl) {
8299 ImplicitExceptionSpecification Spec(
8300 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8301
8302 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8303 QualType ArgType = Context.getRValueReferenceType(ClassType);
8304
8305 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8306
8307 DeclarationName Name
8308 = Context.DeclarationNames.getCXXConstructorName(
8309 Context.getCanonicalType(ClassType));
8310 SourceLocation ClassLoc = ClassDecl->getLocation();
8311 DeclarationNameInfo NameInfo(Name, ClassLoc);
8312
8313 // C++0x [class.copy]p11:
8314 // An implicitly-declared copy/move constructor is an inline public
8315 // member of its class.
8316 CXXConstructorDecl *MoveConstructor
8317 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8318 Context.getFunctionType(Context.VoidTy,
8319 &ArgType, 1, EPI),
8320 /*TInfo=*/0,
8321 /*isExplicit=*/false,
8322 /*isInline=*/true,
8323 /*isImplicitlyDeclared=*/true,
8324 // FIXME: apply the rules for definitions here
8325 /*isConstexpr=*/false);
8326 MoveConstructor->setAccess(AS_public);
8327 MoveConstructor->setDefaulted();
8328 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8329
8330 // Add the parameter to the constructor.
8331 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8332 ClassLoc, ClassLoc,
8333 /*IdentifierInfo=*/0,
8334 ArgType, /*TInfo=*/0,
8335 SC_None,
8336 SC_None, 0);
8337 MoveConstructor->setParams(&FromParam, 1);
8338
8339 // C++0x [class.copy]p9:
8340 // If the definition of a class X does not explicitly declare a move
8341 // constructor, one will be implicitly declared as defaulted if and only if:
8342 // [...]
8343 // - the move constructor would not be implicitly defined as deleted.
8344 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8345 // Cache this result so that we don't try to generate this over and over
8346 // on every lookup, leaking memory and wasting time.
8347 ClassDecl->setFailedImplicitMoveConstructor();
8348 return 0;
8349 }
8350
8351 // Note that we have declared this constructor.
8352 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8353
8354 if (Scope *S = getScopeForContext(ClassDecl))
8355 PushOnScopeChains(MoveConstructor, S, false);
8356 ClassDecl->addDecl(MoveConstructor);
8357
8358 return MoveConstructor;
8359}
8360
8361void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8362 CXXConstructorDecl *MoveConstructor) {
8363 assert((MoveConstructor->isDefaulted() &&
8364 MoveConstructor->isMoveConstructor() &&
8365 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8366 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8367
8368 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8369 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8370
8371 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8372 DiagnosticErrorTrap Trap(Diags);
8373
8374 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8375 Trap.hasErrorOccurred()) {
8376 Diag(CurrentLocation, diag::note_member_synthesized_at)
8377 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8378 MoveConstructor->setInvalidDecl();
8379 } else {
8380 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8381 MoveConstructor->getLocation(),
8382 MultiStmtArg(*this, 0, 0),
8383 /*isStmtExpr=*/false)
8384 .takeAs<Stmt>());
8385 }
8386
8387 MoveConstructor->setUsed();
8388
8389 if (ASTMutationListener *L = getASTMutationListener()) {
8390 L->CompletedImplicitDefinition(MoveConstructor);
8391 }
8392}
8393
John McCall60d7b3a2010-08-24 06:29:42 +00008394ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008395Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008396 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008397 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008398 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008399 unsigned ConstructKind,
8400 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008401 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008402
Douglas Gregor2f599792010-04-02 18:24:57 +00008403 // C++0x [class.copy]p34:
8404 // When certain criteria are met, an implementation is allowed to
8405 // omit the copy/move construction of a class object, even if the
8406 // copy/move constructor and/or destructor for the object have
8407 // side effects. [...]
8408 // - when a temporary class object that has not been bound to a
8409 // reference (12.2) would be copied/moved to a class object
8410 // with the same cv-unqualified type, the copy/move operation
8411 // can be omitted by constructing the temporary object
8412 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008413 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008414 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008415 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008416 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008417 }
Mike Stump1eb44332009-09-09 15:08:12 +00008418
8419 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008420 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008421 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008422}
8423
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008424/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8425/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008426ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008427Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8428 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008429 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008430 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008431 unsigned ConstructKind,
8432 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008433 unsigned NumExprs = ExprArgs.size();
8434 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008435
Nick Lewycky909a70d2011-03-25 01:44:32 +00008436 for (specific_attr_iterator<NonNullAttr>
8437 i = Constructor->specific_attr_begin<NonNullAttr>(),
8438 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8439 const NonNullAttr *NonNull = *i;
8440 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8441 }
8442
Douglas Gregor7edfb692009-11-23 12:27:39 +00008443 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008444 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00008445 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00008446 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008447 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8448 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008449}
8450
Mike Stump1eb44332009-09-09 15:08:12 +00008451bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008452 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00008453 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008454 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008455 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008456 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008457 move(Exprs), false, CXXConstructExpr::CK_Complete,
8458 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008459 if (TempResult.isInvalid())
8460 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008461
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008462 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008463 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008464 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008465 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008466 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008467
Anders Carlssonfe2de492009-08-25 05:18:00 +00008468 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008469}
8470
John McCall68c6c9a2010-02-02 09:10:11 +00008471void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008472 if (VD->isInvalidDecl()) return;
8473
John McCall68c6c9a2010-02-02 09:10:11 +00008474 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008475 if (ClassDecl->isInvalidDecl()) return;
8476 if (ClassDecl->hasTrivialDestructor()) return;
8477 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008478
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008479 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8480 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8481 CheckDestructorAccess(VD->getLocation(), Destructor,
8482 PDiag(diag::err_access_dtor_var)
8483 << VD->getDeclName()
8484 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008485
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008486 if (!VD->hasGlobalStorage()) return;
8487
8488 // Emit warning for non-trivial dtor in global scope (a real global,
8489 // class-static, function-static).
8490 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8491
8492 // TODO: this should be re-enabled for static locals by !CXAAtExit
8493 if (!VD->isStaticLocal())
8494 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008495}
8496
Mike Stump1eb44332009-09-09 15:08:12 +00008497/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008498/// ActOnDeclarator, when a C++ direct initializer is present.
8499/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00008500void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00008501 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008502 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00008503 SourceLocation RParenLoc,
8504 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00008505 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008506
8507 // If there is no declaration, there was an error parsing it. Just ignore
8508 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00008509 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008510 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008511
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008512 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8513 if (!VDecl) {
8514 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8515 RealDecl->setInvalidDecl();
8516 return;
8517 }
8518
Richard Smith34b41d92011-02-20 03:19:35 +00008519 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8520 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008521 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8522 if (Exprs.size() > 1) {
8523 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8524 diag::err_auto_var_init_multiple_expressions)
8525 << VDecl->getDeclName() << VDecl->getType()
8526 << VDecl->getSourceRange();
8527 RealDecl->setInvalidDecl();
8528 return;
8529 }
8530
8531 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00008532 TypeSourceInfo *DeducedType = 0;
8533 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00008534 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8535 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8536 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00008537 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00008538 RealDecl->setInvalidDecl();
8539 return;
8540 }
Richard Smitha085da82011-03-17 16:11:59 +00008541 VDecl->setTypeSourceInfo(DeducedType);
8542 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00008543
John McCallf85e1932011-06-15 23:02:42 +00008544 // In ARC, infer lifetime.
8545 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8546 VDecl->setInvalidDecl();
8547
Richard Smith34b41d92011-02-20 03:19:35 +00008548 // If this is a redeclaration, check that the type we just deduced matches
8549 // the previously declared type.
8550 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8551 MergeVarDeclTypes(VDecl, Old);
8552 }
8553
Douglas Gregor83ddad32009-08-26 21:14:46 +00008554 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008555 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008556 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8557 //
8558 // Clients that want to distinguish between the two forms, can check for
8559 // direct initializer using VarDecl::hasCXXDirectInitializer().
8560 // A major benefit is that clients that don't particularly care about which
8561 // exactly form was it (like the CodeGen) can handle both cases without
8562 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008563
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008564 // C++ 8.5p11:
8565 // The form of initialization (using parentheses or '=') is generally
8566 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008567 // class type.
8568
Douglas Gregor4dffad62010-02-11 22:55:30 +00008569 if (!VDecl->getType()->isDependentType() &&
8570 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00008571 diag::err_typecheck_decl_incomplete_type)) {
8572 VDecl->setInvalidDecl();
8573 return;
8574 }
8575
Douglas Gregor90f93822009-12-22 22:17:25 +00008576 // The variable can not have an abstract class type.
8577 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8578 diag::err_abstract_type_in_decl,
8579 AbstractVariableType))
8580 VDecl->setInvalidDecl();
8581
Sebastian Redl31310a22010-02-01 20:16:42 +00008582 const VarDecl *Def;
8583 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00008584 Diag(VDecl->getLocation(), diag::err_redefinition)
8585 << VDecl->getDeclName();
8586 Diag(Def->getLocation(), diag::note_previous_definition);
8587 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008588 return;
8589 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00008590
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008591 // C++ [class.static.data]p4
8592 // If a static data member is of const integral or const
8593 // enumeration type, its declaration in the class definition can
8594 // specify a constant-initializer which shall be an integral
8595 // constant expression (5.19). In that case, the member can appear
8596 // in integral constant expressions. The member shall still be
8597 // defined in a namespace scope if it is used in the program and the
8598 // namespace scope definition shall not contain an initializer.
8599 //
8600 // We already performed a redefinition check above, but for static
8601 // data members we also need to check whether there was an in-class
8602 // declaration with an initializer.
8603 const VarDecl* PrevInit = 0;
8604 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8605 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8606 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8607 return;
8608 }
8609
Douglas Gregora31040f2010-12-16 01:31:22 +00008610 bool IsDependent = false;
8611 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8612 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8613 VDecl->setInvalidDecl();
8614 return;
8615 }
8616
8617 if (Exprs.get()[I]->isTypeDependent())
8618 IsDependent = true;
8619 }
8620
Douglas Gregor4dffad62010-02-11 22:55:30 +00008621 // If either the declaration has a dependent type or if any of the
8622 // expressions is type-dependent, we represent the initialization
8623 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00008624 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00008625 // Let clients know that initialization was done with a direct initializer.
8626 VDecl->setCXXDirectInitializer(true);
8627
8628 // Store the initialization expressions as a ParenListExpr.
8629 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00008630 VDecl->setInit(new (Context) ParenListExpr(
8631 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8632 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00008633 return;
8634 }
Douglas Gregor90f93822009-12-22 22:17:25 +00008635
8636 // Capture the variable that is being initialized and the style of
8637 // initialization.
8638 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8639
8640 // FIXME: Poor source location information.
8641 InitializationKind Kind
8642 = InitializationKind::CreateDirect(VDecl->getLocation(),
8643 LParenLoc, RParenLoc);
8644
8645 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00008646 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00008647 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00008648 if (Result.isInvalid()) {
8649 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008650 return;
8651 }
John McCallb4eb64d2010-10-08 02:01:28 +00008652
8653 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00008654
Douglas Gregor53c374f2010-12-07 00:41:46 +00008655 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00008656 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008657 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008658
John McCall2998d6b2011-01-19 11:48:09 +00008659 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008660}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008661
Douglas Gregor39da0b82009-09-09 23:08:42 +00008662/// \brief Given a constructor and the set of arguments provided for the
8663/// constructor, convert the arguments and add any required default arguments
8664/// to form a proper call to this constructor.
8665///
8666/// \returns true if an error occurred, false otherwise.
8667bool
8668Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8669 MultiExprArg ArgsPtr,
8670 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00008671 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00008672 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8673 unsigned NumArgs = ArgsPtr.size();
8674 Expr **Args = (Expr **)ArgsPtr.get();
8675
8676 const FunctionProtoType *Proto
8677 = Constructor->getType()->getAs<FunctionProtoType>();
8678 assert(Proto && "Constructor without a prototype?");
8679 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00008680
8681 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008682 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00008683 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008684 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00008685 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008686
8687 VariadicCallType CallType =
8688 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008689 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008690 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8691 Proto, 0, Args, NumArgs, AllArgs,
8692 CallType);
8693 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8694 ConvertedArgs.push_back(AllArgs[i]);
8695 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008696}
8697
Anders Carlsson20d45d22009-12-12 00:32:00 +00008698static inline bool
8699CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8700 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008701 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00008702 if (isa<NamespaceDecl>(DC)) {
8703 return SemaRef.Diag(FnDecl->getLocation(),
8704 diag::err_operator_new_delete_declared_in_namespace)
8705 << FnDecl->getDeclName();
8706 }
8707
8708 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00008709 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008710 return SemaRef.Diag(FnDecl->getLocation(),
8711 diag::err_operator_new_delete_declared_static)
8712 << FnDecl->getDeclName();
8713 }
8714
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00008715 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00008716}
8717
Anders Carlsson156c78e2009-12-13 17:53:43 +00008718static inline bool
8719CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8720 CanQualType ExpectedResultType,
8721 CanQualType ExpectedFirstParamType,
8722 unsigned DependentParamTypeDiag,
8723 unsigned InvalidParamTypeDiag) {
8724 QualType ResultType =
8725 FnDecl->getType()->getAs<FunctionType>()->getResultType();
8726
8727 // Check that the result type is not dependent.
8728 if (ResultType->isDependentType())
8729 return SemaRef.Diag(FnDecl->getLocation(),
8730 diag::err_operator_new_delete_dependent_result_type)
8731 << FnDecl->getDeclName() << ExpectedResultType;
8732
8733 // Check that the result type is what we expect.
8734 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8735 return SemaRef.Diag(FnDecl->getLocation(),
8736 diag::err_operator_new_delete_invalid_result_type)
8737 << FnDecl->getDeclName() << ExpectedResultType;
8738
8739 // A function template must have at least 2 parameters.
8740 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8741 return SemaRef.Diag(FnDecl->getLocation(),
8742 diag::err_operator_new_delete_template_too_few_parameters)
8743 << FnDecl->getDeclName();
8744
8745 // The function decl must have at least 1 parameter.
8746 if (FnDecl->getNumParams() == 0)
8747 return SemaRef.Diag(FnDecl->getLocation(),
8748 diag::err_operator_new_delete_too_few_parameters)
8749 << FnDecl->getDeclName();
8750
8751 // Check the the first parameter type is not dependent.
8752 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8753 if (FirstParamType->isDependentType())
8754 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8755 << FnDecl->getDeclName() << ExpectedFirstParamType;
8756
8757 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00008758 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00008759 ExpectedFirstParamType)
8760 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8761 << FnDecl->getDeclName() << ExpectedFirstParamType;
8762
8763 return false;
8764}
8765
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008766static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00008767CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008768 // C++ [basic.stc.dynamic.allocation]p1:
8769 // A program is ill-formed if an allocation function is declared in a
8770 // namespace scope other than global scope or declared static in global
8771 // scope.
8772 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8773 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00008774
8775 CanQualType SizeTy =
8776 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8777
8778 // C++ [basic.stc.dynamic.allocation]p1:
8779 // The return type shall be void*. The first parameter shall have type
8780 // std::size_t.
8781 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8782 SizeTy,
8783 diag::err_operator_new_dependent_param_type,
8784 diag::err_operator_new_param_type))
8785 return true;
8786
8787 // C++ [basic.stc.dynamic.allocation]p1:
8788 // The first parameter shall not have an associated default argument.
8789 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00008790 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00008791 diag::err_operator_new_default_arg)
8792 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8793
8794 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00008795}
8796
8797static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008798CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8799 // C++ [basic.stc.dynamic.deallocation]p1:
8800 // A program is ill-formed if deallocation functions are declared in a
8801 // namespace scope other than global scope or declared static in global
8802 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00008803 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8804 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008805
8806 // C++ [basic.stc.dynamic.deallocation]p2:
8807 // Each deallocation function shall return void and its first parameter
8808 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00008809 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8810 SemaRef.Context.VoidPtrTy,
8811 diag::err_operator_delete_dependent_param_type,
8812 diag::err_operator_delete_param_type))
8813 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008814
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008815 return false;
8816}
8817
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008818/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8819/// of this overloaded operator is well-formed. If so, returns false;
8820/// otherwise, emits appropriate diagnostics and returns true.
8821bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008822 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008823 "Expected an overloaded operator declaration");
8824
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008825 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8826
Mike Stump1eb44332009-09-09 15:08:12 +00008827 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008828 // The allocation and deallocation functions, operator new,
8829 // operator new[], operator delete and operator delete[], are
8830 // described completely in 3.7.3. The attributes and restrictions
8831 // found in the rest of this subclause do not apply to them unless
8832 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00008833 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008834 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00008835
Anders Carlssona3ccda52009-12-12 00:26:23 +00008836 if (Op == OO_New || Op == OO_Array_New)
8837 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008838
8839 // C++ [over.oper]p6:
8840 // An operator function shall either be a non-static member
8841 // function or be a non-member function and have at least one
8842 // parameter whose type is a class, a reference to a class, an
8843 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008844 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8845 if (MethodDecl->isStatic())
8846 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008847 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008848 } else {
8849 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008850 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8851 ParamEnd = FnDecl->param_end();
8852 Param != ParamEnd; ++Param) {
8853 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00008854 if (ParamType->isDependentType() || ParamType->isRecordType() ||
8855 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008856 ClassOrEnumParam = true;
8857 break;
8858 }
8859 }
8860
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008861 if (!ClassOrEnumParam)
8862 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008863 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008864 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008865 }
8866
8867 // C++ [over.oper]p8:
8868 // An operator function cannot have default arguments (8.3.6),
8869 // except where explicitly stated below.
8870 //
Mike Stump1eb44332009-09-09 15:08:12 +00008871 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008872 // (C++ [over.call]p1).
8873 if (Op != OO_Call) {
8874 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8875 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00008876 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00008877 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00008878 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00008879 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008880 }
8881 }
8882
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008883 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8884 { false, false, false }
8885#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8886 , { Unary, Binary, MemberOnly }
8887#include "clang/Basic/OperatorKinds.def"
8888 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008889
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008890 bool CanBeUnaryOperator = OperatorUses[Op][0];
8891 bool CanBeBinaryOperator = OperatorUses[Op][1];
8892 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008893
8894 // C++ [over.oper]p8:
8895 // [...] Operator functions cannot have more or fewer parameters
8896 // than the number required for the corresponding operator, as
8897 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00008898 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008899 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008900 if (Op != OO_Call &&
8901 ((NumParams == 1 && !CanBeUnaryOperator) ||
8902 (NumParams == 2 && !CanBeBinaryOperator) ||
8903 (NumParams < 1) || (NumParams > 2))) {
8904 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00008905 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008906 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008907 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008908 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008909 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008910 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00008911 assert(CanBeBinaryOperator &&
8912 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00008913 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008914 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008915
Chris Lattner416e46f2008-11-21 07:57:12 +00008916 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008917 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008918 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00008919
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008920 // Overloaded operators other than operator() cannot be variadic.
8921 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00008922 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008923 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008924 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008925 }
8926
8927 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008928 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
8929 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008930 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008931 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008932 }
8933
8934 // C++ [over.inc]p1:
8935 // The user-defined function called operator++ implements the
8936 // prefix and postfix ++ operator. If this function is a member
8937 // function with no parameters, or a non-member function with one
8938 // parameter of class or enumeration type, it defines the prefix
8939 // increment operator ++ for objects of that type. If the function
8940 // is a member function with one parameter (which shall be of type
8941 // int) or a non-member function with two parameters (the second
8942 // of which shall be of type int), it defines the postfix
8943 // increment operator ++ for objects of that type.
8944 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
8945 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
8946 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00008947 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008948 ParamIsInt = BT->getKind() == BuiltinType::Int;
8949
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00008950 if (!ParamIsInt)
8951 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00008952 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00008953 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008954 }
8955
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008956 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008957}
Chris Lattner5a003a42008-12-17 07:09:26 +00008958
Sean Hunta6c058d2010-01-13 09:01:02 +00008959/// CheckLiteralOperatorDeclaration - Check whether the declaration
8960/// of this literal operator function is well-formed. If so, returns
8961/// false; otherwise, emits appropriate diagnostics and returns true.
8962bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
8963 DeclContext *DC = FnDecl->getDeclContext();
8964 Decl::Kind Kind = DC->getDeclKind();
8965 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
8966 Kind != Decl::LinkageSpec) {
8967 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
8968 << FnDecl->getDeclName();
8969 return true;
8970 }
8971
8972 bool Valid = false;
8973
Sean Hunt216c2782010-04-07 23:11:06 +00008974 // template <char...> type operator "" name() is the only valid template
8975 // signature, and the only valid signature with no parameters.
8976 if (FnDecl->param_size() == 0) {
8977 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
8978 // Must have only one template parameter
8979 TemplateParameterList *Params = TpDecl->getTemplateParameters();
8980 if (Params->size() == 1) {
8981 NonTypeTemplateParmDecl *PmDecl =
8982 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00008983
Sean Hunt216c2782010-04-07 23:11:06 +00008984 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00008985 if (PmDecl && PmDecl->isTemplateParameterPack() &&
8986 Context.hasSameType(PmDecl->getType(), Context.CharTy))
8987 Valid = true;
8988 }
8989 }
8990 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00008991 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00008992 FunctionDecl::param_iterator Param = FnDecl->param_begin();
8993
Sean Hunta6c058d2010-01-13 09:01:02 +00008994 QualType T = (*Param)->getType();
8995
Sean Hunt30019c02010-04-07 22:57:35 +00008996 // unsigned long long int, long double, and any character type are allowed
8997 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00008998 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
8999 Context.hasSameType(T, Context.LongDoubleTy) ||
9000 Context.hasSameType(T, Context.CharTy) ||
9001 Context.hasSameType(T, Context.WCharTy) ||
9002 Context.hasSameType(T, Context.Char16Ty) ||
9003 Context.hasSameType(T, Context.Char32Ty)) {
9004 if (++Param == FnDecl->param_end())
9005 Valid = true;
9006 goto FinishedParams;
9007 }
9008
Sean Hunt30019c02010-04-07 22:57:35 +00009009 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009010 const PointerType *PT = T->getAs<PointerType>();
9011 if (!PT)
9012 goto FinishedParams;
9013 T = PT->getPointeeType();
9014 if (!T.isConstQualified())
9015 goto FinishedParams;
9016 T = T.getUnqualifiedType();
9017
9018 // Move on to the second parameter;
9019 ++Param;
9020
9021 // If there is no second parameter, the first must be a const char *
9022 if (Param == FnDecl->param_end()) {
9023 if (Context.hasSameType(T, Context.CharTy))
9024 Valid = true;
9025 goto FinishedParams;
9026 }
9027
9028 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9029 // are allowed as the first parameter to a two-parameter function
9030 if (!(Context.hasSameType(T, Context.CharTy) ||
9031 Context.hasSameType(T, Context.WCharTy) ||
9032 Context.hasSameType(T, Context.Char16Ty) ||
9033 Context.hasSameType(T, Context.Char32Ty)))
9034 goto FinishedParams;
9035
9036 // The second and final parameter must be an std::size_t
9037 T = (*Param)->getType().getUnqualifiedType();
9038 if (Context.hasSameType(T, Context.getSizeType()) &&
9039 ++Param == FnDecl->param_end())
9040 Valid = true;
9041 }
9042
9043 // FIXME: This diagnostic is absolutely terrible.
9044FinishedParams:
9045 if (!Valid) {
9046 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9047 << FnDecl->getDeclName();
9048 return true;
9049 }
9050
9051 return false;
9052}
9053
Douglas Gregor074149e2009-01-05 19:45:36 +00009054/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9055/// linkage specification, including the language and (if present)
9056/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9057/// the location of the language string literal, which is provided
9058/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9059/// the '{' brace. Otherwise, this linkage specification does not
9060/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009061Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9062 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009063 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009064 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009065 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009066 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009067 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009068 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009069 Language = LinkageSpecDecl::lang_cxx;
9070 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009071 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009072 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009073 }
Mike Stump1eb44332009-09-09 15:08:12 +00009074
Chris Lattnercc98eac2008-12-17 07:13:27 +00009075 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009076
Douglas Gregor074149e2009-01-05 19:45:36 +00009077 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009078 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009079 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009080 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009081 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009082}
9083
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009084/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009085/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9086/// valid, it's the position of the closing '}' brace in a linkage
9087/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009088Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009089 Decl *LinkageSpec,
9090 SourceLocation RBraceLoc) {
9091 if (LinkageSpec) {
9092 if (RBraceLoc.isValid()) {
9093 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9094 LSDecl->setRBraceLoc(RBraceLoc);
9095 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009096 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009097 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009098 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009099}
9100
Douglas Gregord308e622009-05-18 20:51:54 +00009101/// \brief Perform semantic analysis for the variable declaration that
9102/// occurs within a C++ catch clause, returning the newly-created
9103/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009104VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009105 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009106 SourceLocation StartLoc,
9107 SourceLocation Loc,
9108 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009109 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009110 QualType ExDeclType = TInfo->getType();
9111
Sebastian Redl4b07b292008-12-22 19:15:10 +00009112 // Arrays and functions decay.
9113 if (ExDeclType->isArrayType())
9114 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9115 else if (ExDeclType->isFunctionType())
9116 ExDeclType = Context.getPointerType(ExDeclType);
9117
9118 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9119 // The exception-declaration shall not denote a pointer or reference to an
9120 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009121 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009122 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009123 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009124 Invalid = true;
9125 }
Douglas Gregord308e622009-05-18 20:51:54 +00009126
Douglas Gregora2762912010-03-08 01:47:36 +00009127 // GCC allows catching pointers and references to incomplete types
9128 // as an extension; so do we, but we warn by default.
9129
Sebastian Redl4b07b292008-12-22 19:15:10 +00009130 QualType BaseType = ExDeclType;
9131 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009132 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00009133 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00009134 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009135 BaseType = Ptr->getPointeeType();
9136 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00009137 DK = diag::ext_catch_incomplete_ptr;
9138 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009139 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009140 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009141 BaseType = Ref->getPointeeType();
9142 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00009143 DK = diag::ext_catch_incomplete_ref;
9144 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009145 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009146 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00009147 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9148 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00009149 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009150
Mike Stump1eb44332009-09-09 15:08:12 +00009151 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009152 RequireNonAbstractType(Loc, ExDeclType,
9153 diag::err_abstract_type_in_decl,
9154 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009155 Invalid = true;
9156
John McCall5a180392010-07-24 00:37:23 +00009157 // Only the non-fragile NeXT runtime currently supports C++ catches
9158 // of ObjC types, and no runtime supports catching ObjC types by value.
9159 if (!Invalid && getLangOptions().ObjC1) {
9160 QualType T = ExDeclType;
9161 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9162 T = RT->getPointeeType();
9163
9164 if (T->isObjCObjectType()) {
9165 Diag(Loc, diag::err_objc_object_catch);
9166 Invalid = true;
9167 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009168 if (!getLangOptions().ObjCNonFragileABI)
9169 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009170 }
9171 }
9172
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009173 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9174 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009175 ExDecl->setExceptionVariable(true);
9176
Douglas Gregorc41b8782011-07-06 18:14:43 +00009177 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009178 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009179 // C++ [except.handle]p16:
9180 // The object declared in an exception-declaration or, if the
9181 // exception-declaration does not specify a name, a temporary (12.2) is
9182 // copy-initialized (8.5) from the exception object. [...]
9183 // The object is destroyed when the handler exits, after the destruction
9184 // of any automatic objects initialized within the handler.
9185 //
9186 // We just pretend to initialize the object with itself, then make sure
9187 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009188 QualType initType = ExDeclType;
9189
9190 InitializedEntity entity =
9191 InitializedEntity::InitializeVariable(ExDecl);
9192 InitializationKind initKind =
9193 InitializationKind::CreateCopy(Loc, SourceLocation());
9194
9195 Expr *opaqueValue =
9196 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9197 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9198 ExprResult result = sequence.Perform(*this, entity, initKind,
9199 MultiExprArg(&opaqueValue, 1));
9200 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009201 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009202 else {
9203 // If the constructor used was non-trivial, set this as the
9204 // "initializer".
9205 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9206 if (!construct->getConstructor()->isTrivial()) {
9207 Expr *init = MaybeCreateExprWithCleanups(construct);
9208 ExDecl->setInit(init);
9209 }
9210
9211 // And make sure it's destructable.
9212 FinalizeVarWithDestructor(ExDecl, recordType);
9213 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009214 }
9215 }
9216
Douglas Gregord308e622009-05-18 20:51:54 +00009217 if (Invalid)
9218 ExDecl->setInvalidDecl();
9219
9220 return ExDecl;
9221}
9222
9223/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9224/// handler.
John McCalld226f652010-08-21 09:40:31 +00009225Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009226 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009227 bool Invalid = D.isInvalidType();
9228
9229 // Check for unexpanded parameter packs.
9230 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9231 UPPC_ExceptionType)) {
9232 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9233 D.getIdentifierLoc());
9234 Invalid = true;
9235 }
9236
Sebastian Redl4b07b292008-12-22 19:15:10 +00009237 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009238 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009239 LookupOrdinaryName,
9240 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009241 // The scope should be freshly made just for us. There is just no way
9242 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009243 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009244 if (PrevDecl->isTemplateParameter()) {
9245 // Maybe we will complain about the shadowed template parameter.
9246 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009247 }
9248 }
9249
Chris Lattnereaaebc72009-04-25 08:06:05 +00009250 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009251 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9252 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009253 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009254 }
9255
Douglas Gregor83cb9422010-09-09 17:09:21 +00009256 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009257 D.getSourceRange().getBegin(),
9258 D.getIdentifierLoc(),
9259 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009260 if (Invalid)
9261 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009262
Sebastian Redl4b07b292008-12-22 19:15:10 +00009263 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009264 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009265 PushOnScopeChains(ExDecl, S);
9266 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009267 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009268
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009269 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009270 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009271}
Anders Carlssonfb311762009-03-14 00:25:26 +00009272
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009273Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009274 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009275 Expr *AssertMessageExpr_,
9276 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009277 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009278
Anders Carlssonc3082412009-03-14 00:33:21 +00009279 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9280 llvm::APSInt Value(32);
9281 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009282 Diag(StaticAssertLoc,
9283 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00009284 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009285 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00009286 }
Anders Carlssonfb311762009-03-14 00:25:26 +00009287
Anders Carlssonc3082412009-03-14 00:33:21 +00009288 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009289 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009290 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009291 }
9292 }
Mike Stump1eb44332009-09-09 15:08:12 +00009293
Douglas Gregor399ad972010-12-15 23:55:21 +00009294 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9295 return 0;
9296
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009297 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9298 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009299
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009300 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009301 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009302}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009303
Douglas Gregor1d869352010-04-07 16:53:43 +00009304/// \brief Perform semantic analysis of the given friend type declaration.
9305///
9306/// \returns A friend declaration that.
9307FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9308 TypeSourceInfo *TSInfo) {
9309 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9310
9311 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009312 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009313
Douglas Gregor06245bf2010-04-07 17:57:12 +00009314 if (!getLangOptions().CPlusPlus0x) {
9315 // C++03 [class.friend]p2:
9316 // An elaborated-type-specifier shall be used in a friend declaration
9317 // for a class.*
9318 //
9319 // * The class-key of the elaborated-type-specifier is required.
9320 if (!ActiveTemplateInstantiations.empty()) {
9321 // Do not complain about the form of friend template types during
9322 // template instantiation; we will already have complained when the
9323 // template was declared.
9324 } else if (!T->isElaboratedTypeSpecifier()) {
9325 // If we evaluated the type to a record type, suggest putting
9326 // a tag in front.
9327 if (const RecordType *RT = T->getAs<RecordType>()) {
9328 RecordDecl *RD = RT->getDecl();
9329
9330 std::string InsertionText = std::string(" ") + RD->getKindName();
9331
9332 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9333 << (unsigned) RD->getTagKind()
9334 << T
9335 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9336 InsertionText);
9337 } else {
9338 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9339 << T
9340 << SourceRange(FriendLoc, TypeRange.getEnd());
9341 }
9342 } else if (T->getAs<EnumType>()) {
9343 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009344 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009345 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009346 }
9347 }
9348
Douglas Gregor06245bf2010-04-07 17:57:12 +00009349 // C++0x [class.friend]p3:
9350 // If the type specifier in a friend declaration designates a (possibly
9351 // cv-qualified) class type, that class is declared as a friend; otherwise,
9352 // the friend declaration is ignored.
9353
9354 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9355 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009356
9357 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9358}
9359
John McCall9a34edb2010-10-19 01:40:49 +00009360/// Handle a friend tag declaration where the scope specifier was
9361/// templated.
9362Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9363 unsigned TagSpec, SourceLocation TagLoc,
9364 CXXScopeSpec &SS,
9365 IdentifierInfo *Name, SourceLocation NameLoc,
9366 AttributeList *Attr,
9367 MultiTemplateParamsArg TempParamLists) {
9368 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9369
9370 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009371 bool Invalid = false;
9372
9373 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009374 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009375 TempParamLists.get(),
9376 TempParamLists.size(),
9377 /*friend*/ true,
9378 isExplicitSpecialization,
9379 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009380 if (TemplateParams->size() > 0) {
9381 // This is a declaration of a class template.
9382 if (Invalid)
9383 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009384
Eric Christopher4110e132011-07-21 05:34:24 +00009385 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9386 SS, Name, NameLoc, Attr,
9387 TemplateParams, AS_public,
9388 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009389 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009390 } else {
9391 // The "template<>" header is extraneous.
9392 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9393 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9394 isExplicitSpecialization = true;
9395 }
9396 }
9397
9398 if (Invalid) return 0;
9399
9400 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9401
9402 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009403 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009404 if (TempParamLists.get()[I]->size()) {
9405 isAllExplicitSpecializations = false;
9406 break;
9407 }
9408 }
9409
9410 // FIXME: don't ignore attributes.
9411
9412 // If it's explicit specializations all the way down, just forget
9413 // about the template header and build an appropriate non-templated
9414 // friend. TODO: for source fidelity, remember the headers.
9415 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00009416 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009417 ElaboratedTypeKeyword Keyword
9418 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009419 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009420 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009421 if (T.isNull())
9422 return 0;
9423
9424 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9425 if (isa<DependentNameType>(T)) {
9426 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9427 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009428 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009429 TL.setNameLoc(NameLoc);
9430 } else {
9431 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9432 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009433 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009434 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9435 }
9436
9437 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9438 TSI, FriendLoc);
9439 Friend->setAccess(AS_public);
9440 CurContext->addDecl(Friend);
9441 return Friend;
9442 }
9443
9444 // Handle the case of a templated-scope friend class. e.g.
9445 // template <class T> class A<T>::B;
9446 // FIXME: we don't support these right now.
9447 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9448 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9449 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9450 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9451 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009452 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009453 TL.setNameLoc(NameLoc);
9454
9455 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9456 TSI, FriendLoc);
9457 Friend->setAccess(AS_public);
9458 Friend->setUnsupportedFriend(true);
9459 CurContext->addDecl(Friend);
9460 return Friend;
9461}
9462
9463
John McCalldd4a3b02009-09-16 22:47:08 +00009464/// Handle a friend type declaration. This works in tandem with
9465/// ActOnTag.
9466///
9467/// Notes on friend class templates:
9468///
9469/// We generally treat friend class declarations as if they were
9470/// declaring a class. So, for example, the elaborated type specifier
9471/// in a friend declaration is required to obey the restrictions of a
9472/// class-head (i.e. no typedefs in the scope chain), template
9473/// parameters are required to match up with simple template-ids, &c.
9474/// However, unlike when declaring a template specialization, it's
9475/// okay to refer to a template specialization without an empty
9476/// template parameter declaration, e.g.
9477/// friend class A<T>::B<unsigned>;
9478/// We permit this as a special case; if there are any template
9479/// parameters present at all, require proper matching, i.e.
9480/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009481Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009482 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00009483 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00009484
9485 assert(DS.isFriendSpecified());
9486 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9487
John McCalldd4a3b02009-09-16 22:47:08 +00009488 // Try to convert the decl specifier to a type. This works for
9489 // friend templates because ActOnTag never produces a ClassTemplateDecl
9490 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009491 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009492 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9493 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009494 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009495 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009496
Douglas Gregor6ccab972010-12-16 01:14:37 +00009497 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9498 return 0;
9499
John McCalldd4a3b02009-09-16 22:47:08 +00009500 // This is definitely an error in C++98. It's probably meant to
9501 // be forbidden in C++0x, too, but the specification is just
9502 // poorly written.
9503 //
9504 // The problem is with declarations like the following:
9505 // template <T> friend A<T>::foo;
9506 // where deciding whether a class C is a friend or not now hinges
9507 // on whether there exists an instantiation of A that causes
9508 // 'foo' to equal C. There are restrictions on class-heads
9509 // (which we declare (by fiat) elaborated friend declarations to
9510 // be) that makes this tractable.
9511 //
9512 // FIXME: handle "template <> friend class A<T>;", which
9513 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009514 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009515 Diag(Loc, diag::err_tagless_friend_type_template)
9516 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009517 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009518 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009519
John McCall02cace72009-08-28 07:59:38 +00009520 // C++98 [class.friend]p1: A friend of a class is a function
9521 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009522 // This is fixed in DR77, which just barely didn't make the C++03
9523 // deadline. It's also a very silly restriction that seriously
9524 // affects inner classes and which nobody else seems to implement;
9525 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009526 //
9527 // But note that we could warn about it: it's always useless to
9528 // friend one of your own members (it's not, however, worthless to
9529 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009530
John McCalldd4a3b02009-09-16 22:47:08 +00009531 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009532 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009533 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009534 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009535 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009536 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009537 DS.getFriendSpecLoc());
9538 else
Douglas Gregor1d869352010-04-07 16:53:43 +00009539 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9540
9541 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009542 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009543
John McCalldd4a3b02009-09-16 22:47:08 +00009544 D->setAccess(AS_public);
9545 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009546
John McCalld226f652010-08-21 09:40:31 +00009547 return D;
John McCall02cace72009-08-28 07:59:38 +00009548}
9549
John McCall337ec3d2010-10-12 23:13:28 +00009550Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9551 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009552 const DeclSpec &DS = D.getDeclSpec();
9553
9554 assert(DS.isFriendSpecified());
9555 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9556
9557 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009558 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9559 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00009560
9561 // C++ [class.friend]p1
9562 // A friend of a class is a function or class....
9563 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009564 // It *doesn't* see through dependent types, which is correct
9565 // according to [temp.arg.type]p3:
9566 // If a declaration acquires a function type through a
9567 // type dependent on a template-parameter and this causes
9568 // a declaration that does not use the syntactic form of a
9569 // function declarator to have a function type, the program
9570 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00009571 if (!T->isFunctionType()) {
9572 Diag(Loc, diag::err_unexpected_friend);
9573
9574 // It might be worthwhile to try to recover by creating an
9575 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009576 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009577 }
9578
9579 // C++ [namespace.memdef]p3
9580 // - If a friend declaration in a non-local class first declares a
9581 // class or function, the friend class or function is a member
9582 // of the innermost enclosing namespace.
9583 // - The name of the friend is not found by simple name lookup
9584 // until a matching declaration is provided in that namespace
9585 // scope (either before or after the class declaration granting
9586 // friendship).
9587 // - If a friend function is called, its name may be found by the
9588 // name lookup that considers functions from namespaces and
9589 // classes associated with the types of the function arguments.
9590 // - When looking for a prior declaration of a class or a function
9591 // declared as a friend, scopes outside the innermost enclosing
9592 // namespace scope are not considered.
9593
John McCall337ec3d2010-10-12 23:13:28 +00009594 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00009595 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9596 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00009597 assert(Name);
9598
Douglas Gregor6ccab972010-12-16 01:14:37 +00009599 // Check for unexpanded parameter packs.
9600 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9601 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9602 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9603 return 0;
9604
John McCall67d1a672009-08-06 02:15:43 +00009605 // The context we found the declaration in, or in which we should
9606 // create the declaration.
9607 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00009608 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00009609 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00009610 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00009611
John McCall337ec3d2010-10-12 23:13:28 +00009612 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00009613
John McCall337ec3d2010-10-12 23:13:28 +00009614 // There are four cases here.
9615 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00009616 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00009617 // there as appropriate.
9618 // Recover from invalid scope qualifiers as if they just weren't there.
9619 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00009620 // C++0x [namespace.memdef]p3:
9621 // If the name in a friend declaration is neither qualified nor
9622 // a template-id and the declaration is a function or an
9623 // elaborated-type-specifier, the lookup to determine whether
9624 // the entity has been previously declared shall not consider
9625 // any scopes outside the innermost enclosing namespace.
9626 // C++0x [class.friend]p11:
9627 // If a friend declaration appears in a local class and the name
9628 // specified is an unqualified name, a prior declaration is
9629 // looked up without considering scopes that are outside the
9630 // innermost enclosing non-class scope. For a friend function
9631 // declaration, if there is no prior declaration, the program is
9632 // ill-formed.
9633 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00009634 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00009635
John McCall29ae6e52010-10-13 05:45:15 +00009636 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00009637 DC = CurContext;
9638 while (true) {
9639 // Skip class contexts. If someone can cite chapter and verse
9640 // for this behavior, that would be nice --- it's what GCC and
9641 // EDG do, and it seems like a reasonable intent, but the spec
9642 // really only says that checks for unqualified existing
9643 // declarations should stop at the nearest enclosing namespace,
9644 // not that they should only consider the nearest enclosing
9645 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00009646 while (DC->isRecord())
9647 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00009648
John McCall68263142009-11-18 22:49:29 +00009649 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00009650
9651 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00009652 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00009653 break;
John McCall29ae6e52010-10-13 05:45:15 +00009654
John McCall8a407372010-10-14 22:22:28 +00009655 if (isTemplateId) {
9656 if (isa<TranslationUnitDecl>(DC)) break;
9657 } else {
9658 if (DC->isFileContext()) break;
9659 }
John McCall67d1a672009-08-06 02:15:43 +00009660 DC = DC->getParent();
9661 }
9662
9663 // C++ [class.friend]p1: A friend of a class is a function or
9664 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00009665 // C++0x changes this for both friend types and functions.
9666 // Most C++ 98 compilers do seem to give an error here, so
9667 // we do, too.
John McCall68263142009-11-18 22:49:29 +00009668 if (!Previous.empty() && DC->Equals(CurContext)
9669 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00009670 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00009671
John McCall380aaa42010-10-13 06:22:15 +00009672 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00009673
John McCall337ec3d2010-10-12 23:13:28 +00009674 // - There's a non-dependent scope specifier, in which case we
9675 // compute it and do a previous lookup there for a function
9676 // or function template.
9677 } else if (!SS.getScopeRep()->isDependent()) {
9678 DC = computeDeclContext(SS);
9679 if (!DC) return 0;
9680
9681 if (RequireCompleteDeclContext(SS, DC)) return 0;
9682
9683 LookupQualifiedName(Previous, DC);
9684
9685 // Ignore things found implicitly in the wrong scope.
9686 // TODO: better diagnostics for this case. Suggesting the right
9687 // qualified scope would be nice...
9688 LookupResult::Filter F = Previous.makeFilter();
9689 while (F.hasNext()) {
9690 NamedDecl *D = F.next();
9691 if (!DC->InEnclosingNamespaceSetOf(
9692 D->getDeclContext()->getRedeclContext()))
9693 F.erase();
9694 }
9695 F.done();
9696
9697 if (Previous.empty()) {
9698 D.setInvalidType();
9699 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9700 return 0;
9701 }
9702
9703 // C++ [class.friend]p1: A friend of a class is a function or
9704 // class that is not a member of the class . . .
9705 if (DC->Equals(CurContext))
9706 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9707
9708 // - There's a scope specifier that does not match any template
9709 // parameter lists, in which case we use some arbitrary context,
9710 // create a method or method template, and wait for instantiation.
9711 // - There's a scope specifier that does match some template
9712 // parameter lists, which we don't handle right now.
9713 } else {
9714 DC = CurContext;
9715 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00009716 }
9717
John McCall29ae6e52010-10-13 05:45:15 +00009718 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00009719 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009720 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9721 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9722 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00009723 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009724 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9725 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00009726 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009727 }
John McCall67d1a672009-08-06 02:15:43 +00009728 }
9729
Douglas Gregor182ddf02009-09-28 00:08:27 +00009730 bool Redeclaration = false;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009731 bool AddToScope = true;
John McCall380aaa42010-10-13 06:22:15 +00009732 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00009733 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00009734 IsDefinition,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009735 Redeclaration, AddToScope);
John McCalld226f652010-08-21 09:40:31 +00009736 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00009737
Douglas Gregor182ddf02009-09-28 00:08:27 +00009738 assert(ND->getDeclContext() == DC);
9739 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00009740
John McCallab88d972009-08-31 22:39:49 +00009741 // Add the function declaration to the appropriate lookup tables,
9742 // adjusting the redeclarations list as necessary. We don't
9743 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00009744 //
John McCallab88d972009-08-31 22:39:49 +00009745 // Also update the scope-based lookup if the target context's
9746 // lookup context is in lexical scope.
9747 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009748 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00009749 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009750 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00009751 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009752 }
John McCall02cace72009-08-28 07:59:38 +00009753
9754 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00009755 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00009756 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00009757 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00009758 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00009759
John McCall337ec3d2010-10-12 23:13:28 +00009760 if (ND->isInvalidDecl())
9761 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00009762 else {
9763 FunctionDecl *FD;
9764 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9765 FD = FTD->getTemplatedDecl();
9766 else
9767 FD = cast<FunctionDecl>(ND);
9768
9769 // Mark templated-scope function declarations as unsupported.
9770 if (FD->getNumTemplateParameterLists())
9771 FrD->setUnsupportedFriend(true);
9772 }
John McCall337ec3d2010-10-12 23:13:28 +00009773
John McCalld226f652010-08-21 09:40:31 +00009774 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00009775}
9776
John McCalld226f652010-08-21 09:40:31 +00009777void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9778 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00009779
Sebastian Redl50de12f2009-03-24 22:27:57 +00009780 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9781 if (!Fn) {
9782 Diag(DelLoc, diag::err_deleted_non_function);
9783 return;
9784 }
9785 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9786 Diag(DelLoc, diag::err_deleted_decl_not_first);
9787 Diag(Prev->getLocation(), diag::note_previous_declaration);
9788 // If the declaration wasn't the first, we delete the function anyway for
9789 // recovery.
9790 }
Sean Hunt10620eb2011-05-06 20:44:56 +00009791 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00009792}
Sebastian Redl13e88542009-04-27 21:33:24 +00009793
Sean Hunte4246a62011-05-12 06:15:49 +00009794void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9795 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9796
9797 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00009798 if (MD->getParent()->isDependentType()) {
9799 MD->setDefaulted();
9800 MD->setExplicitlyDefaulted();
9801 return;
9802 }
9803
Sean Hunte4246a62011-05-12 06:15:49 +00009804 CXXSpecialMember Member = getSpecialMember(MD);
9805 if (Member == CXXInvalid) {
9806 Diag(DefaultLoc, diag::err_default_special_members);
9807 return;
9808 }
9809
9810 MD->setDefaulted();
9811 MD->setExplicitlyDefaulted();
9812
Sean Huntcd10dec2011-05-23 23:14:04 +00009813 // If this definition appears within the record, do the checking when
9814 // the record is complete.
9815 const FunctionDecl *Primary = MD;
9816 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9817 // Find the uninstantiated declaration that actually had the '= default'
9818 // on it.
9819 MD->getTemplateInstantiationPattern()->isDefined(Primary);
9820
9821 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00009822 return;
9823
9824 switch (Member) {
9825 case CXXDefaultConstructor: {
9826 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9827 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009828 if (!CD->isInvalidDecl())
9829 DefineImplicitDefaultConstructor(DefaultLoc, CD);
9830 break;
9831 }
9832
9833 case CXXCopyConstructor: {
9834 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9835 CheckExplicitlyDefaultedCopyConstructor(CD);
9836 if (!CD->isInvalidDecl())
9837 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00009838 break;
9839 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00009840
Sean Hunt2b188082011-05-14 05:23:28 +00009841 case CXXCopyAssignment: {
9842 CheckExplicitlyDefaultedCopyAssignment(MD);
9843 if (!MD->isInvalidDecl())
9844 DefineImplicitCopyAssignment(DefaultLoc, MD);
9845 break;
9846 }
9847
Sean Huntcb45a0f2011-05-12 22:46:25 +00009848 case CXXDestructor: {
9849 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9850 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009851 if (!DD->isInvalidDecl())
9852 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009853 break;
9854 }
9855
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009856 case CXXMoveConstructor: {
9857 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9858 CheckExplicitlyDefaultedMoveConstructor(CD);
9859 if (!CD->isInvalidDecl())
9860 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +00009861 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009862 }
Sean Hunt82713172011-05-25 23:16:36 +00009863
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009864 case CXXMoveAssignment: {
9865 CheckExplicitlyDefaultedMoveAssignment(MD);
9866 if (!MD->isInvalidDecl())
9867 DefineImplicitMoveAssignment(DefaultLoc, MD);
9868 break;
9869 }
9870
9871 case CXXInvalid:
9872 assert(false && "Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +00009873 break;
9874 }
9875 } else {
9876 Diag(DefaultLoc, diag::err_default_special_members);
9877 }
9878}
9879
Sebastian Redl13e88542009-04-27 21:33:24 +00009880static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00009881 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00009882 Stmt *SubStmt = *CI;
9883 if (!SubStmt)
9884 continue;
9885 if (isa<ReturnStmt>(SubStmt))
9886 Self.Diag(SubStmt->getSourceRange().getBegin(),
9887 diag::err_return_in_constructor_handler);
9888 if (!isa<Expr>(SubStmt))
9889 SearchForReturnInStmt(Self, SubStmt);
9890 }
9891}
9892
9893void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
9894 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
9895 CXXCatchStmt *Handler = TryBlock->getHandler(I);
9896 SearchForReturnInStmt(*this, Handler);
9897 }
9898}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009899
Mike Stump1eb44332009-09-09 15:08:12 +00009900bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009901 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00009902 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
9903 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009904
Chandler Carruth73857792010-02-15 11:53:20 +00009905 if (Context.hasSameType(NewTy, OldTy) ||
9906 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009907 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00009908
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009909 // Check if the return types are covariant
9910 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00009911
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009912 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00009913 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
9914 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009915 NewClassTy = NewPT->getPointeeType();
9916 OldClassTy = OldPT->getPointeeType();
9917 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00009918 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
9919 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
9920 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
9921 NewClassTy = NewRT->getPointeeType();
9922 OldClassTy = OldRT->getPointeeType();
9923 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009924 }
9925 }
Mike Stump1eb44332009-09-09 15:08:12 +00009926
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009927 // The return types aren't either both pointers or references to a class type.
9928 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00009929 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009930 diag::err_different_return_type_for_overriding_virtual_function)
9931 << New->getDeclName() << NewTy << OldTy;
9932 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00009933
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009934 return true;
9935 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009936
Anders Carlssonbe2e2052009-12-31 18:34:24 +00009937 // C++ [class.virtual]p6:
9938 // If the return type of D::f differs from the return type of B::f, the
9939 // class type in the return type of D::f shall be complete at the point of
9940 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00009941 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
9942 if (!RT->isBeingDefined() &&
9943 RequireCompleteType(New->getLocation(), NewClassTy,
9944 PDiag(diag::err_covariant_return_incomplete)
9945 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00009946 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00009947 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00009948
Douglas Gregora4923eb2009-11-16 21:35:15 +00009949 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009950 // Check if the new class derives from the old class.
9951 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
9952 Diag(New->getLocation(),
9953 diag::err_covariant_return_not_derived)
9954 << New->getDeclName() << NewTy << OldTy;
9955 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
9956 return true;
9957 }
Mike Stump1eb44332009-09-09 15:08:12 +00009958
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009959 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00009960 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00009961 diag::err_covariant_return_inaccessible_base,
9962 diag::err_covariant_return_ambiguous_derived_to_base_conv,
9963 // FIXME: Should this point to the return type?
9964 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00009965 // FIXME: this note won't trigger for delayed access control
9966 // diagnostics, and it's impossible to get an undelayed error
9967 // here from access control during the original parse because
9968 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009969 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
9970 return true;
9971 }
9972 }
Mike Stump1eb44332009-09-09 15:08:12 +00009973
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009974 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00009975 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009976 Diag(New->getLocation(),
9977 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009978 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009979 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
9980 return true;
9981 };
Mike Stump1eb44332009-09-09 15:08:12 +00009982
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009983
9984 // The new class type must have the same or less qualifiers as the old type.
9985 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
9986 Diag(New->getLocation(),
9987 diag::err_covariant_return_type_class_type_more_qualified)
9988 << New->getDeclName() << NewTy << OldTy;
9989 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
9990 return true;
9991 };
Mike Stump1eb44332009-09-09 15:08:12 +00009992
Anders Carlssonc3a68b22009-05-14 19:52:19 +00009993 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00009994}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009995
Douglas Gregor4ba31362009-12-01 17:24:26 +00009996/// \brief Mark the given method pure.
9997///
9998/// \param Method the method to be marked pure.
9999///
10000/// \param InitRange the source range that covers the "0" initializer.
10001bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010002 SourceLocation EndLoc = InitRange.getEnd();
10003 if (EndLoc.isValid())
10004 Method->setRangeEnd(EndLoc);
10005
Douglas Gregor4ba31362009-12-01 17:24:26 +000010006 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10007 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010008 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010009 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010010
10011 if (!Method->isInvalidDecl())
10012 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10013 << Method->getDeclName() << InitRange;
10014 return true;
10015}
10016
John McCall731ad842009-12-19 09:28:58 +000010017/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10018/// an initializer for the out-of-line declaration 'Dcl'. The scope
10019/// is a fresh scope pushed for just this purpose.
10020///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010021/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10022/// static data member of class X, names should be looked up in the scope of
10023/// class X.
John McCalld226f652010-08-21 09:40:31 +000010024void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010025 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010026 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010027
John McCall731ad842009-12-19 09:28:58 +000010028 // We should only get called for declarations with scope specifiers, like:
10029 // int foo::bar;
10030 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010031 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010032}
10033
10034/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010035/// initializer for the out-of-line declaration 'D'.
10036void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010037 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010038 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010039
John McCall731ad842009-12-19 09:28:58 +000010040 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010041 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010042}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010043
10044/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10045/// C++ if/switch/while/for statement.
10046/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010047DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010048 // C++ 6.4p2:
10049 // The declarator shall not specify a function or an array.
10050 // The type-specifier-seq shall not contain typedef and shall not declare a
10051 // new class or enumeration.
10052 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10053 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010054
10055 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010056 if (!Dcl)
10057 return true;
10058
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010059 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10060 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010061 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010062 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010063 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010064
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010065 return Dcl;
10066}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010067
Douglas Gregordfe65432011-07-28 19:11:31 +000010068void Sema::LoadExternalVTableUses() {
10069 if (!ExternalSource)
10070 return;
10071
10072 SmallVector<ExternalVTableUse, 4> VTables;
10073 ExternalSource->ReadUsedVTables(VTables);
10074 SmallVector<VTableUse, 4> NewUses;
10075 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10076 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10077 = VTablesUsed.find(VTables[I].Record);
10078 // Even if a definition wasn't required before, it may be required now.
10079 if (Pos != VTablesUsed.end()) {
10080 if (!Pos->second && VTables[I].DefinitionRequired)
10081 Pos->second = true;
10082 continue;
10083 }
10084
10085 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10086 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10087 }
10088
10089 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10090}
10091
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010092void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10093 bool DefinitionRequired) {
10094 // Ignore any vtable uses in unevaluated operands or for classes that do
10095 // not have a vtable.
10096 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10097 CurContext->isDependentContext() ||
10098 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010099 return;
10100
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010101 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010102 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010103 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10104 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10105 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10106 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010107 // If we already had an entry, check to see if we are promoting this vtable
10108 // to required a definition. If so, we need to reappend to the VTableUses
10109 // list, since we may have already processed the first entry.
10110 if (DefinitionRequired && !Pos.first->second) {
10111 Pos.first->second = true;
10112 } else {
10113 // Otherwise, we can early exit.
10114 return;
10115 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010116 }
10117
10118 // Local classes need to have their virtual members marked
10119 // immediately. For all other classes, we mark their virtual members
10120 // at the end of the translation unit.
10121 if (Class->isLocalClass())
10122 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010123 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010124 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010125}
10126
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010127bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010128 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010129 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010130 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010131
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010132 // Note: The VTableUses vector could grow as a result of marking
10133 // the members of a class as "used", so we check the size each
10134 // time through the loop and prefer indices (with are stable) to
10135 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010136 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010137 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010138 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010139 if (!Class)
10140 continue;
10141
10142 SourceLocation Loc = VTableUses[I].second;
10143
10144 // If this class has a key function, but that key function is
10145 // defined in another translation unit, we don't need to emit the
10146 // vtable even though we're using it.
10147 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010148 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010149 switch (KeyFunction->getTemplateSpecializationKind()) {
10150 case TSK_Undeclared:
10151 case TSK_ExplicitSpecialization:
10152 case TSK_ExplicitInstantiationDeclaration:
10153 // The key function is in another translation unit.
10154 continue;
10155
10156 case TSK_ExplicitInstantiationDefinition:
10157 case TSK_ImplicitInstantiation:
10158 // We will be instantiating the key function.
10159 break;
10160 }
10161 } else if (!KeyFunction) {
10162 // If we have a class with no key function that is the subject
10163 // of an explicit instantiation declaration, suppress the
10164 // vtable; it will live with the explicit instantiation
10165 // definition.
10166 bool IsExplicitInstantiationDeclaration
10167 = Class->getTemplateSpecializationKind()
10168 == TSK_ExplicitInstantiationDeclaration;
10169 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10170 REnd = Class->redecls_end();
10171 R != REnd; ++R) {
10172 TemplateSpecializationKind TSK
10173 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10174 if (TSK == TSK_ExplicitInstantiationDeclaration)
10175 IsExplicitInstantiationDeclaration = true;
10176 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10177 IsExplicitInstantiationDeclaration = false;
10178 break;
10179 }
10180 }
10181
10182 if (IsExplicitInstantiationDeclaration)
10183 continue;
10184 }
10185
10186 // Mark all of the virtual members of this class as referenced, so
10187 // that we can build a vtable. Then, tell the AST consumer that a
10188 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010189 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010190 MarkVirtualMembersReferenced(Loc, Class);
10191 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10192 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10193
10194 // Optionally warn if we're emitting a weak vtable.
10195 if (Class->getLinkage() == ExternalLinkage &&
10196 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010197 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010198 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10199 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010200 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010201 VTableUses.clear();
10202
Douglas Gregor78844032011-04-22 22:25:37 +000010203 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010204}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010205
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010206void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10207 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010208 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10209 e = RD->method_end(); i != e; ++i) {
10210 CXXMethodDecl *MD = *i;
10211
10212 // C++ [basic.def.odr]p2:
10213 // [...] A virtual member function is used if it is not pure. [...]
10214 if (MD->isVirtual() && !MD->isPure())
10215 MarkDeclarationReferenced(Loc, MD);
10216 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010217
10218 // Only classes that have virtual bases need a VTT.
10219 if (RD->getNumVBases() == 0)
10220 return;
10221
10222 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10223 e = RD->bases_end(); i != e; ++i) {
10224 const CXXRecordDecl *Base =
10225 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010226 if (Base->getNumVBases() == 0)
10227 continue;
10228 MarkVirtualMembersReferenced(Loc, Base);
10229 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010230}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010231
10232/// SetIvarInitializers - This routine builds initialization ASTs for the
10233/// Objective-C implementation whose ivars need be initialized.
10234void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10235 if (!getLangOptions().CPlusPlus)
10236 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010237 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010238 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010239 CollectIvarsToConstructOrDestruct(OID, ivars);
10240 if (ivars.empty())
10241 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010242 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010243 for (unsigned i = 0; i < ivars.size(); i++) {
10244 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010245 if (Field->isInvalidDecl())
10246 continue;
10247
Sean Huntcbb67482011-01-08 20:30:50 +000010248 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010249 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10250 InitializationKind InitKind =
10251 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10252
10253 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010254 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010255 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010256 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010257 // Note, MemberInit could actually come back empty if no initialization
10258 // is required (e.g., because it would call a trivial default constructor)
10259 if (!MemberInit.get() || MemberInit.isInvalid())
10260 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010261
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010262 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010263 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10264 SourceLocation(),
10265 MemberInit.takeAs<Expr>(),
10266 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010267 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010268
10269 // Be sure that the destructor is accessible and is marked as referenced.
10270 if (const RecordType *RecordTy
10271 = Context.getBaseElementType(Field->getType())
10272 ->getAs<RecordType>()) {
10273 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010274 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010275 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10276 CheckDestructorAccess(Field->getLocation(), Destructor,
10277 PDiag(diag::err_access_dtor_ivar)
10278 << Context.getBaseElementType(Field->getType()));
10279 }
10280 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010281 }
10282 ObjCImplementation->setIvarInitializers(Context,
10283 AllToInit.data(), AllToInit.size());
10284 }
10285}
Sean Huntfe57eef2011-05-04 05:57:24 +000010286
Sean Huntebcbe1d2011-05-04 23:29:54 +000010287static
10288void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10289 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10290 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10291 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10292 Sema &S) {
10293 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10294 CE = Current.end();
10295 if (Ctor->isInvalidDecl())
10296 return;
10297
10298 const FunctionDecl *FNTarget = 0;
10299 CXXConstructorDecl *Target;
10300
10301 // We ignore the result here since if we don't have a body, Target will be
10302 // null below.
10303 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10304 Target
10305= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10306
10307 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10308 // Avoid dereferencing a null pointer here.
10309 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10310
10311 if (!Current.insert(Canonical))
10312 return;
10313
10314 // We know that beyond here, we aren't chaining into a cycle.
10315 if (!Target || !Target->isDelegatingConstructor() ||
10316 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10317 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10318 Valid.insert(*CI);
10319 Current.clear();
10320 // We've hit a cycle.
10321 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10322 Current.count(TCanonical)) {
10323 // If we haven't diagnosed this cycle yet, do so now.
10324 if (!Invalid.count(TCanonical)) {
10325 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010326 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010327 << Ctor;
10328
10329 // Don't add a note for a function delegating directo to itself.
10330 if (TCanonical != Canonical)
10331 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10332
10333 CXXConstructorDecl *C = Target;
10334 while (C->getCanonicalDecl() != Canonical) {
10335 (void)C->getTargetConstructor()->hasBody(FNTarget);
10336 assert(FNTarget && "Ctor cycle through bodiless function");
10337
10338 C
10339 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10340 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10341 }
10342 }
10343
10344 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10345 Invalid.insert(*CI);
10346 Current.clear();
10347 } else {
10348 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10349 }
10350}
10351
10352
Sean Huntfe57eef2011-05-04 05:57:24 +000010353void Sema::CheckDelegatingCtorCycles() {
10354 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10355
Sean Huntebcbe1d2011-05-04 23:29:54 +000010356 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10357 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010358
Douglas Gregor0129b562011-07-27 21:57:17 +000010359 for (DelegatingCtorDeclsType::iterator
10360 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010361 E = DelegatingCtorDecls.end();
10362 I != E; ++I) {
10363 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010364 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010365
10366 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10367 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010368}