blob: e8892fd323f6dc6c8197e40608dc22e1359e0c52 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Sean Hunt001cad92011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000118 return;
119
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
122
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith7a614d82011-06-11 17:19:42 +0000132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
134
Sean Hunt001cad92011-05-10 00:49:42 +0000135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
137 return;
138
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
141 return;
142
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
148 return;
149 }
150
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
159
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
162 ClearExceptions();
163 ComputedEST = EST_None;
164 }
165 // noexcept(true) won't change anything either.
166 return;
167 }
168
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
176 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith7a614d82011-06-11 17:19:42 +0000181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders Carlssoned961f92009-08-25 02:29:20 +0000210bool
John McCall9ae2f072010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
216 return true;
217 }
218
Anders Carlssoned961f92009-08-25 02:29:20 +0000219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000233 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000235
John McCallb4eb64d2010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
252 }
253
Anders Carlsson9351c172009-08-25 03:18:48 +0000254 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000255}
256
Chris Lattner8123a952008-04-10 02:22:51 +0000257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260void
John McCalld226f652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000264 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
John McCalld226f652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6f526752010-12-16 08:48:57 +0000277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
280 return;
281 }
282
Anders Carlsson66e30672009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289
John McCall9ae2f072010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000291}
292
Douglas Gregor61366e92008-12-24 00:01:03 +0000293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCalld226f652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000308}
309
Douglas Gregor72b505b2008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCalld226f652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Anders Carlsson5e300d12009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000321}
322
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346 delete Toks;
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner3d1cee32008-04-08 05:04:30 +0000358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
364
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000377 //
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
386
Douglas Gregor6cc15182009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000388
Francois Pichet8d051e02011-04-10 03:03:52 +0000389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
391
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
394 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000395 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
403 else
404 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000409
Francois Pichet8cf90492011-04-10 04:58:30 +0000410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000420
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 if (!Older->getParamDecl(p)->hasDefaultArg())
426 break;
427
428 OldParam = Older->getParamDecl(p);
429 }
430
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCall3d6c1782010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
450 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
462 // instantiated.
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
472 //
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
476 // dependent type.
477 int WhichKind = 2;
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
481 WhichKind = 0;
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483 WhichKind = 1;
484 else
485 WhichKind = 2;
486 }
487
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
490 << WhichKind
491 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
499 << OldSM;
500 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000501 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000502 }
503 }
504
Douglas Gregore13ad832010-02-12 07:32:17 +0000505 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000506 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000507
Douglas Gregorcda9c672009-02-16 17:45:42 +0000508 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000509}
510
Sebastian Redl60618fa2011-03-12 11:50:43 +0000511/// \brief Merge the exception specifications of two variable declarations.
512///
513/// This is called when there's a redeclaration of a VarDecl. The function
514/// checks if the redeclaration might have an exception specification and
515/// validates compatibility and merges the specs if necessary.
516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517 // Shortcut if exceptions are disabled.
518 if (!getLangOptions().CXXExceptions)
519 return;
520
521 assert(Context.hasSameType(New->getType(), Old->getType()) &&
522 "Should only be called if types are otherwise the same.");
523
524 QualType NewType = New->getType();
525 QualType OldType = Old->getType();
526
527 // We're only interested in pointers and references to functions, as well
528 // as pointers to member functions.
529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530 NewType = R->getPointeeType();
531 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533 NewType = P->getPointeeType();
534 OldType = OldType->getAs<PointerType>()->getPointeeType();
535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536 NewType = M->getPointeeType();
537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538 }
539
540 if (!NewType->isFunctionProtoType())
541 return;
542
543 // There's lots of special cases for functions. For function pointers, system
544 // libraries are hopefully not as broken so that we don't need these
545 // workarounds.
546 if (CheckEquivalentExceptionSpec(
547 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549 New->setInvalidDecl();
550 }
551}
552
Chris Lattner3d1cee32008-04-08 05:04:30 +0000553/// CheckCXXDefaultArguments - Verify that the default arguments for a
554/// function declaration are well-formed according to C++
555/// [dcl.fct.default].
556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557 unsigned NumParams = FD->getNumParams();
558 unsigned p;
559
560 // Find first parameter with a default argument
561 for (p = 0; p < NumParams; ++p) {
562 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000563 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 break;
565 }
566
567 // C++ [dcl.fct.default]p4:
568 // In a given function declaration, all parameters
569 // subsequent to a parameter with a default argument shall
570 // have default arguments supplied in this or previous
571 // declarations. A default argument shall not be redefined
572 // by a later declaration (not even to the same value).
573 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000575 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000576 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000580 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000581 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000582 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000583 else
Mike Stump1eb44332009-09-09 15:08:12 +0000584 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner3d1cee32008-04-08 05:04:30 +0000587 LastMissingDefaultArg = p;
588 }
589 }
590
591 if (LastMissingDefaultArg > 0) {
592 // Some default arguments were missing. Clear out all of the
593 // default arguments up to (and including) the last missing
594 // default argument, so that we leave the function parameters
595 // in a semantically valid state.
596 for (p = 0; p <= LastMissingDefaultArg; ++p) {
597 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000598 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599 Param->setDefaultArg(0);
600 }
601 }
602 }
603}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000604
Douglas Gregorb48fe382008-10-31 09:07:45 +0000605/// isCurrentClassName - Determine whether the identifier II is the
606/// name of the class type currently being defined. In the case of
607/// nested classes, this will only return true if II is the name of
608/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000613 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000614 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000615 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617 } else
618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000620 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624}
625
Mike Stump1eb44332009-09-09 15:08:12 +0000626/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627///
628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629/// and returns NULL otherwise.
630CXXBaseSpecifier *
631Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632 SourceRange SpecifierRange,
633 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000636 QualType BaseType = TInfo->getType();
637
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 // C++ [class.union]p1:
639 // A union shall not have base classes.
640 if (Class->isUnion()) {
641 Diag(Class->getLocation(), diag::err_base_clause_on_union)
642 << SpecifierRange;
643 return 0;
644 }
645
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000646 if (EllipsisLoc.isValid() &&
647 !TInfo->getType()->containsUnexpandedParameterPack()) {
648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649 << TInfo->getTypeLoc().getSourceRange();
650 EllipsisLoc = SourceLocation();
651 }
652
Douglas Gregor2943aed2009-03-03 04:44:36 +0000653 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000655 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000656 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659
660 // Base specifiers must be record types.
661 if (!BaseType->isRecordType()) {
662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663 return 0;
664 }
665
666 // C++ [class.union]p1:
667 // A union shall not be used as a base class.
668 if (BaseType->isUnionType()) {
669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670 return 0;
671 }
672
673 // C++ [class.derived]p2:
674 // The class-name in a base-specifier shall not be an incompletely
675 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000676 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000677 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000678 << SpecifierRange)) {
679 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000680 return 0;
John McCall572fc622010-08-17 07:23:57 +0000681 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000682
Eli Friedman1d954f62009-08-15 21:55:26 +0000683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000685 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000686 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000690
Anders Carlsson1d209272011-03-25 14:55:14 +0000691 // C++ [class]p3:
692 // If a class is marked final and it appears as a base-type-specifier in
693 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696 << CXXBaseDecl->getDeclName();
697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698 << CXXBaseDecl->getDeclName();
699 return 0;
700 }
701
John McCall572fc622010-08-17 07:23:57 +0000702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000704
705 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000707 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000708 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000709}
710
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000713/// example:
714/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000715/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000716BaseResult
John McCalld226f652010-08-21 09:40:31 +0000717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000718 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000721 if (!classdecl)
722 return true;
723
Douglas Gregor40808ce2009-03-09 23:48:35 +0000724 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000726 if (!Class)
727 return true;
728
Nick Lewycky56062202010-07-26 16:56:01 +0000729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000731
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000734 UPPC_BaseType))
735 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000736
Douglas Gregor2943aed2009-03-03 04:44:36 +0000737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000738 Virtual, Access, TInfo,
739 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000740 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Douglas Gregor2943aed2009-03-03 04:44:36 +0000742 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000743}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000744
Douglas Gregor2943aed2009-03-03 04:44:36 +0000745/// \brief Performs the actual work of attaching the given base class
746/// specifiers to a C++ class.
747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748 unsigned NumBases) {
749 if (NumBases == 0)
750 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000751
752 // Used to keep track of which base types we have already seen, so
753 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000754 // that the key is always the unqualified canonical type of the base
755 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000759 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000760 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000761 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000762 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000763 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000765 if (KnownBaseTypes[NewBaseType]) {
766 // C++ [class.mi]p3:
767 // A class shall not be specified as a direct base class of a
768 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000769 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000770 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000771 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000772 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000776 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000777
778 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000779 } else {
780 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000787 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000788
789 // Delete the remaining (good) base class specifiers, since their
790 // data has been copied into the CXXRecordDecl.
791 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000792 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000793
794 return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000807 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000808}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000809
John McCall3cb0ebd2010-03-10 03:28:59 +0000810static CXXRecordDecl *GetClassForType(QualType T) {
811 if (const RecordType *RT = T->getAs<RecordType>())
812 return cast<CXXRecordDecl>(RT->getDecl());
813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814 return ICT->getDecl();
815 else
816 return 0;
817}
818
Douglas Gregora8f32e02009-10-06 17:59:45 +0000819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822 if (!getLangOptions().CPlusPlus)
823 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000827 return false;
828
John McCall3cb0ebd2010-03-10 03:28:59 +0000829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000831 return false;
832
John McCall86ff3082010-02-04 22:26:26 +0000833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840 if (!getLangOptions().CPlusPlus)
841 return false;
842
John McCall3cb0ebd2010-03-10 03:28:59 +0000843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000845 return false;
846
John McCall3cb0ebd2010-03-10 03:28:59 +0000847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000849 return false;
850
Douglas Gregora8f32e02009-10-06 17:59:45 +0000851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000855 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000856 assert(BasePathArray.empty() && "Base path array must be empty!");
857 assert(Paths.isRecordingPaths() && "Must record paths!");
858
859 const CXXBasePath &Path = Paths.front();
860
861 // We first go backward and check if we have a virtual base.
862 // FIXME: It would be better if CXXBasePath had the base specifier for
863 // the nearest virtual base.
864 unsigned Start = 0;
865 for (unsigned I = Path.size(); I != 0; --I) {
866 if (Path[I - 1].Base->isVirtual()) {
867 Start = I - 1;
868 break;
869 }
870 }
871
872 // Now add all bases.
873 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000875}
876
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000877/// \brief Determine whether the given base path includes a virtual
878/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887}
888
Douglas Gregora8f32e02009-10-06 17:59:45 +0000889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000899 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000902 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000903 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000904 // First, determine whether the path from Derived to Base is
905 // ambiguous. This is slightly more expensive than checking whether
906 // the Derived to Base conversion exists, because here we need to
907 // explore multiple paths to determine if there is an ambiguity.
908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909 /*DetectVirtual=*/false);
910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911 assert(DerivationOkay &&
912 "Can only be used with a derived-to-base conversion");
913 (void)DerivationOkay;
914
915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000916 if (InaccessibleBaseID) {
917 // Check that the base class can be accessed.
918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919 InaccessibleBaseID)) {
920 case AR_inaccessible:
921 return true;
922 case AR_accessible:
923 case AR_dependent:
924 case AR_delayed:
925 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000926 }
John McCall6b2accb2010-02-10 09:31:12 +0000927 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000933 }
934
935 // We know that the derived-to-base conversion is ambiguous, and
936 // we're going to produce a diagnostic. Perform the derived-to-base
937 // search just one more time to compute all of the possible paths so
938 // that we can print them out. This is more expensive than any of
939 // the previous derived-to-base checks we've done, but at this point
940 // performance isn't as much of an issue.
941 Paths.clear();
942 Paths.setRecordingPaths(true);
943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944 assert(StillOkay && "Can only be used with a derived-to-base conversion");
945 (void)StillOkay;
946
947 // Build up a textual representation of the ambiguous paths, e.g.,
948 // D -> B -> A, that will be used to illustrate the ambiguous
949 // conversions in the diagnostic. We only print one of the paths
950 // to each base class subobject.
951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953 Diag(Loc, AmbigiousBaseConvID)
954 << Derived << Base << PathDisplayStr << Range << Name;
955 return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000960 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000961 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000962 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000963 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000966 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000967 Loc, Range, DeclarationName(),
968 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985 std::string PathDisplayStr;
986 std::set<unsigned> DisplayedPaths;
987 for (CXXBasePaths::paths_iterator Path = Paths.begin();
988 Path != Paths.end(); ++Path) {
989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990 // We haven't displayed a path to this particular base
991 // class subobject yet.
992 PathDisplayStr += "\n ";
993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994 for (CXXBasePath::const_iterator Element = Path->begin();
995 Element != Path->end(); ++Element)
996 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997 }
998 }
999
1000 return PathDisplayStr;
1001}
1002
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
Abramo Bagnara6206d532010-06-05 05:09:32 +00001007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +00001008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +00001015 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +00001016}
1017
Anders Carlsson9e682d92011-01-20 05:57:14 +00001018/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001019void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001020 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001021 if (!MD || !MD->isVirtual())
1022 return;
1023
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001024 if (MD->isDependentContext())
1025 return;
1026
Anders Carlsson9e682d92011-01-20 05:57:14 +00001027 // C++0x [class.virtual]p3:
1028 // If a virtual function is marked with the virt-specifier override and does
1029 // not override a member function of a base class,
1030 // the program is ill-formed.
1031 bool HasOverriddenMethods =
1032 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001034 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039}
1040
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001046 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001047 return false;
1048
1049 Diag(New->getLocation(), diag::err_final_function_overridden)
1050 << New->getDeclName();
1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001053}
1054
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001060Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001062 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001063 Expr *BW, const VirtSpecifiers &VS,
1064 Expr *InitExpr, bool HasDeferredInit,
Richard Smith7a614d82011-06-11 17:19:42 +00001065 bool IsDefinition) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001066 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001070
1071 // For anonymous bitfields, the location should point to the type.
1072 if (Loc.isInvalid())
1073 Loc = D.getSourceRange().getBegin();
1074
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001077
John McCall4bde1e12010-06-04 08:34:12 +00001078 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001079 assert(!DS.isFriendSpecified());
Richard Smith7a614d82011-06-11 17:19:42 +00001080 assert(!Init || !HasDeferredInit);
John McCall67d1a672009-08-06 02:15:43 +00001081
Richard Smith1ab0d902011-06-25 02:28:38 +00001082 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001083
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001084 // C++ 9.2p6: A member shall not be declared to have automatic storage
1085 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001086 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087 // data members and cannot be applied to names declared const or static,
1088 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001089 switch (DS.getStorageClassSpec()) {
1090 case DeclSpec::SCS_unspecified:
1091 case DeclSpec::SCS_typedef:
1092 case DeclSpec::SCS_static:
1093 // FALL THROUGH.
1094 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001095 case DeclSpec::SCS_mutable:
1096 if (isFunc) {
1097 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001099 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Sebastian Redla11f42f2008-11-17 23:24:37 +00001102 // FIXME: It would be nicer if the keyword was ignored only for this
1103 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001104 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001105 }
1106 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001107 default:
1108 if (DS.getStorageClassSpecLoc().isValid())
1109 Diag(DS.getStorageClassSpecLoc(),
1110 diag::err_storageclass_invalid_for_member);
1111 else
1112 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113 D.getMutableDeclSpec().ClearStorageClassSpecs();
1114 }
1115
Sebastian Redl669d5d72008-11-14 23:42:31 +00001116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001118 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001119
1120 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001121 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001122 CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
Douglas Gregorf2503652011-09-21 14:40:46 +00001124 // FIXME: Check that the name is an identifier!
1125 IdentifierInfo *II = Name.getAsIdentifierInfo();
1126
1127 // Member field could not be with "template" keyword.
1128 // So TemplateParameterLists should be empty in this case.
1129 if (TemplateParameterLists.size()) {
1130 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1131 if (TemplateParams->size()) {
1132 // There is no such thing as a member field template.
1133 Diag(D.getIdentifierLoc(), diag::err_template_member)
1134 << II
1135 << SourceRange(TemplateParams->getTemplateLoc(),
1136 TemplateParams->getRAngleLoc());
1137 } else {
1138 // There is an extraneous 'template<>' for this member.
1139 Diag(TemplateParams->getTemplateLoc(),
1140 diag::err_template_member_noparams)
1141 << II
1142 << SourceRange(TemplateParams->getTemplateLoc(),
1143 TemplateParams->getRAngleLoc());
1144 }
1145 return 0;
1146 }
1147
Douglas Gregor922fff22010-10-13 22:19:53 +00001148 if (SS.isSet() && !SS.isInvalid()) {
1149 // The user provided a superfluous scope specifier inside a class
1150 // definition:
1151 //
1152 // class X {
1153 // int X::member;
1154 // };
1155 DeclContext *DC = 0;
1156 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1157 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1158 << Name << FixItHint::CreateRemoval(SS.getRange());
1159 else
1160 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1161 << Name << SS.getRange();
1162
1163 SS.clear();
1164 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001165
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001166 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001167 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001168 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001169 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001170 assert(!HasDeferredInit);
1171
Sean Hunte4246a62011-05-12 06:15:49 +00001172 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001173 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001174 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001175 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001176
1177 // Non-instance-fields can't have a bitfield.
1178 if (BitWidth) {
1179 if (Member->isInvalidDecl()) {
1180 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001181 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001182 // C++ 9.6p3: A bit-field shall not be a static member.
1183 // "static member 'A' cannot be a bit-field"
1184 Diag(Loc, diag::err_static_not_bitfield)
1185 << Name << BitWidth->getSourceRange();
1186 } else if (isa<TypedefDecl>(Member)) {
1187 // "typedef member 'x' cannot be a bit-field"
1188 Diag(Loc, diag::err_typedef_not_bitfield)
1189 << Name << BitWidth->getSourceRange();
1190 } else {
1191 // A function typedef ("typedef int f(); f a;").
1192 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1193 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001194 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001195 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Chris Lattner8b963ef2009-03-05 23:01:03 +00001198 BitWidth = 0;
1199 Member->setInvalidDecl();
1200 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001201
1202 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregor37b372b2009-08-20 22:52:58 +00001204 // If we have declared a member function template, set the access of the
1205 // templated declaration as well.
1206 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1207 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001208 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001209
Anders Carlssonaae5af22011-01-20 04:34:22 +00001210 if (VS.isOverrideSpecified()) {
1211 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1212 if (!MD || !MD->isVirtual()) {
1213 Diag(Member->getLocStart(),
1214 diag::override_keyword_only_allowed_on_virtual_member_functions)
1215 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001216 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001217 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001218 }
1219 if (VS.isFinalSpecified()) {
1220 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1221 if (!MD || !MD->isVirtual()) {
1222 Diag(Member->getLocStart(),
1223 diag::override_keyword_only_allowed_on_virtual_member_functions)
1224 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001225 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001226 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001227 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001228
Douglas Gregorf5251602011-03-08 17:10:18 +00001229 if (VS.getLastLocation().isValid()) {
1230 // Update the end location of a method that has a virt-specifiers.
1231 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1232 MD->setRangeEnd(VS.getLastLocation());
1233 }
1234
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001235 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001236
Douglas Gregor10bd3682008-11-17 22:58:34 +00001237 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001238
Douglas Gregor021c3b32009-03-11 23:00:04 +00001239 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001240 AddInitializerToDecl(Member, Init, false,
1241 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith7a614d82011-06-11 17:19:42 +00001242 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1243 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1244 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1245 // data member if a brace-or-equal-initializer is provided.
1246 Diag(Loc, diag::err_auto_var_requires_init)
1247 << Name << cast<ValueDecl>(Member)->getType();
1248 Member->setInvalidDecl();
1249 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001250
Richard Smith483b9f32011-02-21 20:05:19 +00001251 FinalizeDeclaration(Member);
1252
John McCallb25b2952011-02-15 07:12:36 +00001253 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001254 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001255 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001256}
1257
Richard Smith7a614d82011-06-11 17:19:42 +00001258/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001259/// in-class initializer for a non-static C++ class member, and after
1260/// instantiating an in-class initializer in a class template. Such actions
1261/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001262void
1263Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1264 Expr *InitExpr) {
1265 FieldDecl *FD = cast<FieldDecl>(D);
1266
1267 if (!InitExpr) {
1268 FD->setInvalidDecl();
1269 FD->removeInClassInitializer();
1270 return;
1271 }
1272
1273 ExprResult Init = InitExpr;
1274 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1275 // FIXME: if there is no EqualLoc, this is list-initialization.
1276 Init = PerformCopyInitialization(
1277 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1278 if (Init.isInvalid()) {
1279 FD->setInvalidDecl();
1280 return;
1281 }
1282
1283 CheckImplicitConversions(Init.get(), EqualLoc);
1284 }
1285
1286 // C++0x [class.base.init]p7:
1287 // The initialization of each base and member constitutes a
1288 // full-expression.
1289 Init = MaybeCreateExprWithCleanups(Init);
1290 if (Init.isInvalid()) {
1291 FD->setInvalidDecl();
1292 return;
1293 }
1294
1295 InitExpr = Init.release();
1296
1297 FD->setInClassInitializer(InitExpr);
1298}
1299
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001300/// \brief Find the direct and/or virtual base specifiers that
1301/// correspond to the given base type, for use in base initialization
1302/// within a constructor.
1303static bool FindBaseInitializer(Sema &SemaRef,
1304 CXXRecordDecl *ClassDecl,
1305 QualType BaseType,
1306 const CXXBaseSpecifier *&DirectBaseSpec,
1307 const CXXBaseSpecifier *&VirtualBaseSpec) {
1308 // First, check for a direct base class.
1309 DirectBaseSpec = 0;
1310 for (CXXRecordDecl::base_class_const_iterator Base
1311 = ClassDecl->bases_begin();
1312 Base != ClassDecl->bases_end(); ++Base) {
1313 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1314 // We found a direct base of this type. That's what we're
1315 // initializing.
1316 DirectBaseSpec = &*Base;
1317 break;
1318 }
1319 }
1320
1321 // Check for a virtual base class.
1322 // FIXME: We might be able to short-circuit this if we know in advance that
1323 // there are no virtual bases.
1324 VirtualBaseSpec = 0;
1325 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1326 // We haven't found a base yet; search the class hierarchy for a
1327 // virtual base class.
1328 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1329 /*DetectVirtual=*/false);
1330 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1331 BaseType, Paths)) {
1332 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1333 Path != Paths.end(); ++Path) {
1334 if (Path->back().Base->isVirtual()) {
1335 VirtualBaseSpec = Path->back().Base;
1336 break;
1337 }
1338 }
1339 }
1340 }
1341
1342 return DirectBaseSpec || VirtualBaseSpec;
1343}
1344
Sebastian Redl6df65482011-09-24 17:48:25 +00001345/// \brief Handle a C++ member initializer using braced-init-list syntax.
1346MemInitResult
1347Sema::ActOnMemInitializer(Decl *ConstructorD,
1348 Scope *S,
1349 CXXScopeSpec &SS,
1350 IdentifierInfo *MemberOrBase,
1351 ParsedType TemplateTypeTy,
1352 SourceLocation IdLoc,
1353 Expr *InitList,
1354 SourceLocation EllipsisLoc) {
1355 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1356 IdLoc, MultiInitializer(InitList), EllipsisLoc);
1357}
1358
1359/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001360MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001361Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001362 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001363 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001364 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001365 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001366 SourceLocation IdLoc,
1367 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001368 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001369 SourceLocation RParenLoc,
1370 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001371 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1372 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs,
1373 RParenLoc),
1374 EllipsisLoc);
1375}
1376
1377/// \brief Handle a C++ member initializer.
1378MemInitResult
1379Sema::BuildMemInitializer(Decl *ConstructorD,
1380 Scope *S,
1381 CXXScopeSpec &SS,
1382 IdentifierInfo *MemberOrBase,
1383 ParsedType TemplateTypeTy,
1384 SourceLocation IdLoc,
1385 const MultiInitializer &Args,
1386 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001387 if (!ConstructorD)
1388 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001390 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001391
1392 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001393 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001394 if (!Constructor) {
1395 // The user wrote a constructor initializer on a function that is
1396 // not a C++ constructor. Ignore the error for now, because we may
1397 // have more member initializers coming; we'll diagnose it just
1398 // once in ActOnMemInitializers.
1399 return true;
1400 }
1401
1402 CXXRecordDecl *ClassDecl = Constructor->getParent();
1403
1404 // C++ [class.base.init]p2:
1405 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001406 // constructor's class and, if not found in that scope, are looked
1407 // up in the scope containing the constructor's definition.
1408 // [Note: if the constructor's class contains a member with the
1409 // same name as a direct or virtual base class of the class, a
1410 // mem-initializer-id naming the member or base class and composed
1411 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001412 // mem-initializer-id for the hidden base class may be specified
1413 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001414 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001415 // Look for a member, first.
1416 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001417 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001418 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001419 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001420 Member = dyn_cast<FieldDecl>(*Result.first);
Sebastian Redl6df65482011-09-24 17:48:25 +00001421
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001422 if (Member) {
1423 if (EllipsisLoc.isValid())
1424 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001425 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1426
1427 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001428 }
Sebastian Redl6df65482011-09-24 17:48:25 +00001429
Francois Pichet00eb3f92010-12-04 09:14:42 +00001430 // Handle anonymous union case.
1431 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001432 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1433 if (EllipsisLoc.isValid())
1434 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001435 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001436
Sebastian Redl6df65482011-09-24 17:48:25 +00001437 return BuildMemberInitializer(IndirectField, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001438 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001439 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001440 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001441 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001442 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001443 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001444
1445 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001446 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001447 } else {
1448 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1449 LookupParsedName(R, S, &SS);
1450
1451 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1452 if (!TyD) {
1453 if (R.isAmbiguous()) return true;
1454
John McCallfd225442010-04-09 19:01:14 +00001455 // We don't want access-control diagnostics here.
1456 R.suppressDiagnostics();
1457
Douglas Gregor7a886e12010-01-19 06:46:48 +00001458 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1459 bool NotUnknownSpecialization = false;
1460 DeclContext *DC = computeDeclContext(SS, false);
1461 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1462 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1463
1464 if (!NotUnknownSpecialization) {
1465 // When the scope specifier can refer to a member of an unknown
1466 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001467 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1468 SS.getWithLocInContext(Context),
1469 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001470 if (BaseType.isNull())
1471 return true;
1472
Douglas Gregor7a886e12010-01-19 06:46:48 +00001473 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001474 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001475 }
1476 }
1477
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001478 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001479 TypoCorrection Corr;
Douglas Gregor7a886e12010-01-19 06:46:48 +00001480 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001481 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1482 ClassDecl, false, CTC_NoKeywords))) {
1483 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1484 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1485 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001486 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001487 // We have found a non-static data member with a similar
1488 // name to what was typed; complain and initialize that
1489 // member.
1490 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001491 << MemberOrBase << true << CorrectedQuotedStr
1492 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001493 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001494 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001495
Sebastian Redl6df65482011-09-24 17:48:25 +00001496 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001497 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001498 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001499 const CXXBaseSpecifier *DirectBaseSpec;
1500 const CXXBaseSpecifier *VirtualBaseSpec;
1501 if (FindBaseInitializer(*this, ClassDecl,
1502 Context.getTypeDeclType(Type),
1503 DirectBaseSpec, VirtualBaseSpec)) {
1504 // We have found a direct or virtual base class with a
1505 // similar name to what was typed; complain and initialize
1506 // that base class.
1507 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001508 << MemberOrBase << false << CorrectedQuotedStr
1509 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001510
1511 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1512 : VirtualBaseSpec;
1513 Diag(BaseSpec->getSourceRange().getBegin(),
1514 diag::note_base_class_specified_here)
1515 << BaseSpec->getType()
1516 << BaseSpec->getSourceRange();
1517
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001518 TyD = Type;
1519 }
1520 }
1521 }
1522
Douglas Gregor7a886e12010-01-19 06:46:48 +00001523 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001524 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001525 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001526 return true;
1527 }
John McCall2b194412009-12-21 10:41:20 +00001528 }
1529
Douglas Gregor7a886e12010-01-19 06:46:48 +00001530 if (BaseType.isNull()) {
1531 BaseType = Context.getTypeDeclType(TyD);
1532 if (SS.isSet()) {
1533 NestedNameSpecifier *Qualifier =
1534 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001535
Douglas Gregor7a886e12010-01-19 06:46:48 +00001536 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001537 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001538 }
John McCall2b194412009-12-21 10:41:20 +00001539 }
1540 }
Mike Stump1eb44332009-09-09 15:08:12 +00001541
John McCalla93c9342009-12-07 02:54:59 +00001542 if (!TInfo)
1543 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001544
Sebastian Redl6df65482011-09-24 17:48:25 +00001545 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001546}
1547
Chandler Carruth81c64772011-09-03 01:14:15 +00001548/// Checks a member initializer expression for cases where reference (or
1549/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001550static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1551 Expr *Init,
1552 SourceLocation IdLoc) {
1553 QualType MemberTy = Member->getType();
1554
1555 // We only handle pointers and references currently.
1556 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1557 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1558 return;
1559
1560 const bool IsPointer = MemberTy->isPointerType();
1561 if (IsPointer) {
1562 if (const UnaryOperator *Op
1563 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1564 // The only case we're worried about with pointers requires taking the
1565 // address.
1566 if (Op->getOpcode() != UO_AddrOf)
1567 return;
1568
1569 Init = Op->getSubExpr();
1570 } else {
1571 // We only handle address-of expression initializers for pointers.
1572 return;
1573 }
1574 }
1575
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001576 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1577 // Taking the address of a temporary will be diagnosed as a hard error.
1578 if (IsPointer)
1579 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001580
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001581 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1582 << Member << Init->getSourceRange();
1583 } else if (const DeclRefExpr *DRE
1584 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1585 // We only warn when referring to a non-reference parameter declaration.
1586 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1587 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001588 return;
1589
1590 S.Diag(Init->getExprLoc(),
1591 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1592 : diag::warn_bind_ref_member_to_parameter)
1593 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001594 } else {
1595 // Other initializers are fine.
1596 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001597 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001598
1599 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1600 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00001601}
1602
John McCallb4190042009-11-04 23:02:40 +00001603/// Checks an initializer expression for use of uninitialized fields, such as
1604/// containing the field that is being initialized. Returns true if there is an
1605/// uninitialized field was used an updates the SourceLocation parameter; false
1606/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001607static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001608 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001609 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001610 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1611
Nick Lewycky43ad1822010-06-15 07:32:55 +00001612 if (isa<CallExpr>(S)) {
1613 // Do not descend into function calls or constructors, as the use
1614 // of an uninitialized field may be valid. One would have to inspect
1615 // the contents of the function/ctor to determine if it is safe or not.
1616 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1617 // may be safe, depending on what the function/ctor does.
1618 return false;
1619 }
1620 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1621 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001622
1623 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1624 // The member expression points to a static data member.
1625 assert(VD->isStaticDataMember() &&
1626 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001627 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001628 return false;
1629 }
1630
1631 if (isa<EnumConstantDecl>(RhsField)) {
1632 // The member expression points to an enum.
1633 return false;
1634 }
1635
John McCallb4190042009-11-04 23:02:40 +00001636 if (RhsField == LhsField) {
1637 // Initializing a field with itself. Throw a warning.
1638 // But wait; there are exceptions!
1639 // Exception #1: The field may not belong to this record.
1640 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001641 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001642 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1643 // Even though the field matches, it does not belong to this record.
1644 return false;
1645 }
1646 // None of the exceptions triggered; return true to indicate an
1647 // uninitialized field was used.
1648 *L = ME->getMemberLoc();
1649 return true;
1650 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001651 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001652 // sizeof/alignof doesn't reference contents, do not warn.
1653 return false;
1654 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1655 // address-of doesn't reference contents (the pointer may be dereferenced
1656 // in the same expression but it would be rare; and weird).
1657 if (UOE->getOpcode() == UO_AddrOf)
1658 return false;
John McCallb4190042009-11-04 23:02:40 +00001659 }
John McCall7502c1d2011-02-13 04:07:26 +00001660 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001661 if (!*it) {
1662 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001663 continue;
1664 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001665 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1666 return true;
John McCallb4190042009-11-04 23:02:40 +00001667 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001668 return false;
John McCallb4190042009-11-04 23:02:40 +00001669}
1670
John McCallf312b1e2010-08-26 23:41:50 +00001671MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00001672Sema::BuildMemberInitializer(ValueDecl *Member,
1673 const MultiInitializer &Args,
1674 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001675 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1676 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1677 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001678 "Member must be a FieldDecl or IndirectFieldDecl");
1679
Douglas Gregor464b2f02010-11-05 22:21:31 +00001680 if (Member->isInvalidDecl())
1681 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001682
John McCallb4190042009-11-04 23:02:40 +00001683 // Diagnose value-uses of fields to initialize themselves, e.g.
1684 // foo(foo)
1685 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001686 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00001687 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
1688 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00001689 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00001690 Expr *Arg = *I;
1691 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
1692 Arg = DIE->getInit();
1693 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00001694 // FIXME: Return true in the case when other fields are used before being
1695 // uninitialized. For example, let this field be the i'th field. When
1696 // initializing the i'th field, throw a warning if any of the >= i'th
1697 // fields are used, as they are not yet initialized.
1698 // Right now we are only handling the case where the i'th field uses
1699 // itself in its initializer.
1700 Diag(L, diag::warn_field_is_uninit);
1701 }
1702 }
1703
Sebastian Redl6df65482011-09-24 17:48:25 +00001704 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00001705
Chandler Carruth894aed92010-12-06 09:23:57 +00001706 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001707 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001708 // Can't check initialization for a member of dependent type or when
1709 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00001710 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001711
John McCallf85e1932011-06-15 23:02:42 +00001712 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00001713 } else {
1714 // Initialize the member.
1715 InitializedEntity MemberEntity =
1716 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1717 : InitializedEntity::InitializeMember(IndirectMember, 0);
1718 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00001719 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
1720 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00001721
Sebastian Redl6df65482011-09-24 17:48:25 +00001722 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00001723 if (MemberInit.isInvalid())
1724 return true;
1725
Sebastian Redl6df65482011-09-24 17:48:25 +00001726 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00001727
1728 // C++0x [class.base.init]p7:
1729 // The initialization of each base and member constitutes a
1730 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001731 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001732 if (MemberInit.isInvalid())
1733 return true;
1734
1735 // If we are in a dependent context, template instantiation will
1736 // perform this type-checking again. Just save the arguments that we
1737 // received in a ParenListExpr.
1738 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1739 // of the information that we have about the member
1740 // initializer. However, deconstructing the ASTs is a dicey process,
1741 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00001742 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001743 Init = Args.CreateInitExpr(Context,
1744 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00001745 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00001746 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00001747 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
1748 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001749 }
1750
Chandler Carruth894aed92010-12-06 09:23:57 +00001751 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001752 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00001753 IdLoc, Args.getStartLoc(),
1754 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00001755 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001756 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00001757 IdLoc, Args.getStartLoc(),
1758 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00001759 }
Eli Friedman59c04372009-07-29 19:44:27 +00001760}
1761
John McCallf312b1e2010-08-26 23:41:50 +00001762MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001763Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00001764 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00001765 SourceLocation NameLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001766 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001767 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1768 if (!LangOpts.CPlusPlus0x)
1769 return Diag(Loc, diag::err_delegation_0x_only)
1770 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001771
Sean Hunt41717662011-02-26 19:13:13 +00001772 // Initialize the object.
1773 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1774 QualType(ClassDecl->getTypeForDecl(), 0));
1775 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00001776 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
1777 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00001778
Sebastian Redl6df65482011-09-24 17:48:25 +00001779 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00001780 if (DelegationInit.isInvalid())
1781 return true;
1782
1783 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001784 CXXConstructorDecl *Constructor
1785 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001786 assert(Constructor && "Delegating constructor with no target?");
1787
Sebastian Redl6df65482011-09-24 17:48:25 +00001788 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00001789
1790 // C++0x [class.base.init]p7:
1791 // The initialization of each base and member constitutes a
1792 // full-expression.
1793 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1794 if (DelegationInit.isInvalid())
1795 return true;
1796
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001797 assert(!CurContext->isDependentContext());
Sebastian Redl6df65482011-09-24 17:48:25 +00001798 return new (Context) CXXCtorInitializer(Context, Loc, Args.getStartLoc(),
1799 Constructor,
Sean Hunt41717662011-02-26 19:13:13 +00001800 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00001801 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00001802}
1803
1804MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001805Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00001806 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001807 CXXRecordDecl *ClassDecl,
1808 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001809 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00001810
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001811 SourceLocation BaseLoc
1812 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00001813
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001814 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1815 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1816 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1817
1818 // C++ [class.base.init]p2:
1819 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001820 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001821 // of that class, the mem-initializer is ill-formed. A
1822 // mem-initializer-list can initialize a base class using any
1823 // name that denotes that base class type.
1824 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1825
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001826 if (EllipsisLoc.isValid()) {
1827 // This is a pack expansion.
1828 if (!BaseType->containsUnexpandedParameterPack()) {
1829 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00001830 << SourceRange(BaseLoc, Args.getEndLoc());
1831
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001832 EllipsisLoc = SourceLocation();
1833 }
1834 } else {
1835 // Check for any unexpanded parameter packs.
1836 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1837 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00001838
1839 if (Args.DiagnoseUnexpandedParameterPack(*this))
1840 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001841 }
Sebastian Redl6df65482011-09-24 17:48:25 +00001842
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001843 // Check for direct and virtual base classes.
1844 const CXXBaseSpecifier *DirectBaseSpec = 0;
1845 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1846 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001847 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1848 BaseType))
Sebastian Redl6df65482011-09-24 17:48:25 +00001849 return BuildDelegatingInitializer(BaseTInfo, Args, BaseLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001850
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001851 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1852 VirtualBaseSpec);
1853
1854 // C++ [base.class.init]p2:
1855 // Unless the mem-initializer-id names a nonstatic data member of the
1856 // constructor's class or a direct or virtual base of that class, the
1857 // mem-initializer is ill-formed.
1858 if (!DirectBaseSpec && !VirtualBaseSpec) {
1859 // If the class has any dependent bases, then it's possible that
1860 // one of those types will resolve to the same type as
1861 // BaseType. Therefore, just treat this as a dependent base
1862 // class initialization. FIXME: Should we try to check the
1863 // initialization anyway? It seems odd.
1864 if (ClassDecl->hasAnyDependentBases())
1865 Dependent = true;
1866 else
1867 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1868 << BaseType << Context.getTypeDeclType(ClassDecl)
1869 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1870 }
1871 }
1872
1873 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001874 // Can't check initialization for a base of dependent type or when
1875 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00001876 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00001877
John McCallf85e1932011-06-15 23:02:42 +00001878 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Sebastian Redl6df65482011-09-24 17:48:25 +00001880 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1881 /*IsVirtual=*/false,
1882 Args.getStartLoc(), BaseInit,
1883 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001884 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001885
1886 // C++ [base.class.init]p2:
1887 // If a mem-initializer-id is ambiguous because it designates both
1888 // a direct non-virtual base class and an inherited virtual base
1889 // class, the mem-initializer is ill-formed.
1890 if (DirectBaseSpec && VirtualBaseSpec)
1891 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001892 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001893
1894 CXXBaseSpecifier *BaseSpec
1895 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1896 if (!BaseSpec)
1897 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1898
1899 // Initialize the base.
1900 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001901 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001902 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00001903 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
1904 Args.getEndLoc());
1905
1906 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001907 if (BaseInit.isInvalid())
1908 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001909
Sebastian Redl6df65482011-09-24 17:48:25 +00001910 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
1911
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001912 // C++0x [class.base.init]p7:
1913 // The initialization of each base and member constitutes a
1914 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001915 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001916 if (BaseInit.isInvalid())
1917 return true;
1918
1919 // If we are in a dependent context, template instantiation will
1920 // perform this type-checking again. Just save the arguments that we
1921 // received in a ParenListExpr.
1922 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1923 // of the information that we have about the base
1924 // initializer. However, deconstructing the ASTs is a dicey process,
1925 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00001926 if (CurContext->isDependentContext())
1927 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001928
Sean Huntcbb67482011-01-08 20:30:50 +00001929 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00001930 BaseSpec->isVirtual(),
1931 Args.getStartLoc(),
1932 BaseInit.takeAs<Expr>(),
1933 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001934}
1935
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001936// Create a static_cast\<T&&>(expr).
1937static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
1938 QualType ExprType = E->getType();
1939 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
1940 SourceLocation ExprLoc = E->getLocStart();
1941 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
1942 TargetType, ExprLoc);
1943
1944 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1945 SourceRange(ExprLoc, ExprLoc),
1946 E->getSourceRange()).take();
1947}
1948
Anders Carlssone5ef7402010-04-23 03:10:23 +00001949/// ImplicitInitializerKind - How an implicit base or member initializer should
1950/// initialize its base or member.
1951enum ImplicitInitializerKind {
1952 IIK_Default,
1953 IIK_Copy,
1954 IIK_Move
1955};
1956
Anders Carlssondefefd22010-04-23 02:00:02 +00001957static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001958BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001959 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001960 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001961 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001962 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001963 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001964 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1965 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001966
John McCall60d7b3a2010-08-24 06:29:42 +00001967 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001968
1969 switch (ImplicitInitKind) {
1970 case IIK_Default: {
1971 InitializationKind InitKind
1972 = InitializationKind::CreateDefault(Constructor->getLocation());
1973 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1974 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001975 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001976 break;
1977 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001978
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001979 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00001980 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001981 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001982 ParmVarDecl *Param = Constructor->getParamDecl(0);
1983 QualType ParamType = Param->getType().getNonReferenceType();
1984
1985 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001986 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001987 Constructor->getLocation(), ParamType,
1988 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001989
Anders Carlssonc7957502010-04-24 22:02:54 +00001990 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001991 QualType ArgTy =
1992 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1993 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001994
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001995 if (Moving) {
1996 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
1997 }
1998
John McCallf871d0c2010-08-07 06:22:56 +00001999 CXXCastPath BasePath;
2000 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002001 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2002 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002003 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002004 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002005
Anders Carlssone5ef7402010-04-23 03:10:23 +00002006 InitializationKind InitKind
2007 = InitializationKind::CreateDirect(Constructor->getLocation(),
2008 SourceLocation(), SourceLocation());
2009 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2010 &CopyCtorArg, 1);
2011 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002012 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002013 break;
2014 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002015 }
John McCall9ae2f072010-08-23 23:25:46 +00002016
Douglas Gregor53c374f2010-12-07 00:41:46 +00002017 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002018 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002019 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002020
Anders Carlssondefefd22010-04-23 02:00:02 +00002021 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002022 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002023 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2024 SourceLocation()),
2025 BaseSpec->isVirtual(),
2026 SourceLocation(),
2027 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002028 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002029 SourceLocation());
2030
Anders Carlssondefefd22010-04-23 02:00:02 +00002031 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002032}
2033
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002034static bool RefersToRValueRef(Expr *MemRef) {
2035 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2036 return Referenced->getType()->isRValueReferenceType();
2037}
2038
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002039static bool
2040BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002041 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002042 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002043 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002044 if (Field->isInvalidDecl())
2045 return true;
2046
Chandler Carruthf186b542010-06-29 23:50:44 +00002047 SourceLocation Loc = Constructor->getLocation();
2048
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002049 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2050 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002051 ParmVarDecl *Param = Constructor->getParamDecl(0);
2052 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002053
2054 // Suppress copying zero-width bitfields.
2055 if (const Expr *Width = Field->getBitWidth())
2056 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2057 return false;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002058
2059 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002060 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002061 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002062
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002063 if (Moving) {
2064 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2065 }
2066
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002067 // Build a reference to this field within the parameter.
2068 CXXScopeSpec SS;
2069 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2070 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002071 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2072 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002073 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002074 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002075 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002076 ParamType, Loc,
2077 /*IsArrow=*/false,
2078 SS,
2079 /*FirstQualifierInScope=*/0,
2080 MemberLookup,
2081 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002082 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002083 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002084
2085 // C++11 [class.copy]p15:
2086 // - if a member m has rvalue reference type T&&, it is direct-initialized
2087 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002088 if (RefersToRValueRef(CtorArg.get())) {
2089 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002090 }
2091
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002092 // When the field we are copying is an array, create index variables for
2093 // each dimension of the array. We use these index variables to subscript
2094 // the source array, and other clients (e.g., CodeGen) will perform the
2095 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002096 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002097 QualType BaseType = Field->getType();
2098 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002099 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002100 while (const ConstantArrayType *Array
2101 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002102 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002103 // Create the iteration variable for this array index.
2104 IdentifierInfo *IterationVarName = 0;
2105 {
2106 llvm::SmallString<8> Str;
2107 llvm::raw_svector_ostream OS(Str);
2108 OS << "__i" << IndexVariables.size();
2109 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2110 }
2111 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002112 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002113 IterationVarName, SizeType,
2114 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002115 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002116 IndexVariables.push_back(IterationVar);
2117
2118 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002119 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002120 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002121 assert(!IterationVarRef.isInvalid() &&
2122 "Reference to invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002123
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002124 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002125 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002126 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002127 Loc);
2128 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002129 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002130
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002131 BaseType = Array->getElementType();
2132 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002133
2134 // The array subscript expression is an lvalue, which is wrong for moving.
2135 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002136 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002137
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002138 // Construct the entity that we will be initializing. For an array, this
2139 // will be first element in the array, which may require several levels
2140 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002141 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002142 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002143 if (Indirect)
2144 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2145 else
2146 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002147 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2148 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2149 0,
2150 Entities.back()));
2151
2152 // Direct-initialize to use the copy constructor.
2153 InitializationKind InitKind =
2154 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2155
Sebastian Redl74e611a2011-09-04 18:14:28 +00002156 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002157 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002158 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002159
John McCall60d7b3a2010-08-24 06:29:42 +00002160 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002161 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002162 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002163 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002164 if (MemberInit.isInvalid())
2165 return true;
2166
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002167 if (Indirect) {
2168 assert(IndexVariables.size() == 0 &&
2169 "Indirect field improperly initialized");
2170 CXXMemberInit
2171 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2172 Loc, Loc,
2173 MemberInit.takeAs<Expr>(),
2174 Loc);
2175 } else
2176 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2177 Loc, MemberInit.takeAs<Expr>(),
2178 Loc,
2179 IndexVariables.data(),
2180 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002181 return false;
2182 }
2183
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002184 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2185
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002186 QualType FieldBaseElementType =
2187 SemaRef.Context.getBaseElementType(Field->getType());
2188
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002189 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002190 InitializedEntity InitEntity
2191 = Indirect? InitializedEntity::InitializeMember(Indirect)
2192 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002193 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002194 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002195
2196 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002197 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002198 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002199
Douglas Gregor53c374f2010-12-07 00:41:46 +00002200 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002201 if (MemberInit.isInvalid())
2202 return true;
2203
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002204 if (Indirect)
2205 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2206 Indirect, Loc,
2207 Loc,
2208 MemberInit.get(),
2209 Loc);
2210 else
2211 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2212 Field, Loc, Loc,
2213 MemberInit.get(),
2214 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002215 return false;
2216 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002217
Sean Hunt1f2f3842011-05-17 00:19:05 +00002218 if (!Field->getParent()->isUnion()) {
2219 if (FieldBaseElementType->isReferenceType()) {
2220 SemaRef.Diag(Constructor->getLocation(),
2221 diag::err_uninitialized_member_in_ctor)
2222 << (int)Constructor->isImplicit()
2223 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2224 << 0 << Field->getDeclName();
2225 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2226 return true;
2227 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002228
Sean Hunt1f2f3842011-05-17 00:19:05 +00002229 if (FieldBaseElementType.isConstQualified()) {
2230 SemaRef.Diag(Constructor->getLocation(),
2231 diag::err_uninitialized_member_in_ctor)
2232 << (int)Constructor->isImplicit()
2233 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2234 << 1 << Field->getDeclName();
2235 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2236 return true;
2237 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002238 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002239
John McCallf85e1932011-06-15 23:02:42 +00002240 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2241 FieldBaseElementType->isObjCRetainableType() &&
2242 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2243 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2244 // Instant objects:
2245 // Default-initialize Objective-C pointers to NULL.
2246 CXXMemberInit
2247 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2248 Loc, Loc,
2249 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2250 Loc);
2251 return false;
2252 }
2253
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002254 // Nothing to initialize.
2255 CXXMemberInit = 0;
2256 return false;
2257}
John McCallf1860e52010-05-20 23:23:51 +00002258
2259namespace {
2260struct BaseAndFieldInfo {
2261 Sema &S;
2262 CXXConstructorDecl *Ctor;
2263 bool AnyErrorsInInits;
2264 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002265 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002266 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002267
2268 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2269 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002270 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2271 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002272 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002273 else if (Generated && Ctor->isMoveConstructor())
2274 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002275 else
2276 IIK = IIK_Default;
2277 }
2278};
2279}
2280
Richard Smitha4950662011-09-19 13:34:43 +00002281/// \brief Determine whether the given indirect field declaration is somewhere
2282/// within an anonymous union.
2283static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2284 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2285 CEnd = F->chain_end();
2286 C != CEnd; ++C)
2287 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2288 if (Record->isUnion())
2289 return true;
2290
2291 return false;
2292}
2293
Richard Smith7a614d82011-06-11 17:19:42 +00002294static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002295 FieldDecl *Field,
2296 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002297
Chandler Carruthe861c602010-06-30 02:59:29 +00002298 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002299 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002300 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002301 return false;
2302 }
2303
Richard Smith7a614d82011-06-11 17:19:42 +00002304 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2305 // has a brace-or-equal-initializer, the entity is initialized as specified
2306 // in [dcl.init].
2307 if (Field->hasInClassInitializer()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002308 CXXCtorInitializer *Init;
2309 if (Indirect)
2310 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2311 SourceLocation(),
2312 SourceLocation(), 0,
2313 SourceLocation());
2314 else
2315 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2316 SourceLocation(),
2317 SourceLocation(), 0,
2318 SourceLocation());
2319 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002320 return false;
2321 }
2322
Richard Smithc115f632011-09-18 11:14:50 +00002323 // Don't build an implicit initializer for union members if none was
2324 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002325 if (Field->getParent()->isUnion() ||
2326 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002327 return false;
2328
John McCallf1860e52010-05-20 23:23:51 +00002329 // Don't try to build an implicit initializer if there were semantic
2330 // errors in any of the initializers (and therefore we might be
2331 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002332 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002333 return false;
2334
Sean Huntcbb67482011-01-08 20:30:50 +00002335 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002336 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2337 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002338 return true;
John McCallf1860e52010-05-20 23:23:51 +00002339
Francois Pichet00eb3f92010-12-04 09:14:42 +00002340 if (Init)
2341 Info.AllToInit.push_back(Init);
2342
John McCallf1860e52010-05-20 23:23:51 +00002343 return false;
2344}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002345
2346bool
2347Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2348 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002349 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002350 Constructor->setNumCtorInitializers(1);
2351 CXXCtorInitializer **initializer =
2352 new (Context) CXXCtorInitializer*[1];
2353 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2354 Constructor->setCtorInitializers(initializer);
2355
Sean Huntb76af9c2011-05-03 23:05:34 +00002356 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2357 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2358 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2359 }
2360
Sean Huntc1598702011-05-05 00:05:47 +00002361 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002362
Sean Hunt059ce0d2011-05-01 07:04:31 +00002363 return false;
2364}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002365
John McCallb77115d2011-06-17 00:18:42 +00002366bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2367 CXXCtorInitializer **Initializers,
2368 unsigned NumInitializers,
2369 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002370 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002371 // Just store the initializers as written, they will be checked during
2372 // instantiation.
2373 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002374 Constructor->setNumCtorInitializers(NumInitializers);
2375 CXXCtorInitializer **baseOrMemberInitializers =
2376 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002377 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002378 NumInitializers * sizeof(CXXCtorInitializer*));
2379 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002380 }
2381
2382 return false;
2383 }
2384
John McCallf1860e52010-05-20 23:23:51 +00002385 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002386
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002387 // We need to build the initializer AST according to order of construction
2388 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002389 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002390 if (!ClassDecl)
2391 return true;
2392
Eli Friedman80c30da2009-11-09 19:20:36 +00002393 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002395 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002396 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002397
2398 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002399 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002400 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002401 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002402 }
2403
Anders Carlsson711f34a2010-04-21 19:52:01 +00002404 // Keep track of the direct virtual bases.
2405 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2406 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2407 E = ClassDecl->bases_end(); I != E; ++I) {
2408 if (I->isVirtual())
2409 DirectVBases.insert(I);
2410 }
2411
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002412 // Push virtual bases before others.
2413 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2414 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2415
Sean Huntcbb67482011-01-08 20:30:50 +00002416 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002417 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2418 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002419 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002420 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002421 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002422 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002423 VBase, IsInheritedVirtualBase,
2424 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002425 HadError = true;
2426 continue;
2427 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002428
John McCallf1860e52010-05-20 23:23:51 +00002429 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002430 }
2431 }
Mike Stump1eb44332009-09-09 15:08:12 +00002432
John McCallf1860e52010-05-20 23:23:51 +00002433 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002434 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2435 E = ClassDecl->bases_end(); Base != E; ++Base) {
2436 // Virtuals are in the virtual base list and already constructed.
2437 if (Base->isVirtual())
2438 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002439
Sean Huntcbb67482011-01-08 20:30:50 +00002440 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002441 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2442 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002443 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002444 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002445 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002446 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002447 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002448 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002449 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002450 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002451
John McCallf1860e52010-05-20 23:23:51 +00002452 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002453 }
2454 }
Mike Stump1eb44332009-09-09 15:08:12 +00002455
John McCallf1860e52010-05-20 23:23:51 +00002456 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002457 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2458 MemEnd = ClassDecl->decls_end();
2459 Mem != MemEnd; ++Mem) {
2460 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2461 if (F->getType()->isIncompleteArrayType()) {
2462 assert(ClassDecl->hasFlexibleArrayMember() &&
2463 "Incomplete array type is not valid");
2464 continue;
2465 }
2466
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002467 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002468 // handle anonymous struct/union fields based on their individual
2469 // indirect fields.
2470 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2471 continue;
2472
2473 if (CollectFieldInitializer(*this, Info, F))
2474 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002475 continue;
2476 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002477
2478 // Beyond this point, we only consider default initialization.
2479 if (Info.IIK != IIK_Default)
2480 continue;
2481
2482 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2483 if (F->getType()->isIncompleteArrayType()) {
2484 assert(ClassDecl->hasFlexibleArrayMember() &&
2485 "Incomplete array type is not valid");
2486 continue;
2487 }
2488
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002489 // Initialize each field of an anonymous struct individually.
2490 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2491 HadError = true;
2492
2493 continue;
2494 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002495 }
Mike Stump1eb44332009-09-09 15:08:12 +00002496
John McCallf1860e52010-05-20 23:23:51 +00002497 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002498 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002499 Constructor->setNumCtorInitializers(NumInitializers);
2500 CXXCtorInitializer **baseOrMemberInitializers =
2501 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002502 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002503 NumInitializers * sizeof(CXXCtorInitializer*));
2504 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002505
John McCallef027fe2010-03-16 21:39:52 +00002506 // Constructors implicitly reference the base and member
2507 // destructors.
2508 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2509 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002510 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002511
2512 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002513}
2514
Eli Friedman6347f422009-07-21 19:28:10 +00002515static void *GetKeyForTopLevelField(FieldDecl *Field) {
2516 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002517 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002518 if (RT->getDecl()->isAnonymousStructOrUnion())
2519 return static_cast<void *>(RT->getDecl());
2520 }
2521 return static_cast<void *>(Field);
2522}
2523
Anders Carlssonea356fb2010-04-02 05:42:15 +00002524static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002525 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002526}
2527
Anders Carlssonea356fb2010-04-02 05:42:15 +00002528static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002529 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002530 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002531 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002532
Eli Friedman6347f422009-07-21 19:28:10 +00002533 // For fields injected into the class via declaration of an anonymous union,
2534 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002535 FieldDecl *Field = Member->getAnyMember();
2536
John McCall3c3ccdb2010-04-10 09:28:51 +00002537 // If the field is a member of an anonymous struct or union, our key
2538 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002539 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002540 if (RD->isAnonymousStructOrUnion()) {
2541 while (true) {
2542 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2543 if (Parent->isAnonymousStructOrUnion())
2544 RD = Parent;
2545 else
2546 break;
2547 }
2548
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002549 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002550 }
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002552 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002553}
2554
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002555static void
2556DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002557 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002558 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002559 unsigned NumInits) {
2560 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002561 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002563 // Don't check initializers order unless the warning is enabled at the
2564 // location of at least one initializer.
2565 bool ShouldCheckOrder = false;
2566 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002567 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002568 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2569 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00002570 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002571 ShouldCheckOrder = true;
2572 break;
2573 }
2574 }
2575 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002576 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002577
John McCalld6ca8da2010-04-10 07:37:23 +00002578 // Build the list of bases and members in the order that they'll
2579 // actually be initialized. The explicit initializers should be in
2580 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002581 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Anders Carlsson071d6102010-04-02 03:38:04 +00002583 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2584
John McCalld6ca8da2010-04-10 07:37:23 +00002585 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002586 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002587 ClassDecl->vbases_begin(),
2588 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002589 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002590
John McCalld6ca8da2010-04-10 07:37:23 +00002591 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002592 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002593 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002594 if (Base->isVirtual())
2595 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002596 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002597 }
Mike Stump1eb44332009-09-09 15:08:12 +00002598
John McCalld6ca8da2010-04-10 07:37:23 +00002599 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002600 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2601 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002602 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002603
John McCalld6ca8da2010-04-10 07:37:23 +00002604 unsigned NumIdealInits = IdealInitKeys.size();
2605 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002606
Sean Huntcbb67482011-01-08 20:30:50 +00002607 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002608 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002609 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002610 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002611
2612 // Scan forward to try to find this initializer in the idealized
2613 // initializers list.
2614 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2615 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002616 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002617
2618 // If we didn't find this initializer, it must be because we
2619 // scanned past it on a previous iteration. That can only
2620 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002621 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002622 Sema::SemaDiagnosticBuilder D =
2623 SemaRef.Diag(PrevInit->getSourceLocation(),
2624 diag::warn_initializer_out_of_order);
2625
Francois Pichet00eb3f92010-12-04 09:14:42 +00002626 if (PrevInit->isAnyMemberInitializer())
2627 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002628 else
2629 D << 1 << PrevInit->getBaseClassInfo()->getType();
2630
Francois Pichet00eb3f92010-12-04 09:14:42 +00002631 if (Init->isAnyMemberInitializer())
2632 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002633 else
2634 D << 1 << Init->getBaseClassInfo()->getType();
2635
2636 // Move back to the initializer's location in the ideal list.
2637 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2638 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002639 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002640
2641 assert(IdealIndex != NumIdealInits &&
2642 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002643 }
John McCalld6ca8da2010-04-10 07:37:23 +00002644
2645 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002646 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002647}
2648
John McCall3c3ccdb2010-04-10 09:28:51 +00002649namespace {
2650bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002651 CXXCtorInitializer *Init,
2652 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002653 if (!PrevInit) {
2654 PrevInit = Init;
2655 return false;
2656 }
2657
2658 if (FieldDecl *Field = Init->getMember())
2659 S.Diag(Init->getSourceLocation(),
2660 diag::err_multiple_mem_initialization)
2661 << Field->getDeclName()
2662 << Init->getSourceRange();
2663 else {
John McCallf4c73712011-01-19 06:33:43 +00002664 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002665 assert(BaseClass && "neither field nor base");
2666 S.Diag(Init->getSourceLocation(),
2667 diag::err_multiple_base_initialization)
2668 << QualType(BaseClass, 0)
2669 << Init->getSourceRange();
2670 }
2671 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2672 << 0 << PrevInit->getSourceRange();
2673
2674 return true;
2675}
2676
Sean Huntcbb67482011-01-08 20:30:50 +00002677typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002678typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2679
2680bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002681 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002682 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002683 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002684 RecordDecl *Parent = Field->getParent();
2685 if (!Parent->isAnonymousStructOrUnion())
2686 return false;
2687
2688 NamedDecl *Child = Field;
2689 do {
2690 if (Parent->isUnion()) {
2691 UnionEntry &En = Unions[Parent];
2692 if (En.first && En.first != Child) {
2693 S.Diag(Init->getSourceLocation(),
2694 diag::err_multiple_mem_union_initialization)
2695 << Field->getDeclName()
2696 << Init->getSourceRange();
2697 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2698 << 0 << En.second->getSourceRange();
2699 return true;
2700 } else if (!En.first) {
2701 En.first = Child;
2702 En.second = Init;
2703 }
2704 }
2705
2706 Child = Parent;
2707 Parent = cast<RecordDecl>(Parent->getDeclContext());
2708 } while (Parent->isAnonymousStructOrUnion());
2709
2710 return false;
2711}
2712}
2713
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002714/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002715void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002716 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00002717 CXXCtorInitializer **meminits,
2718 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002719 bool AnyErrors) {
2720 if (!ConstructorDecl)
2721 return;
2722
2723 AdjustDeclIfTemplate(ConstructorDecl);
2724
2725 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002726 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002727
2728 if (!Constructor) {
2729 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2730 return;
2731 }
2732
Sean Huntcbb67482011-01-08 20:30:50 +00002733 CXXCtorInitializer **MemInits =
2734 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002735
2736 // Mapping for the duplicate initializers check.
2737 // For member initializers, this is keyed with a FieldDecl*.
2738 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002739 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002740
2741 // Mapping for the inconsistent anonymous-union initializers check.
2742 RedundantUnionMap MemberUnions;
2743
Anders Carlssonea356fb2010-04-02 05:42:15 +00002744 bool HadError = false;
2745 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002746 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002747
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002748 // Set the source order index.
2749 Init->setSourceOrder(i);
2750
Francois Pichet00eb3f92010-12-04 09:14:42 +00002751 if (Init->isAnyMemberInitializer()) {
2752 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002753 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2754 CheckRedundantUnionInit(*this, Init, MemberUnions))
2755 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002756 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002757 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2758 if (CheckRedundantInit(*this, Init, Members[Key]))
2759 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002760 } else {
2761 assert(Init->isDelegatingInitializer());
2762 // This must be the only initializer
2763 if (i != 0 || NumMemInits > 1) {
2764 Diag(MemInits[0]->getSourceLocation(),
2765 diag::err_delegating_initializer_alone)
2766 << MemInits[0]->getSourceRange();
2767 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002768 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002769 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002770 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002771 // Return immediately as the initializer is set.
2772 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002773 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002774 }
2775
Anders Carlssonea356fb2010-04-02 05:42:15 +00002776 if (HadError)
2777 return;
2778
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002779 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002780
Sean Huntcbb67482011-01-08 20:30:50 +00002781 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002782}
2783
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002784void
John McCallef027fe2010-03-16 21:39:52 +00002785Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2786 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00002787 // Ignore dependent contexts. Also ignore unions, since their members never
2788 // have destructors implicitly called.
2789 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002790 return;
John McCall58e6f342010-03-16 05:22:47 +00002791
2792 // FIXME: all the access-control diagnostics are positioned on the
2793 // field/base declaration. That's probably good; that said, the
2794 // user might reasonably want to know why the destructor is being
2795 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002796
Anders Carlsson9f853df2009-11-17 04:44:12 +00002797 // Non-static data members.
2798 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2799 E = ClassDecl->field_end(); I != E; ++I) {
2800 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002801 if (Field->isInvalidDecl())
2802 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002803 QualType FieldType = Context.getBaseElementType(Field->getType());
2804
2805 const RecordType* RT = FieldType->getAs<RecordType>();
2806 if (!RT)
2807 continue;
2808
2809 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002810 if (FieldClassDecl->isInvalidDecl())
2811 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002812 if (FieldClassDecl->hasTrivialDestructor())
2813 continue;
2814
Douglas Gregordb89f282010-07-01 22:47:18 +00002815 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002816 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002817 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002818 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002819 << Field->getDeclName()
2820 << FieldType);
2821
John McCallef027fe2010-03-16 21:39:52 +00002822 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002823 }
2824
John McCall58e6f342010-03-16 05:22:47 +00002825 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2826
Anders Carlsson9f853df2009-11-17 04:44:12 +00002827 // Bases.
2828 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2829 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002830 // Bases are always records in a well-formed non-dependent class.
2831 const RecordType *RT = Base->getType()->getAs<RecordType>();
2832
2833 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002834 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002835 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002836
John McCall58e6f342010-03-16 05:22:47 +00002837 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002838 // If our base class is invalid, we probably can't get its dtor anyway.
2839 if (BaseClassDecl->isInvalidDecl())
2840 continue;
2841 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002842 if (BaseClassDecl->hasTrivialDestructor())
2843 continue;
John McCall58e6f342010-03-16 05:22:47 +00002844
Douglas Gregordb89f282010-07-01 22:47:18 +00002845 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002846 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002847
2848 // FIXME: caret should be on the start of the class name
2849 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002850 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002851 << Base->getType()
2852 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002853
John McCallef027fe2010-03-16 21:39:52 +00002854 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002855 }
2856
2857 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002858 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2859 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002860
2861 // Bases are always records in a well-formed non-dependent class.
2862 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2863
2864 // Ignore direct virtual bases.
2865 if (DirectVirtualBases.count(RT))
2866 continue;
2867
John McCall58e6f342010-03-16 05:22:47 +00002868 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002869 // If our base class is invalid, we probably can't get its dtor anyway.
2870 if (BaseClassDecl->isInvalidDecl())
2871 continue;
2872 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002873 if (BaseClassDecl->hasTrivialDestructor())
2874 continue;
John McCall58e6f342010-03-16 05:22:47 +00002875
Douglas Gregordb89f282010-07-01 22:47:18 +00002876 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002877 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002878 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002879 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002880 << VBase->getType());
2881
John McCallef027fe2010-03-16 21:39:52 +00002882 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002883 }
2884}
2885
John McCalld226f652010-08-21 09:40:31 +00002886void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002887 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002888 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Mike Stump1eb44332009-09-09 15:08:12 +00002890 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002891 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002892 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002893}
2894
Mike Stump1eb44332009-09-09 15:08:12 +00002895bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002896 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002897 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002898 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002899 else
John McCall94c3b562010-08-18 09:41:07 +00002900 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002901}
2902
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002903bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002904 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002905 if (!getLangOptions().CPlusPlus)
2906 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002907
Anders Carlsson11f21a02009-03-23 19:10:31 +00002908 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002909 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002910
Ted Kremenek6217b802009-07-29 21:53:49 +00002911 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002912 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002913 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002914 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002915
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002916 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002917 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002918 }
Mike Stump1eb44332009-09-09 15:08:12 +00002919
Ted Kremenek6217b802009-07-29 21:53:49 +00002920 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002921 if (!RT)
2922 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002923
John McCall86ff3082010-02-04 22:26:26 +00002924 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002925
John McCall94c3b562010-08-18 09:41:07 +00002926 // We can't answer whether something is abstract until it has a
2927 // definition. If it's currently being defined, we'll walk back
2928 // over all the declarations when we have a full definition.
2929 const CXXRecordDecl *Def = RD->getDefinition();
2930 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002931 return false;
2932
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002933 if (!RD->isAbstract())
2934 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002936 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002937 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002938
John McCall94c3b562010-08-18 09:41:07 +00002939 return true;
2940}
2941
2942void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2943 // Check if we've already emitted the list of pure virtual functions
2944 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002945 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002946 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002947
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002948 CXXFinalOverriderMap FinalOverriders;
2949 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002950
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002951 // Keep a set of seen pure methods so we won't diagnose the same method
2952 // more than once.
2953 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2954
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002955 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2956 MEnd = FinalOverriders.end();
2957 M != MEnd;
2958 ++M) {
2959 for (OverridingMethods::iterator SO = M->second.begin(),
2960 SOEnd = M->second.end();
2961 SO != SOEnd; ++SO) {
2962 // C++ [class.abstract]p4:
2963 // A class is abstract if it contains or inherits at least one
2964 // pure virtual function for which the final overrider is pure
2965 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002967 //
2968 if (SO->second.size() != 1)
2969 continue;
2970
2971 if (!SO->second.front().Method->isPure())
2972 continue;
2973
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002974 if (!SeenPureMethods.insert(SO->second.front().Method))
2975 continue;
2976
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002977 Diag(SO->second.front().Method->getLocation(),
2978 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002979 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002980 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002981 }
2982
2983 if (!PureVirtualClassDiagSet)
2984 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2985 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002986}
2987
Anders Carlsson8211eff2009-03-24 01:19:16 +00002988namespace {
John McCall94c3b562010-08-18 09:41:07 +00002989struct AbstractUsageInfo {
2990 Sema &S;
2991 CXXRecordDecl *Record;
2992 CanQualType AbstractType;
2993 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002994
John McCall94c3b562010-08-18 09:41:07 +00002995 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2996 : S(S), Record(Record),
2997 AbstractType(S.Context.getCanonicalType(
2998 S.Context.getTypeDeclType(Record))),
2999 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003000
John McCall94c3b562010-08-18 09:41:07 +00003001 void DiagnoseAbstractType() {
3002 if (Invalid) return;
3003 S.DiagnoseAbstractType(Record);
3004 Invalid = true;
3005 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003006
John McCall94c3b562010-08-18 09:41:07 +00003007 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3008};
3009
3010struct CheckAbstractUsage {
3011 AbstractUsageInfo &Info;
3012 const NamedDecl *Ctx;
3013
3014 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3015 : Info(Info), Ctx(Ctx) {}
3016
3017 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3018 switch (TL.getTypeLocClass()) {
3019#define ABSTRACT_TYPELOC(CLASS, PARENT)
3020#define TYPELOC(CLASS, PARENT) \
3021 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3022#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003023 }
John McCall94c3b562010-08-18 09:41:07 +00003024 }
Mike Stump1eb44332009-09-09 15:08:12 +00003025
John McCall94c3b562010-08-18 09:41:07 +00003026 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3027 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3028 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003029 if (!TL.getArg(I))
3030 continue;
3031
John McCall94c3b562010-08-18 09:41:07 +00003032 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3033 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003034 }
John McCall94c3b562010-08-18 09:41:07 +00003035 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003036
John McCall94c3b562010-08-18 09:41:07 +00003037 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3038 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3039 }
Mike Stump1eb44332009-09-09 15:08:12 +00003040
John McCall94c3b562010-08-18 09:41:07 +00003041 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3042 // Visit the type parameters from a permissive context.
3043 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3044 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3045 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3046 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3047 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3048 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003049 }
John McCall94c3b562010-08-18 09:41:07 +00003050 }
Mike Stump1eb44332009-09-09 15:08:12 +00003051
John McCall94c3b562010-08-18 09:41:07 +00003052 // Visit pointee types from a permissive context.
3053#define CheckPolymorphic(Type) \
3054 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3055 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3056 }
3057 CheckPolymorphic(PointerTypeLoc)
3058 CheckPolymorphic(ReferenceTypeLoc)
3059 CheckPolymorphic(MemberPointerTypeLoc)
3060 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003061
John McCall94c3b562010-08-18 09:41:07 +00003062 /// Handle all the types we haven't given a more specific
3063 /// implementation for above.
3064 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3065 // Every other kind of type that we haven't called out already
3066 // that has an inner type is either (1) sugar or (2) contains that
3067 // inner type in some way as a subobject.
3068 if (TypeLoc Next = TL.getNextTypeLoc())
3069 return Visit(Next, Sel);
3070
3071 // If there's no inner type and we're in a permissive context,
3072 // don't diagnose.
3073 if (Sel == Sema::AbstractNone) return;
3074
3075 // Check whether the type matches the abstract type.
3076 QualType T = TL.getType();
3077 if (T->isArrayType()) {
3078 Sel = Sema::AbstractArrayType;
3079 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003080 }
John McCall94c3b562010-08-18 09:41:07 +00003081 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3082 if (CT != Info.AbstractType) return;
3083
3084 // It matched; do some magic.
3085 if (Sel == Sema::AbstractArrayType) {
3086 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3087 << T << TL.getSourceRange();
3088 } else {
3089 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3090 << Sel << T << TL.getSourceRange();
3091 }
3092 Info.DiagnoseAbstractType();
3093 }
3094};
3095
3096void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3097 Sema::AbstractDiagSelID Sel) {
3098 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3099}
3100
3101}
3102
3103/// Check for invalid uses of an abstract type in a method declaration.
3104static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3105 CXXMethodDecl *MD) {
3106 // No need to do the check on definitions, which require that
3107 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003108 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003109 return;
3110
3111 // For safety's sake, just ignore it if we don't have type source
3112 // information. This should never happen for non-implicit methods,
3113 // but...
3114 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3115 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3116}
3117
3118/// Check for invalid uses of an abstract type within a class definition.
3119static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3120 CXXRecordDecl *RD) {
3121 for (CXXRecordDecl::decl_iterator
3122 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3123 Decl *D = *I;
3124 if (D->isImplicit()) continue;
3125
3126 // Methods and method templates.
3127 if (isa<CXXMethodDecl>(D)) {
3128 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3129 } else if (isa<FunctionTemplateDecl>(D)) {
3130 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3131 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3132
3133 // Fields and static variables.
3134 } else if (isa<FieldDecl>(D)) {
3135 FieldDecl *FD = cast<FieldDecl>(D);
3136 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3137 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3138 } else if (isa<VarDecl>(D)) {
3139 VarDecl *VD = cast<VarDecl>(D);
3140 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3141 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3142
3143 // Nested classes and class templates.
3144 } else if (isa<CXXRecordDecl>(D)) {
3145 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3146 } else if (isa<ClassTemplateDecl>(D)) {
3147 CheckAbstractClassUsage(Info,
3148 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3149 }
3150 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003151}
3152
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003153/// \brief Perform semantic checks on a class definition that has been
3154/// completing, introducing implicitly-declared members, checking for
3155/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003156void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003157 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003158 return;
3159
John McCall94c3b562010-08-18 09:41:07 +00003160 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3161 AbstractUsageInfo Info(*this, Record);
3162 CheckAbstractClassUsage(Info, Record);
3163 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003164
3165 // If this is not an aggregate type and has no user-declared constructor,
3166 // complain about any non-static data members of reference or const scalar
3167 // type, since they will never get initializers.
3168 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3169 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3170 bool Complained = false;
3171 for (RecordDecl::field_iterator F = Record->field_begin(),
3172 FEnd = Record->field_end();
3173 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003174 if (F->hasInClassInitializer())
3175 continue;
3176
Douglas Gregor325e5932010-04-15 00:00:53 +00003177 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003178 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003179 if (!Complained) {
3180 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3181 << Record->getTagKind() << Record;
3182 Complained = true;
3183 }
3184
3185 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3186 << F->getType()->isReferenceType()
3187 << F->getDeclName();
3188 }
3189 }
3190 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003191
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003192 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003193 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003194
3195 if (Record->getIdentifier()) {
3196 // C++ [class.mem]p13:
3197 // If T is the name of a class, then each of the following shall have a
3198 // name different from T:
3199 // - every member of every anonymous union that is a member of class T.
3200 //
3201 // C++ [class.mem]p14:
3202 // In addition, if class T has a user-declared constructor (12.1), every
3203 // non-static data member of class T shall have a name different from T.
3204 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003205 R.first != R.second; ++R.first) {
3206 NamedDecl *D = *R.first;
3207 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3208 isa<IndirectFieldDecl>(D)) {
3209 Diag(D->getLocation(), diag::err_member_name_of_class)
3210 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003211 break;
3212 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003213 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003214 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003215
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003216 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003217 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003218 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003219 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003220 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3221 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3222 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003223
3224 // See if a method overloads virtual methods in a base
3225 /// class without overriding any.
3226 if (!Record->isDependentType()) {
3227 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3228 MEnd = Record->method_end();
3229 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003230 if (!(*M)->isStatic())
3231 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003232 }
3233 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003234
3235 // Declare inherited constructors. We do this eagerly here because:
3236 // - The standard requires an eager diagnostic for conflicting inherited
3237 // constructors from different classes.
3238 // - The lazy declaration of the other implicit constructors is so as to not
3239 // waste space and performance on classes that are not meant to be
3240 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3241 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003242 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003243
Sean Hunteb88ae52011-05-23 21:07:59 +00003244 if (!Record->isDependentType())
3245 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003246}
3247
3248void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003249 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3250 ME = Record->method_end();
3251 MI != ME; ++MI) {
3252 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3253 switch (getSpecialMember(*MI)) {
3254 case CXXDefaultConstructor:
3255 CheckExplicitlyDefaultedDefaultConstructor(
3256 cast<CXXConstructorDecl>(*MI));
3257 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003258
Sean Huntcb45a0f2011-05-12 22:46:25 +00003259 case CXXDestructor:
3260 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3261 break;
3262
3263 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003264 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3265 break;
3266
Sean Huntcb45a0f2011-05-12 22:46:25 +00003267 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003268 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003269 break;
3270
Sean Hunt82713172011-05-25 23:16:36 +00003271 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003272 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003273 break;
3274
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003275 case CXXMoveAssignment:
3276 CheckExplicitlyDefaultedMoveAssignment(*MI);
3277 break;
3278
3279 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003280 llvm_unreachable("non-special member explicitly defaulted!");
3281 }
Sean Hunt001cad92011-05-10 00:49:42 +00003282 }
3283 }
3284
Sean Hunt001cad92011-05-10 00:49:42 +00003285}
3286
3287void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3288 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3289
3290 // Whether this was the first-declared instance of the constructor.
3291 // This affects whether we implicitly add an exception spec (and, eventually,
3292 // constexpr). It is also ill-formed to explicitly default a constructor such
3293 // that it would be deleted. (C++0x [decl.fct.def.default])
3294 bool First = CD == CD->getCanonicalDecl();
3295
Sean Hunt49634cf2011-05-13 06:10:58 +00003296 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003297 if (CD->getNumParams() != 0) {
3298 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3299 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003300 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003301 }
3302
3303 ImplicitExceptionSpecification Spec
3304 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3305 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003306 if (EPI.ExceptionSpecType == EST_Delayed) {
3307 // Exception specification depends on some deferred part of the class. We'll
3308 // try again when the class's definition has been fully processed.
3309 return;
3310 }
Sean Hunt001cad92011-05-10 00:49:42 +00003311 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3312 *ExceptionType = Context.getFunctionType(
3313 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3314
3315 if (CtorType->hasExceptionSpec()) {
3316 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003317 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003318 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003319 PDiag(),
3320 ExceptionType, SourceLocation(),
3321 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003322 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003323 }
3324 } else if (First) {
3325 // We set the declaration to have the computed exception spec here.
3326 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003327 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003328 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3329 }
Sean Huntca46d132011-05-12 03:51:48 +00003330
Sean Hunt49634cf2011-05-13 06:10:58 +00003331 if (HadError) {
3332 CD->setInvalidDecl();
3333 return;
3334 }
3335
Sean Huntca46d132011-05-12 03:51:48 +00003336 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003337 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003338 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003339 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003340 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003341 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003342 CD->setInvalidDecl();
3343 }
3344 }
3345}
3346
3347void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3348 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3349
3350 // Whether this was the first-declared instance of the constructor.
3351 bool First = CD == CD->getCanonicalDecl();
3352
3353 bool HadError = false;
3354 if (CD->getNumParams() != 1) {
3355 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3356 << CD->getSourceRange();
3357 HadError = true;
3358 }
3359
3360 ImplicitExceptionSpecification Spec(Context);
3361 bool Const;
3362 llvm::tie(Spec, Const) =
3363 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3364
3365 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3366 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3367 *ExceptionType = Context.getFunctionType(
3368 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3369
3370 // Check for parameter type matching.
3371 // This is a copy ctor so we know it's a cv-qualified reference to T.
3372 QualType ArgType = CtorType->getArgType(0);
3373 if (ArgType->getPointeeType().isVolatileQualified()) {
3374 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3375 HadError = true;
3376 }
3377 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3378 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3379 HadError = true;
3380 }
3381
3382 if (CtorType->hasExceptionSpec()) {
3383 if (CheckEquivalentExceptionSpec(
3384 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003385 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003386 PDiag(),
3387 ExceptionType, SourceLocation(),
3388 CtorType, CD->getLocation())) {
3389 HadError = true;
3390 }
3391 } else if (First) {
3392 // We set the declaration to have the computed exception spec here.
3393 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003394 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003395 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3396 }
3397
3398 if (HadError) {
3399 CD->setInvalidDecl();
3400 return;
3401 }
3402
3403 if (ShouldDeleteCopyConstructor(CD)) {
3404 if (First) {
3405 CD->setDeletedAsWritten();
3406 } else {
3407 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003408 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003409 CD->setInvalidDecl();
3410 }
Sean Huntca46d132011-05-12 03:51:48 +00003411 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003412}
Sean Hunt001cad92011-05-10 00:49:42 +00003413
Sean Hunt2b188082011-05-14 05:23:28 +00003414void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3415 assert(MD->isExplicitlyDefaulted());
3416
3417 // Whether this was the first-declared instance of the operator
3418 bool First = MD == MD->getCanonicalDecl();
3419
3420 bool HadError = false;
3421 if (MD->getNumParams() != 1) {
3422 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3423 << MD->getSourceRange();
3424 HadError = true;
3425 }
3426
3427 QualType ReturnType =
3428 MD->getType()->getAs<FunctionType>()->getResultType();
3429 if (!ReturnType->isLValueReferenceType() ||
3430 !Context.hasSameType(
3431 Context.getCanonicalType(ReturnType->getPointeeType()),
3432 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3433 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3434 HadError = true;
3435 }
3436
3437 ImplicitExceptionSpecification Spec(Context);
3438 bool Const;
3439 llvm::tie(Spec, Const) =
3440 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3441
3442 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3443 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3444 *ExceptionType = Context.getFunctionType(
3445 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3446
Sean Hunt2b188082011-05-14 05:23:28 +00003447 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003448 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003449 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003450 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003451 } else {
3452 if (ArgType->getPointeeType().isVolatileQualified()) {
3453 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3454 HadError = true;
3455 }
3456 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3457 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3458 HadError = true;
3459 }
Sean Hunt2b188082011-05-14 05:23:28 +00003460 }
Sean Huntbe631222011-05-17 20:44:43 +00003461
Sean Hunt2b188082011-05-14 05:23:28 +00003462 if (OperType->getTypeQuals()) {
3463 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3464 HadError = true;
3465 }
3466
3467 if (OperType->hasExceptionSpec()) {
3468 if (CheckEquivalentExceptionSpec(
3469 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003470 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003471 PDiag(),
3472 ExceptionType, SourceLocation(),
3473 OperType, MD->getLocation())) {
3474 HadError = true;
3475 }
3476 } else if (First) {
3477 // We set the declaration to have the computed exception spec here.
3478 // We duplicate the one parameter type.
3479 EPI.RefQualifier = OperType->getRefQualifier();
3480 EPI.ExtInfo = OperType->getExtInfo();
3481 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3482 }
3483
3484 if (HadError) {
3485 MD->setInvalidDecl();
3486 return;
3487 }
3488
3489 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3490 if (First) {
3491 MD->setDeletedAsWritten();
3492 } else {
3493 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003494 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003495 MD->setInvalidDecl();
3496 }
3497 }
3498}
3499
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003500void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3501 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3502
3503 // Whether this was the first-declared instance of the constructor.
3504 bool First = CD == CD->getCanonicalDecl();
3505
3506 bool HadError = false;
3507 if (CD->getNumParams() != 1) {
3508 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3509 << CD->getSourceRange();
3510 HadError = true;
3511 }
3512
3513 ImplicitExceptionSpecification Spec(
3514 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3515
3516 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3517 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3518 *ExceptionType = Context.getFunctionType(
3519 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3520
3521 // Check for parameter type matching.
3522 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3523 QualType ArgType = CtorType->getArgType(0);
3524 if (ArgType->getPointeeType().isVolatileQualified()) {
3525 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3526 HadError = true;
3527 }
3528 if (ArgType->getPointeeType().isConstQualified()) {
3529 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3530 HadError = true;
3531 }
3532
3533 if (CtorType->hasExceptionSpec()) {
3534 if (CheckEquivalentExceptionSpec(
3535 PDiag(diag::err_incorrect_defaulted_exception_spec)
3536 << CXXMoveConstructor,
3537 PDiag(),
3538 ExceptionType, SourceLocation(),
3539 CtorType, CD->getLocation())) {
3540 HadError = true;
3541 }
3542 } else if (First) {
3543 // We set the declaration to have the computed exception spec here.
3544 // We duplicate the one parameter type.
3545 EPI.ExtInfo = CtorType->getExtInfo();
3546 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3547 }
3548
3549 if (HadError) {
3550 CD->setInvalidDecl();
3551 return;
3552 }
3553
3554 if (ShouldDeleteMoveConstructor(CD)) {
3555 if (First) {
3556 CD->setDeletedAsWritten();
3557 } else {
3558 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3559 << CXXMoveConstructor;
3560 CD->setInvalidDecl();
3561 }
3562 }
3563}
3564
3565void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3566 assert(MD->isExplicitlyDefaulted());
3567
3568 // Whether this was the first-declared instance of the operator
3569 bool First = MD == MD->getCanonicalDecl();
3570
3571 bool HadError = false;
3572 if (MD->getNumParams() != 1) {
3573 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3574 << MD->getSourceRange();
3575 HadError = true;
3576 }
3577
3578 QualType ReturnType =
3579 MD->getType()->getAs<FunctionType>()->getResultType();
3580 if (!ReturnType->isLValueReferenceType() ||
3581 !Context.hasSameType(
3582 Context.getCanonicalType(ReturnType->getPointeeType()),
3583 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3584 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3585 HadError = true;
3586 }
3587
3588 ImplicitExceptionSpecification Spec(
3589 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3590
3591 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3592 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3593 *ExceptionType = Context.getFunctionType(
3594 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3595
3596 QualType ArgType = OperType->getArgType(0);
3597 if (!ArgType->isRValueReferenceType()) {
3598 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3599 HadError = true;
3600 } else {
3601 if (ArgType->getPointeeType().isVolatileQualified()) {
3602 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3603 HadError = true;
3604 }
3605 if (ArgType->getPointeeType().isConstQualified()) {
3606 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3607 HadError = true;
3608 }
3609 }
3610
3611 if (OperType->getTypeQuals()) {
3612 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3613 HadError = true;
3614 }
3615
3616 if (OperType->hasExceptionSpec()) {
3617 if (CheckEquivalentExceptionSpec(
3618 PDiag(diag::err_incorrect_defaulted_exception_spec)
3619 << CXXMoveAssignment,
3620 PDiag(),
3621 ExceptionType, SourceLocation(),
3622 OperType, MD->getLocation())) {
3623 HadError = true;
3624 }
3625 } else if (First) {
3626 // We set the declaration to have the computed exception spec here.
3627 // We duplicate the one parameter type.
3628 EPI.RefQualifier = OperType->getRefQualifier();
3629 EPI.ExtInfo = OperType->getExtInfo();
3630 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3631 }
3632
3633 if (HadError) {
3634 MD->setInvalidDecl();
3635 return;
3636 }
3637
3638 if (ShouldDeleteMoveAssignmentOperator(MD)) {
3639 if (First) {
3640 MD->setDeletedAsWritten();
3641 } else {
3642 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3643 << CXXMoveAssignment;
3644 MD->setInvalidDecl();
3645 }
3646 }
3647}
3648
Sean Huntcb45a0f2011-05-12 22:46:25 +00003649void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3650 assert(DD->isExplicitlyDefaulted());
3651
3652 // Whether this was the first-declared instance of the destructor.
3653 bool First = DD == DD->getCanonicalDecl();
3654
3655 ImplicitExceptionSpecification Spec
3656 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3657 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3658 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3659 *ExceptionType = Context.getFunctionType(
3660 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3661
3662 if (DtorType->hasExceptionSpec()) {
3663 if (CheckEquivalentExceptionSpec(
3664 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003665 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003666 PDiag(),
3667 ExceptionType, SourceLocation(),
3668 DtorType, DD->getLocation())) {
3669 DD->setInvalidDecl();
3670 return;
3671 }
3672 } else if (First) {
3673 // We set the declaration to have the computed exception spec here.
3674 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003675 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003676 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3677 }
3678
3679 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003680 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003681 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003682 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003683 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003684 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003685 DD->setInvalidDecl();
3686 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003687 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003688}
3689
Sean Huntcdee3fe2011-05-11 22:34:38 +00003690bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3691 CXXRecordDecl *RD = CD->getParent();
3692 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003693 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003694 return false;
3695
Sean Hunt71a682f2011-05-18 03:41:58 +00003696 SourceLocation Loc = CD->getLocation();
3697
Sean Huntcdee3fe2011-05-11 22:34:38 +00003698 // Do access control from the constructor
3699 ContextRAII CtorContext(*this, CD);
3700
3701 bool Union = RD->isUnion();
3702 bool AllConst = true;
3703
Sean Huntcdee3fe2011-05-11 22:34:38 +00003704 // We do this because we should never actually use an anonymous
3705 // union's constructor.
3706 if (Union && RD->isAnonymousStructOrUnion())
3707 return false;
3708
3709 // FIXME: We should put some diagnostic logic right into this function.
3710
3711 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003712 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003713
3714 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3715 BE = RD->bases_end();
3716 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003717 // We'll handle this one later
3718 if (BI->isVirtual())
3719 continue;
3720
Sean Huntcdee3fe2011-05-11 22:34:38 +00003721 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3722 assert(BaseDecl && "base isn't a CXXRecordDecl");
3723
3724 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003725 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003726 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3727 if (BaseDtor->isDeleted())
3728 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003729 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003730 AR_accessible)
3731 return true;
3732
Sean Huntcdee3fe2011-05-11 22:34:38 +00003733 // -- any [direct base class either] has no default constructor or
3734 // overload resolution as applied to [its] default constructor
3735 // results in an ambiguity or in a function that is deleted or
3736 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003737 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3738 if (!BaseDefault || BaseDefault->isDeleted())
3739 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003740
Sean Huntb320e0c2011-06-10 03:50:41 +00003741 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3742 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003743 return true;
3744 }
3745
3746 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3747 BE = RD->vbases_end();
3748 BI != BE; ++BI) {
3749 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3750 assert(BaseDecl && "base isn't a CXXRecordDecl");
3751
3752 // -- any [virtual base class] has a type with a destructor that is
3753 // delete or inaccessible from the defaulted default constructor
3754 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3755 if (BaseDtor->isDeleted())
3756 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003757 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003758 AR_accessible)
3759 return true;
3760
3761 // -- any [virtual base class either] has no default constructor or
3762 // overload resolution as applied to [its] default constructor
3763 // results in an ambiguity or in a function that is deleted or
3764 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003765 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3766 if (!BaseDefault || BaseDefault->isDeleted())
3767 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003768
Sean Huntb320e0c2011-06-10 03:50:41 +00003769 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3770 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003771 return true;
3772 }
3773
3774 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3775 FE = RD->field_end();
3776 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003777 if (FI->isInvalidDecl())
3778 continue;
3779
Sean Huntcdee3fe2011-05-11 22:34:38 +00003780 QualType FieldType = Context.getBaseElementType(FI->getType());
3781 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003782
Sean Huntcdee3fe2011-05-11 22:34:38 +00003783 // -- any non-static data member with no brace-or-equal-initializer is of
3784 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003785 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003786 return true;
3787
3788 // -- X is a union and all its variant members are of const-qualified type
3789 // (or array thereof)
3790 if (Union && !FieldType.isConstQualified())
3791 AllConst = false;
3792
3793 if (FieldRecord) {
3794 // -- X is a union-like class that has a variant member with a non-trivial
3795 // default constructor
3796 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3797 return true;
3798
3799 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3800 if (FieldDtor->isDeleted())
3801 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003802 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003803 AR_accessible)
3804 return true;
3805
3806 // -- any non-variant non-static data member of const-qualified type (or
3807 // array thereof) with no brace-or-equal-initializer does not have a
3808 // user-provided default constructor
3809 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003810 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003811 !FieldRecord->hasUserProvidedDefaultConstructor())
3812 return true;
3813
3814 if (!Union && FieldRecord->isUnion() &&
3815 FieldRecord->isAnonymousStructOrUnion()) {
3816 // We're okay to reuse AllConst here since we only care about the
3817 // value otherwise if we're in a union.
3818 AllConst = true;
3819
3820 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3821 UE = FieldRecord->field_end();
3822 UI != UE; ++UI) {
3823 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3824 CXXRecordDecl *UnionFieldRecord =
3825 UnionFieldType->getAsCXXRecordDecl();
3826
3827 if (!UnionFieldType.isConstQualified())
3828 AllConst = false;
3829
3830 if (UnionFieldRecord &&
3831 !UnionFieldRecord->hasTrivialDefaultConstructor())
3832 return true;
3833 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003834
Sean Huntcdee3fe2011-05-11 22:34:38 +00003835 if (AllConst)
3836 return true;
3837
3838 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003839 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003840 continue;
3841 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003842
Richard Smith7a614d82011-06-11 17:19:42 +00003843 // -- any non-static data member with no brace-or-equal-initializer has
3844 // class type M (or array thereof) and either M has no default
3845 // constructor or overload resolution as applied to M's default
3846 // constructor results in an ambiguity or in a function that is deleted
3847 // or inaccessible from the defaulted default constructor.
3848 if (!FI->hasInClassInitializer()) {
3849 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3850 if (!FieldDefault || FieldDefault->isDeleted())
3851 return true;
3852 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3853 PDiag()) != AR_accessible)
3854 return true;
3855 }
3856 } else if (!Union && FieldType.isConstQualified() &&
3857 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003858 // -- any non-variant non-static data member of const-qualified type (or
3859 // array thereof) with no brace-or-equal-initializer does not have a
3860 // user-provided default constructor
3861 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003862 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003863 }
3864
3865 if (Union && AllConst)
3866 return true;
3867
3868 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003869}
3870
Sean Hunt49634cf2011-05-13 06:10:58 +00003871bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003872 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003873 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003874 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt49634cf2011-05-13 06:10:58 +00003875 return false;
3876
Sean Hunt71a682f2011-05-18 03:41:58 +00003877 SourceLocation Loc = CD->getLocation();
3878
Sean Hunt49634cf2011-05-13 06:10:58 +00003879 // Do access control from the constructor
3880 ContextRAII CtorContext(*this, CD);
3881
Sean Huntc530d172011-06-10 04:44:37 +00003882 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003883
Sean Hunt2b188082011-05-14 05:23:28 +00003884 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3885 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003886 unsigned ArgQuals =
3887 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3888 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003889
3890 // We do this because we should never actually use an anonymous
3891 // union's constructor.
3892 if (Union && RD->isAnonymousStructOrUnion())
3893 return false;
3894
3895 // FIXME: We should put some diagnostic logic right into this function.
3896
3897 // C++0x [class.copy]/11
3898 // A defaulted [copy] constructor for class X is defined as delete if X has:
3899
3900 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3901 BE = RD->bases_end();
3902 BI != BE; ++BI) {
3903 // We'll handle this one later
3904 if (BI->isVirtual())
3905 continue;
3906
3907 QualType BaseType = BI->getType();
3908 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3909 assert(BaseDecl && "base isn't a CXXRecordDecl");
3910
3911 // -- any [direct base class] of a type with a destructor that is deleted or
3912 // inaccessible from the defaulted constructor
3913 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3914 if (BaseDtor->isDeleted())
3915 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003916 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003917 AR_accessible)
3918 return true;
3919
3920 // -- a [direct base class] B that cannot be [copied] because overload
3921 // resolution, as applied to B's [copy] constructor, results in an
3922 // ambiguity or a function that is deleted or inaccessible from the
3923 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003924 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003925 if (!BaseCtor || BaseCtor->isDeleted())
3926 return true;
3927 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3928 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003929 return true;
3930 }
3931
3932 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3933 BE = RD->vbases_end();
3934 BI != BE; ++BI) {
3935 QualType BaseType = BI->getType();
3936 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3937 assert(BaseDecl && "base isn't a CXXRecordDecl");
3938
Sean Huntb320e0c2011-06-10 03:50:41 +00003939 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003940 // inaccessible from the defaulted constructor
3941 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3942 if (BaseDtor->isDeleted())
3943 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003944 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003945 AR_accessible)
3946 return true;
3947
3948 // -- a [virtual base class] B that cannot be [copied] because overload
3949 // resolution, as applied to B's [copy] constructor, results in an
3950 // ambiguity or a function that is deleted or inaccessible from the
3951 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003952 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003953 if (!BaseCtor || BaseCtor->isDeleted())
3954 return true;
3955 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3956 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003957 return true;
3958 }
3959
3960 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3961 FE = RD->field_end();
3962 FI != FE; ++FI) {
3963 QualType FieldType = Context.getBaseElementType(FI->getType());
3964
3965 // -- for a copy constructor, a non-static data member of rvalue reference
3966 // type
3967 if (FieldType->isRValueReferenceType())
3968 return true;
3969
3970 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3971
3972 if (FieldRecord) {
3973 // This is an anonymous union
3974 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3975 // Anonymous unions inside unions do not variant members create
3976 if (!Union) {
3977 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3978 UE = FieldRecord->field_end();
3979 UI != UE; ++UI) {
3980 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3981 CXXRecordDecl *UnionFieldRecord =
3982 UnionFieldType->getAsCXXRecordDecl();
3983
3984 // -- a variant member with a non-trivial [copy] constructor and X
3985 // is a union-like class
3986 if (UnionFieldRecord &&
3987 !UnionFieldRecord->hasTrivialCopyConstructor())
3988 return true;
3989 }
3990 }
3991
3992 // Don't try to initalize an anonymous union
3993 continue;
3994 } else {
3995 // -- a variant member with a non-trivial [copy] constructor and X is a
3996 // union-like class
3997 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3998 return true;
3999
4000 // -- any [non-static data member] of a type with a destructor that is
4001 // deleted or inaccessible from the defaulted constructor
4002 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4003 if (FieldDtor->isDeleted())
4004 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004005 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00004006 AR_accessible)
4007 return true;
4008 }
Sean Huntc530d172011-06-10 04:44:37 +00004009
4010 // -- a [non-static data member of class type (or array thereof)] B that
4011 // cannot be [copied] because overload resolution, as applied to B's
4012 // [copy] constructor, results in an ambiguity or a function that is
4013 // deleted or inaccessible from the defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00004014 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
4015 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00004016 if (!FieldCtor || FieldCtor->isDeleted())
4017 return true;
4018 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4019 PDiag()) != AR_accessible)
4020 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00004021 }
Sean Hunt49634cf2011-05-13 06:10:58 +00004022 }
4023
4024 return false;
4025}
4026
Sean Hunt7f410192011-05-14 05:23:24 +00004027bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4028 CXXRecordDecl *RD = MD->getParent();
4029 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004030 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004031 return false;
4032
Sean Hunt71a682f2011-05-18 03:41:58 +00004033 SourceLocation Loc = MD->getLocation();
4034
Sean Hunt7f410192011-05-14 05:23:24 +00004035 // Do access control from the constructor
4036 ContextRAII MethodContext(*this, MD);
4037
4038 bool Union = RD->isUnion();
4039
Sean Hunt661c67a2011-06-21 23:42:56 +00004040 unsigned ArgQuals =
4041 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4042 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004043
4044 // We do this because we should never actually use an anonymous
4045 // union's constructor.
4046 if (Union && RD->isAnonymousStructOrUnion())
4047 return false;
4048
Sean Hunt7f410192011-05-14 05:23:24 +00004049 // FIXME: We should put some diagnostic logic right into this function.
4050
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004051 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004052 // A defaulted [copy] assignment operator for class X is defined as deleted
4053 // if X has:
4054
4055 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4056 BE = RD->bases_end();
4057 BI != BE; ++BI) {
4058 // We'll handle this one later
4059 if (BI->isVirtual())
4060 continue;
4061
4062 QualType BaseType = BI->getType();
4063 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4064 assert(BaseDecl && "base isn't a CXXRecordDecl");
4065
4066 // -- a [direct base class] B that cannot be [copied] because overload
4067 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004068 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004069 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004070 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4071 0);
4072 if (!CopyOper || CopyOper->isDeleted())
4073 return true;
4074 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004075 return true;
4076 }
4077
4078 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4079 BE = RD->vbases_end();
4080 BI != BE; ++BI) {
4081 QualType BaseType = BI->getType();
4082 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4083 assert(BaseDecl && "base isn't a CXXRecordDecl");
4084
Sean Hunt7f410192011-05-14 05:23:24 +00004085 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004086 // resolution, as applied to B's [copy] assignment operator, results in
4087 // an ambiguity or a function that is deleted or inaccessible from the
4088 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004089 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4090 0);
4091 if (!CopyOper || CopyOper->isDeleted())
4092 return true;
4093 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004094 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004095 }
4096
4097 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4098 FE = RD->field_end();
4099 FI != FE; ++FI) {
4100 QualType FieldType = Context.getBaseElementType(FI->getType());
4101
4102 // -- a non-static data member of reference type
4103 if (FieldType->isReferenceType())
4104 return true;
4105
4106 // -- a non-static data member of const non-class type (or array thereof)
4107 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4108 return true;
4109
4110 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4111
4112 if (FieldRecord) {
4113 // This is an anonymous union
4114 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4115 // Anonymous unions inside unions do not variant members create
4116 if (!Union) {
4117 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4118 UE = FieldRecord->field_end();
4119 UI != UE; ++UI) {
4120 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4121 CXXRecordDecl *UnionFieldRecord =
4122 UnionFieldType->getAsCXXRecordDecl();
4123
4124 // -- a variant member with a non-trivial [copy] assignment operator
4125 // and X is a union-like class
4126 if (UnionFieldRecord &&
4127 !UnionFieldRecord->hasTrivialCopyAssignment())
4128 return true;
4129 }
4130 }
4131
4132 // Don't try to initalize an anonymous union
4133 continue;
4134 // -- a variant member with a non-trivial [copy] assignment operator
4135 // and X is a union-like class
4136 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4137 return true;
4138 }
Sean Hunt7f410192011-05-14 05:23:24 +00004139
Sean Hunt661c67a2011-06-21 23:42:56 +00004140 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4141 false, 0);
4142 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004143 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004144 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004145 return true;
4146 }
4147 }
4148
4149 return false;
4150}
4151
4152bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4153 CXXRecordDecl *RD = CD->getParent();
4154 assert(!RD->isDependentType() && "do deletion after instantiation");
4155 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4156 return false;
4157
4158 SourceLocation Loc = CD->getLocation();
4159
4160 // Do access control from the constructor
4161 ContextRAII CtorContext(*this, CD);
4162
4163 bool Union = RD->isUnion();
4164
4165 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4166 "copy assignment arg has no pointee type");
4167
4168 // We do this because we should never actually use an anonymous
4169 // union's constructor.
4170 if (Union && RD->isAnonymousStructOrUnion())
4171 return false;
4172
4173 // C++0x [class.copy]/11
4174 // A defaulted [move] constructor for class X is defined as deleted
4175 // if X has:
4176
4177 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4178 BE = RD->bases_end();
4179 BI != BE; ++BI) {
4180 // We'll handle this one later
4181 if (BI->isVirtual())
4182 continue;
4183
4184 QualType BaseType = BI->getType();
4185 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4186 assert(BaseDecl && "base isn't a CXXRecordDecl");
4187
4188 // -- any [direct base class] of a type with a destructor that is deleted or
4189 // inaccessible from the defaulted constructor
4190 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4191 if (BaseDtor->isDeleted())
4192 return true;
4193 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4194 AR_accessible)
4195 return true;
4196
4197 // -- a [direct base class] B that cannot be [moved] because overload
4198 // resolution, as applied to B's [move] constructor, results in an
4199 // ambiguity or a function that is deleted or inaccessible from the
4200 // defaulted constructor
4201 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4202 if (!BaseCtor || BaseCtor->isDeleted())
4203 return true;
4204 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4205 AR_accessible)
4206 return true;
4207
4208 // -- for a move constructor, a [direct base class] with a type that
4209 // does not have a move constructor and is not trivially copyable.
4210 // If the field isn't a record, it's always trivially copyable.
4211 // A moving constructor could be a copy constructor instead.
4212 if (!BaseCtor->isMoveConstructor() &&
4213 !BaseDecl->isTriviallyCopyable())
4214 return true;
4215 }
4216
4217 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4218 BE = RD->vbases_end();
4219 BI != BE; ++BI) {
4220 QualType BaseType = BI->getType();
4221 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4222 assert(BaseDecl && "base isn't a CXXRecordDecl");
4223
4224 // -- any [virtual base class] of a type with a destructor that is deleted
4225 // or inaccessible from the defaulted constructor
4226 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4227 if (BaseDtor->isDeleted())
4228 return true;
4229 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4230 AR_accessible)
4231 return true;
4232
4233 // -- a [virtual base class] B that cannot be [moved] because overload
4234 // resolution, as applied to B's [move] constructor, results in an
4235 // ambiguity or a function that is deleted or inaccessible from the
4236 // defaulted constructor
4237 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4238 if (!BaseCtor || BaseCtor->isDeleted())
4239 return true;
4240 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4241 AR_accessible)
4242 return true;
4243
4244 // -- for a move constructor, a [virtual base class] with a type that
4245 // does not have a move constructor and is not trivially copyable.
4246 // If the field isn't a record, it's always trivially copyable.
4247 // A moving constructor could be a copy constructor instead.
4248 if (!BaseCtor->isMoveConstructor() &&
4249 !BaseDecl->isTriviallyCopyable())
4250 return true;
4251 }
4252
4253 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4254 FE = RD->field_end();
4255 FI != FE; ++FI) {
4256 QualType FieldType = Context.getBaseElementType(FI->getType());
4257
4258 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4259 // This is an anonymous union
4260 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4261 // Anonymous unions inside unions do not variant members create
4262 if (!Union) {
4263 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4264 UE = FieldRecord->field_end();
4265 UI != UE; ++UI) {
4266 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4267 CXXRecordDecl *UnionFieldRecord =
4268 UnionFieldType->getAsCXXRecordDecl();
4269
4270 // -- a variant member with a non-trivial [move] constructor and X
4271 // is a union-like class
4272 if (UnionFieldRecord &&
4273 !UnionFieldRecord->hasTrivialMoveConstructor())
4274 return true;
4275 }
4276 }
4277
4278 // Don't try to initalize an anonymous union
4279 continue;
4280 } else {
4281 // -- a variant member with a non-trivial [move] constructor and X is a
4282 // union-like class
4283 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4284 return true;
4285
4286 // -- any [non-static data member] of a type with a destructor that is
4287 // deleted or inaccessible from the defaulted constructor
4288 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4289 if (FieldDtor->isDeleted())
4290 return true;
4291 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4292 AR_accessible)
4293 return true;
4294 }
4295
4296 // -- a [non-static data member of class type (or array thereof)] B that
4297 // cannot be [moved] because overload resolution, as applied to B's
4298 // [move] constructor, results in an ambiguity or a function that is
4299 // deleted or inaccessible from the defaulted constructor
4300 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4301 if (!FieldCtor || FieldCtor->isDeleted())
4302 return true;
4303 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4304 PDiag()) != AR_accessible)
4305 return true;
4306
4307 // -- for a move constructor, a [non-static data member] with a type that
4308 // does not have a move constructor and is not trivially copyable.
4309 // If the field isn't a record, it's always trivially copyable.
4310 // A moving constructor could be a copy constructor instead.
4311 if (!FieldCtor->isMoveConstructor() &&
4312 !FieldRecord->isTriviallyCopyable())
4313 return true;
4314 }
4315 }
4316
4317 return false;
4318}
4319
4320bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4321 CXXRecordDecl *RD = MD->getParent();
4322 assert(!RD->isDependentType() && "do deletion after instantiation");
4323 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4324 return false;
4325
4326 SourceLocation Loc = MD->getLocation();
4327
4328 // Do access control from the constructor
4329 ContextRAII MethodContext(*this, MD);
4330
4331 bool Union = RD->isUnion();
4332
4333 // We do this because we should never actually use an anonymous
4334 // union's constructor.
4335 if (Union && RD->isAnonymousStructOrUnion())
4336 return false;
4337
4338 // C++0x [class.copy]/20
4339 // A defaulted [move] assignment operator for class X is defined as deleted
4340 // if X has:
4341
4342 // -- for the move constructor, [...] any direct or indirect virtual base
4343 // class.
4344 if (RD->getNumVBases() != 0)
4345 return true;
4346
4347 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4348 BE = RD->bases_end();
4349 BI != BE; ++BI) {
4350
4351 QualType BaseType = BI->getType();
4352 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4353 assert(BaseDecl && "base isn't a CXXRecordDecl");
4354
4355 // -- a [direct base class] B that cannot be [moved] because overload
4356 // resolution, as applied to B's [move] assignment operator, results in
4357 // an ambiguity or a function that is deleted or inaccessible from the
4358 // assignment operator
4359 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4360 if (!MoveOper || MoveOper->isDeleted())
4361 return true;
4362 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4363 return true;
4364
4365 // -- for the move assignment operator, a [direct base class] with a type
4366 // that does not have a move assignment operator and is not trivially
4367 // copyable.
4368 if (!MoveOper->isMoveAssignmentOperator() &&
4369 !BaseDecl->isTriviallyCopyable())
4370 return true;
4371 }
4372
4373 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4374 FE = RD->field_end();
4375 FI != FE; ++FI) {
4376 QualType FieldType = Context.getBaseElementType(FI->getType());
4377
4378 // -- a non-static data member of reference type
4379 if (FieldType->isReferenceType())
4380 return true;
4381
4382 // -- a non-static data member of const non-class type (or array thereof)
4383 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4384 return true;
4385
4386 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4387
4388 if (FieldRecord) {
4389 // This is an anonymous union
4390 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4391 // Anonymous unions inside unions do not variant members create
4392 if (!Union) {
4393 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4394 UE = FieldRecord->field_end();
4395 UI != UE; ++UI) {
4396 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4397 CXXRecordDecl *UnionFieldRecord =
4398 UnionFieldType->getAsCXXRecordDecl();
4399
4400 // -- a variant member with a non-trivial [move] assignment operator
4401 // and X is a union-like class
4402 if (UnionFieldRecord &&
4403 !UnionFieldRecord->hasTrivialMoveAssignment())
4404 return true;
4405 }
4406 }
4407
4408 // Don't try to initalize an anonymous union
4409 continue;
4410 // -- a variant member with a non-trivial [move] assignment operator
4411 // and X is a union-like class
4412 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4413 return true;
4414 }
4415
4416 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4417 if (!MoveOper || MoveOper->isDeleted())
4418 return true;
4419 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4420 return true;
4421
4422 // -- for the move assignment operator, a [non-static data member] with a
4423 // type that does not have a move assignment operator and is not
4424 // trivially copyable.
4425 if (!MoveOper->isMoveAssignmentOperator() &&
4426 !FieldRecord->isTriviallyCopyable())
4427 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004428 }
Sean Hunt7f410192011-05-14 05:23:24 +00004429 }
4430
4431 return false;
4432}
4433
Sean Huntcb45a0f2011-05-12 22:46:25 +00004434bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4435 CXXRecordDecl *RD = DD->getParent();
4436 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004437 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004438 return false;
4439
Sean Hunt71a682f2011-05-18 03:41:58 +00004440 SourceLocation Loc = DD->getLocation();
4441
Sean Huntcb45a0f2011-05-12 22:46:25 +00004442 // Do access control from the destructor
4443 ContextRAII CtorContext(*this, DD);
4444
4445 bool Union = RD->isUnion();
4446
Sean Hunt49634cf2011-05-13 06:10:58 +00004447 // We do this because we should never actually use an anonymous
4448 // union's destructor.
4449 if (Union && RD->isAnonymousStructOrUnion())
4450 return false;
4451
Sean Huntcb45a0f2011-05-12 22:46:25 +00004452 // C++0x [class.dtor]p5
4453 // A defaulted destructor for a class X is defined as deleted if:
4454 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4455 BE = RD->bases_end();
4456 BI != BE; ++BI) {
4457 // We'll handle this one later
4458 if (BI->isVirtual())
4459 continue;
4460
4461 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4462 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4463 assert(BaseDtor && "base has no destructor");
4464
4465 // -- any direct or virtual base class has a deleted destructor or
4466 // a destructor that is inaccessible from the defaulted destructor
4467 if (BaseDtor->isDeleted())
4468 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004469 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004470 AR_accessible)
4471 return true;
4472 }
4473
4474 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4475 BE = RD->vbases_end();
4476 BI != BE; ++BI) {
4477 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4478 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4479 assert(BaseDtor && "base has no destructor");
4480
4481 // -- any direct or virtual base class has a deleted destructor or
4482 // a destructor that is inaccessible from the defaulted destructor
4483 if (BaseDtor->isDeleted())
4484 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004485 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004486 AR_accessible)
4487 return true;
4488 }
4489
4490 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4491 FE = RD->field_end();
4492 FI != FE; ++FI) {
4493 QualType FieldType = Context.getBaseElementType(FI->getType());
4494 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4495 if (FieldRecord) {
4496 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4497 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4498 UE = FieldRecord->field_end();
4499 UI != UE; ++UI) {
4500 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4501 CXXRecordDecl *UnionFieldRecord =
4502 UnionFieldType->getAsCXXRecordDecl();
4503
4504 // -- X is a union-like class that has a variant member with a non-
4505 // trivial destructor.
4506 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4507 return true;
4508 }
4509 // Technically we are supposed to do this next check unconditionally.
4510 // But that makes absolutely no sense.
4511 } else {
4512 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4513
4514 // -- any of the non-static data members has class type M (or array
4515 // thereof) and M has a deleted destructor or a destructor that is
4516 // inaccessible from the defaulted destructor
4517 if (FieldDtor->isDeleted())
4518 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004519 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004520 AR_accessible)
4521 return true;
4522
4523 // -- X is a union-like class that has a variant member with a non-
4524 // trivial destructor.
4525 if (Union && !FieldDtor->isTrivial())
4526 return true;
4527 }
4528 }
4529 }
4530
4531 if (DD->isVirtual()) {
4532 FunctionDecl *OperatorDelete = 0;
4533 DeclarationName Name =
4534 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004535 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004536 false))
4537 return true;
4538 }
4539
4540
4541 return false;
4542}
4543
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004544/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004545namespace {
4546 struct FindHiddenVirtualMethodData {
4547 Sema *S;
4548 CXXMethodDecl *Method;
4549 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004550 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004551 };
4552}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004553
4554/// \brief Member lookup function that determines whether a given C++
4555/// method overloads virtual methods in a base class without overriding any,
4556/// to be used with CXXRecordDecl::lookupInBases().
4557static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4558 CXXBasePath &Path,
4559 void *UserData) {
4560 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4561
4562 FindHiddenVirtualMethodData &Data
4563 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4564
4565 DeclarationName Name = Data.Method->getDeclName();
4566 assert(Name.getNameKind() == DeclarationName::Identifier);
4567
4568 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004569 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004570 for (Path.Decls = BaseRecord->lookup(Name);
4571 Path.Decls.first != Path.Decls.second;
4572 ++Path.Decls.first) {
4573 NamedDecl *D = *Path.Decls.first;
4574 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004575 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004576 foundSameNameMethod = true;
4577 // Interested only in hidden virtual methods.
4578 if (!MD->isVirtual())
4579 continue;
4580 // If the method we are checking overrides a method from its base
4581 // don't warn about the other overloaded methods.
4582 if (!Data.S->IsOverload(Data.Method, MD, false))
4583 return true;
4584 // Collect the overload only if its hidden.
4585 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4586 overloadedMethods.push_back(MD);
4587 }
4588 }
4589
4590 if (foundSameNameMethod)
4591 Data.OverloadedMethods.append(overloadedMethods.begin(),
4592 overloadedMethods.end());
4593 return foundSameNameMethod;
4594}
4595
4596/// \brief See if a method overloads virtual methods in a base class without
4597/// overriding any.
4598void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4599 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004600 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004601 return;
4602 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4603 return;
4604
4605 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4606 /*bool RecordPaths=*/false,
4607 /*bool DetectVirtual=*/false);
4608 FindHiddenVirtualMethodData Data;
4609 Data.Method = MD;
4610 Data.S = this;
4611
4612 // Keep the base methods that were overriden or introduced in the subclass
4613 // by 'using' in a set. A base method not in this set is hidden.
4614 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4615 res.first != res.second; ++res.first) {
4616 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4617 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4618 E = MD->end_overridden_methods();
4619 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004620 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004621 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4622 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004623 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004624 }
4625
4626 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4627 !Data.OverloadedMethods.empty()) {
4628 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4629 << MD << (Data.OverloadedMethods.size() > 1);
4630
4631 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4632 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4633 Diag(overloadedMD->getLocation(),
4634 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4635 }
4636 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004637}
4638
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004639void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004640 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004641 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004642 SourceLocation RBrac,
4643 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004644 if (!TagDecl)
4645 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004646
Douglas Gregor42af25f2009-05-11 19:58:34 +00004647 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004648
David Blaikie77b6de02011-09-22 02:58:26 +00004649 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004650 // strict aliasing violation!
4651 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004652 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004653
Douglas Gregor23c94db2010-07-02 17:43:08 +00004654 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004655 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004656}
4657
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004658/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4659/// special functions, such as the default constructor, copy
4660/// constructor, or destructor, to the given C++ class (C++
4661/// [special]p1). This routine can only be executed just before the
4662/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004663void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004664 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004665 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004666
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004667 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004668 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004669
Douglas Gregora376d102010-07-02 21:50:04 +00004670 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4671 ++ASTContext::NumImplicitCopyAssignmentOperators;
4672
4673 // If we have a dynamic class, then the copy assignment operator may be
4674 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4675 // it shows up in the right place in the vtable and that we diagnose
4676 // problems with the implicit exception specification.
4677 if (ClassDecl->isDynamicClass())
4678 DeclareImplicitCopyAssignment(ClassDecl);
4679 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004680
Douglas Gregor4923aa22010-07-02 20:37:36 +00004681 if (!ClassDecl->hasUserDeclaredDestructor()) {
4682 ++ASTContext::NumImplicitDestructors;
4683
4684 // If we have a dynamic class, then the destructor may be virtual, so we
4685 // have to declare the destructor immediately. This ensures that, e.g., it
4686 // shows up in the right place in the vtable and that we diagnose problems
4687 // with the implicit exception specification.
4688 if (ClassDecl->isDynamicClass())
4689 DeclareImplicitDestructor(ClassDecl);
4690 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004691}
4692
Francois Pichet8387e2a2011-04-22 22:18:13 +00004693void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4694 if (!D)
4695 return;
4696
4697 int NumParamList = D->getNumTemplateParameterLists();
4698 for (int i = 0; i < NumParamList; i++) {
4699 TemplateParameterList* Params = D->getTemplateParameterList(i);
4700 for (TemplateParameterList::iterator Param = Params->begin(),
4701 ParamEnd = Params->end();
4702 Param != ParamEnd; ++Param) {
4703 NamedDecl *Named = cast<NamedDecl>(*Param);
4704 if (Named->getDeclName()) {
4705 S->AddDecl(Named);
4706 IdResolver.AddDecl(Named);
4707 }
4708 }
4709 }
4710}
4711
John McCalld226f652010-08-21 09:40:31 +00004712void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004713 if (!D)
4714 return;
4715
4716 TemplateParameterList *Params = 0;
4717 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4718 Params = Template->getTemplateParameters();
4719 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4720 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4721 Params = PartialSpec->getTemplateParameters();
4722 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004723 return;
4724
Douglas Gregor6569d682009-05-27 23:11:45 +00004725 for (TemplateParameterList::iterator Param = Params->begin(),
4726 ParamEnd = Params->end();
4727 Param != ParamEnd; ++Param) {
4728 NamedDecl *Named = cast<NamedDecl>(*Param);
4729 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004730 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004731 IdResolver.AddDecl(Named);
4732 }
4733 }
4734}
4735
John McCalld226f652010-08-21 09:40:31 +00004736void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004737 if (!RecordD) return;
4738 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004739 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004740 PushDeclContext(S, Record);
4741}
4742
John McCalld226f652010-08-21 09:40:31 +00004743void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004744 if (!RecordD) return;
4745 PopDeclContext();
4746}
4747
Douglas Gregor72b505b2008-12-16 21:30:33 +00004748/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4749/// parsing a top-level (non-nested) C++ class, and we are now
4750/// parsing those parts of the given Method declaration that could
4751/// not be parsed earlier (C++ [class.mem]p2), such as default
4752/// arguments. This action should enter the scope of the given
4753/// Method declaration as if we had just parsed the qualified method
4754/// name. However, it should not bring the parameters into scope;
4755/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004756void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004757}
4758
4759/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4760/// C++ method declaration. We're (re-)introducing the given
4761/// function parameter into scope for use in parsing later parts of
4762/// the method declaration. For example, we could see an
4763/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004764void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004765 if (!ParamD)
4766 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004767
John McCalld226f652010-08-21 09:40:31 +00004768 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004769
4770 // If this parameter has an unparsed default argument, clear it out
4771 // to make way for the parsed default argument.
4772 if (Param->hasUnparsedDefaultArg())
4773 Param->setDefaultArg(0);
4774
John McCalld226f652010-08-21 09:40:31 +00004775 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004776 if (Param->getDeclName())
4777 IdResolver.AddDecl(Param);
4778}
4779
4780/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4781/// processing the delayed method declaration for Method. The method
4782/// declaration is now considered finished. There may be a separate
4783/// ActOnStartOfFunctionDef action later (not necessarily
4784/// immediately!) for this method, if it was also defined inside the
4785/// class body.
John McCalld226f652010-08-21 09:40:31 +00004786void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004787 if (!MethodD)
4788 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004789
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004790 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004791
John McCalld226f652010-08-21 09:40:31 +00004792 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004793
4794 // Now that we have our default arguments, check the constructor
4795 // again. It could produce additional diagnostics or affect whether
4796 // the class has implicitly-declared destructors, among other
4797 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004798 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4799 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004800
4801 // Check the default arguments, which we may have added.
4802 if (!Method->isInvalidDecl())
4803 CheckCXXDefaultArguments(Method);
4804}
4805
Douglas Gregor42a552f2008-11-05 20:51:48 +00004806/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004807/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004808/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004809/// emit diagnostics and set the invalid bit to true. In any case, the type
4810/// will be updated to reflect a well-formed type for the constructor and
4811/// returned.
4812QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004813 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004814 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004815
4816 // C++ [class.ctor]p3:
4817 // A constructor shall not be virtual (10.3) or static (9.4). A
4818 // constructor can be invoked for a const, volatile or const
4819 // volatile object. A constructor shall not be declared const,
4820 // volatile, or const volatile (9.3.2).
4821 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004822 if (!D.isInvalidType())
4823 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4824 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4825 << SourceRange(D.getIdentifierLoc());
4826 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004827 }
John McCalld931b082010-08-26 03:08:43 +00004828 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004829 if (!D.isInvalidType())
4830 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4831 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4832 << SourceRange(D.getIdentifierLoc());
4833 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004834 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004835 }
Mike Stump1eb44332009-09-09 15:08:12 +00004836
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004837 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004838 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004839 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004840 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4841 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004842 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004843 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4844 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004845 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004846 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4847 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004848 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004849 }
Mike Stump1eb44332009-09-09 15:08:12 +00004850
Douglas Gregorc938c162011-01-26 05:01:58 +00004851 // C++0x [class.ctor]p4:
4852 // A constructor shall not be declared with a ref-qualifier.
4853 if (FTI.hasRefQualifier()) {
4854 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4855 << FTI.RefQualifierIsLValueRef
4856 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4857 D.setInvalidType();
4858 }
4859
Douglas Gregor42a552f2008-11-05 20:51:48 +00004860 // Rebuild the function type "R" without any type qualifiers (in
4861 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004862 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004863 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004864 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4865 return R;
4866
4867 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4868 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004869 EPI.RefQualifier = RQ_None;
4870
Chris Lattner65401802009-04-25 08:28:21 +00004871 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004872 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004873}
4874
Douglas Gregor72b505b2008-12-16 21:30:33 +00004875/// CheckConstructor - Checks a fully-formed constructor for
4876/// well-formedness, issuing any diagnostics required. Returns true if
4877/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004878void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004879 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004880 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4881 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004882 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004883
4884 // C++ [class.copy]p3:
4885 // A declaration of a constructor for a class X is ill-formed if
4886 // its first parameter is of type (optionally cv-qualified) X and
4887 // either there are no other parameters or else all other
4888 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004889 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004890 ((Constructor->getNumParams() == 1) ||
4891 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004892 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4893 Constructor->getTemplateSpecializationKind()
4894 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004895 QualType ParamType = Constructor->getParamDecl(0)->getType();
4896 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4897 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004898 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004899 const char *ConstRef
4900 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4901 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004902 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004903 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004904
4905 // FIXME: Rather that making the constructor invalid, we should endeavor
4906 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004907 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004908 }
4909 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004910}
4911
John McCall15442822010-08-04 01:04:25 +00004912/// CheckDestructor - Checks a fully-formed destructor definition for
4913/// well-formedness, issuing any diagnostics required. Returns true
4914/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004915bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004916 CXXRecordDecl *RD = Destructor->getParent();
4917
4918 if (Destructor->isVirtual()) {
4919 SourceLocation Loc;
4920
4921 if (!Destructor->isImplicit())
4922 Loc = Destructor->getLocation();
4923 else
4924 Loc = RD->getLocation();
4925
4926 // If we have a virtual destructor, look up the deallocation function
4927 FunctionDecl *OperatorDelete = 0;
4928 DeclarationName Name =
4929 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004930 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004931 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004932
4933 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004934
4935 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004936 }
Anders Carlsson37909802009-11-30 21:24:50 +00004937
4938 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004939}
4940
Mike Stump1eb44332009-09-09 15:08:12 +00004941static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004942FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4943 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4944 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004945 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004946}
4947
Douglas Gregor42a552f2008-11-05 20:51:48 +00004948/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4949/// the well-formednes of the destructor declarator @p D with type @p
4950/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004951/// emit diagnostics and set the declarator to invalid. Even if this happens,
4952/// will be updated to reflect a well-formed type for the destructor and
4953/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004954QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004955 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004956 // C++ [class.dtor]p1:
4957 // [...] A typedef-name that names a class is a class-name
4958 // (7.1.3); however, a typedef-name that names a class shall not
4959 // be used as the identifier in the declarator for a destructor
4960 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004961 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004962 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004963 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004964 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004965 else if (const TemplateSpecializationType *TST =
4966 DeclaratorType->getAs<TemplateSpecializationType>())
4967 if (TST->isTypeAlias())
4968 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4969 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004970
4971 // C++ [class.dtor]p2:
4972 // A destructor is used to destroy objects of its class type. A
4973 // destructor takes no parameters, and no return type can be
4974 // specified for it (not even void). The address of a destructor
4975 // shall not be taken. A destructor shall not be static. A
4976 // destructor can be invoked for a const, volatile or const
4977 // volatile object. A destructor shall not be declared const,
4978 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004979 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004980 if (!D.isInvalidType())
4981 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4982 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004983 << SourceRange(D.getIdentifierLoc())
4984 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4985
John McCalld931b082010-08-26 03:08:43 +00004986 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004987 }
Chris Lattner65401802009-04-25 08:28:21 +00004988 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004989 // Destructors don't have return types, but the parser will
4990 // happily parse something like:
4991 //
4992 // class X {
4993 // float ~X();
4994 // };
4995 //
4996 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004997 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4998 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4999 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005000 }
Mike Stump1eb44332009-09-09 15:08:12 +00005001
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005002 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005003 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005004 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005005 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5006 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005007 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005008 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5009 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005010 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005011 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5012 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005013 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005014 }
5015
Douglas Gregorc938c162011-01-26 05:01:58 +00005016 // C++0x [class.dtor]p2:
5017 // A destructor shall not be declared with a ref-qualifier.
5018 if (FTI.hasRefQualifier()) {
5019 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5020 << FTI.RefQualifierIsLValueRef
5021 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5022 D.setInvalidType();
5023 }
5024
Douglas Gregor42a552f2008-11-05 20:51:48 +00005025 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005026 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005027 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5028
5029 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005030 FTI.freeArgs();
5031 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005032 }
5033
Mike Stump1eb44332009-09-09 15:08:12 +00005034 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005035 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005036 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005037 D.setInvalidType();
5038 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005039
5040 // Rebuild the function type "R" without any type qualifiers or
5041 // parameters (in case any of the errors above fired) and with
5042 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005043 // types.
John McCalle23cf432010-12-14 08:05:40 +00005044 if (!D.isInvalidType())
5045 return R;
5046
Douglas Gregord92ec472010-07-01 05:10:53 +00005047 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005048 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5049 EPI.Variadic = false;
5050 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005051 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005052 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005053}
5054
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005055/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5056/// well-formednes of the conversion function declarator @p D with
5057/// type @p R. If there are any errors in the declarator, this routine
5058/// will emit diagnostics and return true. Otherwise, it will return
5059/// false. Either way, the type @p R will be updated to reflect a
5060/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005061void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005062 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005063 // C++ [class.conv.fct]p1:
5064 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005065 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005066 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005067 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005068 if (!D.isInvalidType())
5069 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5070 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5071 << SourceRange(D.getIdentifierLoc());
5072 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005073 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005074 }
John McCalla3f81372010-04-13 00:04:31 +00005075
5076 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5077
Chris Lattner6e475012009-04-25 08:35:12 +00005078 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005079 // Conversion functions don't have return types, but the parser will
5080 // happily parse something like:
5081 //
5082 // class X {
5083 // float operator bool();
5084 // };
5085 //
5086 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005087 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5088 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5089 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005090 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005091 }
5092
John McCalla3f81372010-04-13 00:04:31 +00005093 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5094
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005095 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005096 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005097 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5098
5099 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005100 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005101 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005102 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005103 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005104 D.setInvalidType();
5105 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005106
John McCalla3f81372010-04-13 00:04:31 +00005107 // Diagnose "&operator bool()" and other such nonsense. This
5108 // is actually a gcc extension which we don't support.
5109 if (Proto->getResultType() != ConvType) {
5110 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5111 << Proto->getResultType();
5112 D.setInvalidType();
5113 ConvType = Proto->getResultType();
5114 }
5115
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005116 // C++ [class.conv.fct]p4:
5117 // The conversion-type-id shall not represent a function type nor
5118 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005119 if (ConvType->isArrayType()) {
5120 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5121 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005122 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005123 } else if (ConvType->isFunctionType()) {
5124 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5125 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005126 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005127 }
5128
5129 // Rebuild the function type "R" without any parameters (in case any
5130 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005131 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005132 if (D.isInvalidType())
5133 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005134
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005135 // C++0x explicit conversion operators.
5136 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00005137 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005138 diag::warn_explicit_conversion_functions)
5139 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005140}
5141
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005142/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5143/// the declaration of the given C++ conversion function. This routine
5144/// is responsible for recording the conversion function in the C++
5145/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005146Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005147 assert(Conversion && "Expected to receive a conversion function declaration");
5148
Douglas Gregor9d350972008-12-12 08:25:50 +00005149 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005150
5151 // Make sure we aren't redeclaring the conversion function.
5152 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005153
5154 // C++ [class.conv.fct]p1:
5155 // [...] A conversion function is never used to convert a
5156 // (possibly cv-qualified) object to the (possibly cv-qualified)
5157 // same object type (or a reference to it), to a (possibly
5158 // cv-qualified) base class of that type (or a reference to it),
5159 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005160 // FIXME: Suppress this warning if the conversion function ends up being a
5161 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005162 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005163 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005164 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005165 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005166 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5167 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005168 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005169 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005170 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5171 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005172 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005173 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005174 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005175 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005176 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005177 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005178 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005179 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005180 }
5181
Douglas Gregore80622f2010-09-29 04:25:11 +00005182 if (FunctionTemplateDecl *ConversionTemplate
5183 = Conversion->getDescribedFunctionTemplate())
5184 return ConversionTemplate;
5185
John McCalld226f652010-08-21 09:40:31 +00005186 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005187}
5188
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005189//===----------------------------------------------------------------------===//
5190// Namespace Handling
5191//===----------------------------------------------------------------------===//
5192
John McCallea318642010-08-26 09:15:37 +00005193
5194
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005195/// ActOnStartNamespaceDef - This is called at the start of a namespace
5196/// definition.
John McCalld226f652010-08-21 09:40:31 +00005197Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005198 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005199 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005200 SourceLocation IdentLoc,
5201 IdentifierInfo *II,
5202 SourceLocation LBrace,
5203 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005204 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5205 // For anonymous namespace, take the location of the left brace.
5206 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00005207 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005208 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005209 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005210
5211 Scope *DeclRegionScope = NamespcScope->getParent();
5212
Anders Carlsson2a3503d2010-02-07 01:09:23 +00005213 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5214
John McCall90f14502010-12-10 02:59:44 +00005215 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5216 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005217
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005218 if (II) {
5219 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005220 // The identifier in an original-namespace-definition shall not
5221 // have been previously defined in the declarative region in
5222 // which the original-namespace-definition appears. The
5223 // identifier in an original-namespace-definition is the name of
5224 // the namespace. Subsequently in that declarative region, it is
5225 // treated as an original-namespace-name.
5226 //
5227 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005228 // look through using directives, just look for any ordinary names.
5229
5230 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5231 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5232 Decl::IDNS_Namespace;
5233 NamedDecl *PrevDecl = 0;
5234 for (DeclContext::lookup_result R
5235 = CurContext->getRedeclContext()->lookup(II);
5236 R.first != R.second; ++R.first) {
5237 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5238 PrevDecl = *R.first;
5239 break;
5240 }
5241 }
5242
Douglas Gregor44b43212008-12-11 16:49:14 +00005243 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5244 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005245 if (Namespc->isInline() != OrigNS->isInline()) {
5246 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005247 if (OrigNS->isInline()) {
5248 // The user probably just forgot the 'inline', so suggest that it
5249 // be added back.
5250 Diag(Namespc->getLocation(),
5251 diag::warn_inline_namespace_reopened_noninline)
5252 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5253 } else {
5254 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5255 << Namespc->isInline();
5256 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005257 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005258
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005259 // Recover by ignoring the new namespace's inline status.
5260 Namespc->setInline(OrigNS->isInline());
5261 }
5262
Douglas Gregor44b43212008-12-11 16:49:14 +00005263 // Attach this namespace decl to the chain of extended namespace
5264 // definitions.
5265 OrigNS->setNextNamespace(Namespc);
5266 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005267
Mike Stump1eb44332009-09-09 15:08:12 +00005268 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00005269 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00005270 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00005271 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005272 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005273 } else if (PrevDecl) {
5274 // This is an invalid name redefinition.
5275 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5276 << Namespc->getDeclName();
5277 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5278 Namespc->setInvalidDecl();
5279 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005280 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005281 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005282 // This is the first "real" definition of the namespace "std", so update
5283 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005284 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005285 // We had already defined a dummy namespace "std". Link this new
5286 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005287 StdNS->setNextNamespace(Namespc);
5288 StdNS->setLocation(IdentLoc);
5289 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005290 }
5291
5292 // Make our StdNamespace cache point at the first real definition of the
5293 // "std" namespace.
5294 StdNamespace = Namespc;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005295
5296 // Add this instance of "std" to the set of known namespaces
5297 KnownNamespaces[Namespc] = false;
5298 } else if (!Namespc->isInline()) {
5299 // Since this is an "original" namespace, add it to the known set of
5300 // namespaces if it is not an inline namespace.
5301 KnownNamespaces[Namespc] = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005302 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005303
5304 PushOnScopeChains(Namespc, DeclRegionScope);
5305 } else {
John McCall9aeed322009-10-01 00:25:31 +00005306 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00005307 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00005308
5309 // Link the anonymous namespace into its parent.
5310 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005311 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005312 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5313 PrevDecl = TU->getAnonymousNamespace();
5314 TU->setAnonymousNamespace(Namespc);
5315 } else {
5316 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5317 PrevDecl = ND->getAnonymousNamespace();
5318 ND->setAnonymousNamespace(Namespc);
5319 }
5320
5321 // Link the anonymous namespace with its previous declaration.
5322 if (PrevDecl) {
5323 assert(PrevDecl->isAnonymousNamespace());
5324 assert(!PrevDecl->getNextNamespace());
5325 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5326 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005327
5328 if (Namespc->isInline() != PrevDecl->isInline()) {
5329 // inline-ness must match
5330 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5331 << Namespc->isInline();
5332 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5333 Namespc->setInvalidDecl();
5334 // Recover by ignoring the new namespace's inline status.
5335 Namespc->setInline(PrevDecl->isInline());
5336 }
John McCall5fdd7642009-12-16 02:06:49 +00005337 }
John McCall9aeed322009-10-01 00:25:31 +00005338
Douglas Gregora4181472010-03-24 00:46:35 +00005339 CurContext->addDecl(Namespc);
5340
John McCall9aeed322009-10-01 00:25:31 +00005341 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5342 // behaves as if it were replaced by
5343 // namespace unique { /* empty body */ }
5344 // using namespace unique;
5345 // namespace unique { namespace-body }
5346 // where all occurrences of 'unique' in a translation unit are
5347 // replaced by the same identifier and this identifier differs
5348 // from all other identifiers in the entire program.
5349
5350 // We just create the namespace with an empty name and then add an
5351 // implicit using declaration, just like the standard suggests.
5352 //
5353 // CodeGen enforces the "universally unique" aspect by giving all
5354 // declarations semantically contained within an anonymous
5355 // namespace internal linkage.
5356
John McCall5fdd7642009-12-16 02:06:49 +00005357 if (!PrevDecl) {
5358 UsingDirectiveDecl* UD
5359 = UsingDirectiveDecl::Create(Context, CurContext,
5360 /* 'using' */ LBrace,
5361 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005362 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005363 /* identifier */ SourceLocation(),
5364 Namespc,
5365 /* Ancestor */ CurContext);
5366 UD->setImplicit();
5367 CurContext->addDecl(UD);
5368 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005369 }
5370
5371 // Although we could have an invalid decl (i.e. the namespace name is a
5372 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005373 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5374 // for the namespace has the declarations that showed up in that particular
5375 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005376 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005377 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005378}
5379
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005380/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5381/// is a namespace alias, returns the namespace it points to.
5382static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5383 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5384 return AD->getNamespace();
5385 return dyn_cast_or_null<NamespaceDecl>(D);
5386}
5387
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005388/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5389/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005390void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005391 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5392 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005393 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005394 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005395 if (Namespc->hasAttr<VisibilityAttr>())
5396 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005397}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005398
John McCall384aff82010-08-25 07:42:41 +00005399CXXRecordDecl *Sema::getStdBadAlloc() const {
5400 return cast_or_null<CXXRecordDecl>(
5401 StdBadAlloc.get(Context.getExternalSource()));
5402}
5403
5404NamespaceDecl *Sema::getStdNamespace() const {
5405 return cast_or_null<NamespaceDecl>(
5406 StdNamespace.get(Context.getExternalSource()));
5407}
5408
Douglas Gregor66992202010-06-29 17:53:46 +00005409/// \brief Retrieve the special "std" namespace, which may require us to
5410/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005411NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005412 if (!StdNamespace) {
5413 // The "std" namespace has not yet been defined, so build one implicitly.
5414 StdNamespace = NamespaceDecl::Create(Context,
5415 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005416 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00005417 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005418 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005419 }
5420
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005421 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005422}
5423
Douglas Gregor9172aa62011-03-26 22:25:30 +00005424/// \brief Determine whether a using statement is in a context where it will be
5425/// apply in all contexts.
5426static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5427 switch (CurContext->getDeclKind()) {
5428 case Decl::TranslationUnit:
5429 return true;
5430 case Decl::LinkageSpec:
5431 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5432 default:
5433 return false;
5434 }
5435}
5436
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005437static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5438 CXXScopeSpec &SS,
5439 SourceLocation IdentLoc,
5440 IdentifierInfo *Ident) {
5441 R.clear();
5442 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5443 R.getLookupKind(), Sc, &SS, NULL,
5444 false, S.CTC_NoKeywords, NULL)) {
5445 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5446 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5447 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5448 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5449 if (DeclContext *DC = S.computeDeclContext(SS, false))
5450 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5451 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5452 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5453 else
5454 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5455 << Ident << CorrectedQuotedStr
5456 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5457
5458 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5459 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5460
5461 Ident = Corrected.getCorrectionAsIdentifierInfo();
5462 R.addDecl(Corrected.getCorrectionDecl());
5463 return true;
5464 }
5465 R.setLookupName(Ident);
5466 }
5467 return false;
5468}
5469
John McCalld226f652010-08-21 09:40:31 +00005470Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005471 SourceLocation UsingLoc,
5472 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005473 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005474 SourceLocation IdentLoc,
5475 IdentifierInfo *NamespcName,
5476 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005477 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5478 assert(NamespcName && "Invalid NamespcName.");
5479 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005480
5481 // This can only happen along a recovery path.
5482 while (S->getFlags() & Scope::TemplateParamScope)
5483 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005484 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005485
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005486 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005487 NestedNameSpecifier *Qualifier = 0;
5488 if (SS.isSet())
5489 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5490
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005491 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005492 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5493 LookupParsedName(R, S, &SS);
5494 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005495 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005496
Douglas Gregor66992202010-06-29 17:53:46 +00005497 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005498 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005499 // Allow "using namespace std;" or "using namespace ::std;" even if
5500 // "std" hasn't been defined yet, for GCC compatibility.
5501 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5502 NamespcName->isStr("std")) {
5503 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005504 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005505 R.resolveKind();
5506 }
5507 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005508 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005509 }
5510
John McCallf36e02d2009-10-09 21:13:30 +00005511 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005512 NamedDecl *Named = R.getFoundDecl();
5513 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5514 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005515 // C++ [namespace.udir]p1:
5516 // A using-directive specifies that the names in the nominated
5517 // namespace can be used in the scope in which the
5518 // using-directive appears after the using-directive. During
5519 // unqualified name lookup (3.4.1), the names appear as if they
5520 // were declared in the nearest enclosing namespace which
5521 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005522 // namespace. [Note: in this context, "contains" means "contains
5523 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005524
5525 // Find enclosing context containing both using-directive and
5526 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005527 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005528 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5529 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5530 CommonAncestor = CommonAncestor->getParent();
5531
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005532 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005533 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005534 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005535
Douglas Gregor9172aa62011-03-26 22:25:30 +00005536 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005537 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005538 Diag(IdentLoc, diag::warn_using_directive_in_header);
5539 }
5540
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005541 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005542 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005543 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005544 }
5545
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005546 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005547 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005548}
5549
5550void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5551 // If scope has associated entity, then using directive is at namespace
5552 // or translation unit scope. We add UsingDirectiveDecls, into
5553 // it's lookup structure.
5554 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005555 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005556 else
5557 // Otherwise it is block-sope. using-directives will affect lookup
5558 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005559 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005560}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005561
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005562
John McCalld226f652010-08-21 09:40:31 +00005563Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005564 AccessSpecifier AS,
5565 bool HasUsingKeyword,
5566 SourceLocation UsingLoc,
5567 CXXScopeSpec &SS,
5568 UnqualifiedId &Name,
5569 AttributeList *AttrList,
5570 bool IsTypeName,
5571 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005572 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005573
Douglas Gregor12c118a2009-11-04 16:30:06 +00005574 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005575 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005576 case UnqualifiedId::IK_Identifier:
5577 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005578 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005579 case UnqualifiedId::IK_ConversionFunctionId:
5580 break;
5581
5582 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005583 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005584 // C++0x inherited constructors.
5585 if (getLangOptions().CPlusPlus0x) break;
5586
Douglas Gregor12c118a2009-11-04 16:30:06 +00005587 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5588 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005589 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005590
5591 case UnqualifiedId::IK_DestructorName:
5592 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5593 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005594 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005595
5596 case UnqualifiedId::IK_TemplateId:
5597 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5598 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005599 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005600 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005601
5602 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5603 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005604 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005605 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005606
John McCall60fa3cf2009-12-11 02:10:03 +00005607 // Warn about using declarations.
5608 // TODO: store that the declaration was written without 'using' and
5609 // talk about access decls instead of using decls in the
5610 // diagnostics.
5611 if (!HasUsingKeyword) {
5612 UsingLoc = Name.getSourceRange().getBegin();
5613
5614 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005615 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005616 }
5617
Douglas Gregor56c04582010-12-16 00:46:58 +00005618 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5619 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5620 return 0;
5621
John McCall9488ea12009-11-17 05:59:44 +00005622 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005623 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005624 /* IsInstantiation */ false,
5625 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005626 if (UD)
5627 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005628
John McCalld226f652010-08-21 09:40:31 +00005629 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005630}
5631
Douglas Gregor09acc982010-07-07 23:08:52 +00005632/// \brief Determine whether a using declaration considers the given
5633/// declarations as "equivalent", e.g., if they are redeclarations of
5634/// the same entity or are both typedefs of the same type.
5635static bool
5636IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5637 bool &SuppressRedeclaration) {
5638 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5639 SuppressRedeclaration = false;
5640 return true;
5641 }
5642
Richard Smith162e1c12011-04-15 14:24:37 +00005643 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5644 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005645 SuppressRedeclaration = true;
5646 return Context.hasSameType(TD1->getUnderlyingType(),
5647 TD2->getUnderlyingType());
5648 }
5649
5650 return false;
5651}
5652
5653
John McCall9f54ad42009-12-10 09:41:52 +00005654/// Determines whether to create a using shadow decl for a particular
5655/// decl, given the set of decls existing prior to this using lookup.
5656bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5657 const LookupResult &Previous) {
5658 // Diagnose finding a decl which is not from a base class of the
5659 // current class. We do this now because there are cases where this
5660 // function will silently decide not to build a shadow decl, which
5661 // will pre-empt further diagnostics.
5662 //
5663 // We don't need to do this in C++0x because we do the check once on
5664 // the qualifier.
5665 //
5666 // FIXME: diagnose the following if we care enough:
5667 // struct A { int foo; };
5668 // struct B : A { using A::foo; };
5669 // template <class T> struct C : A {};
5670 // template <class T> struct D : C<T> { using B::foo; } // <---
5671 // This is invalid (during instantiation) in C++03 because B::foo
5672 // resolves to the using decl in B, which is not a base class of D<T>.
5673 // We can't diagnose it immediately because C<T> is an unknown
5674 // specialization. The UsingShadowDecl in D<T> then points directly
5675 // to A::foo, which will look well-formed when we instantiate.
5676 // The right solution is to not collapse the shadow-decl chain.
5677 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5678 DeclContext *OrigDC = Orig->getDeclContext();
5679
5680 // Handle enums and anonymous structs.
5681 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5682 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5683 while (OrigRec->isAnonymousStructOrUnion())
5684 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5685
5686 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5687 if (OrigDC == CurContext) {
5688 Diag(Using->getLocation(),
5689 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005690 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005691 Diag(Orig->getLocation(), diag::note_using_decl_target);
5692 return true;
5693 }
5694
Douglas Gregordc355712011-02-25 00:36:19 +00005695 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005696 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005697 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005698 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005699 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005700 Diag(Orig->getLocation(), diag::note_using_decl_target);
5701 return true;
5702 }
5703 }
5704
5705 if (Previous.empty()) return false;
5706
5707 NamedDecl *Target = Orig;
5708 if (isa<UsingShadowDecl>(Target))
5709 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5710
John McCalld7533ec2009-12-11 02:33:26 +00005711 // If the target happens to be one of the previous declarations, we
5712 // don't have a conflict.
5713 //
5714 // FIXME: but we might be increasing its access, in which case we
5715 // should redeclare it.
5716 NamedDecl *NonTag = 0, *Tag = 0;
5717 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5718 I != E; ++I) {
5719 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005720 bool Result;
5721 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5722 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005723
5724 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5725 }
5726
John McCall9f54ad42009-12-10 09:41:52 +00005727 if (Target->isFunctionOrFunctionTemplate()) {
5728 FunctionDecl *FD;
5729 if (isa<FunctionTemplateDecl>(Target))
5730 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5731 else
5732 FD = cast<FunctionDecl>(Target);
5733
5734 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005735 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005736 case Ovl_Overload:
5737 return false;
5738
5739 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005740 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005741 break;
5742
5743 // We found a decl with the exact signature.
5744 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005745 // If we're in a record, we want to hide the target, so we
5746 // return true (without a diagnostic) to tell the caller not to
5747 // build a shadow decl.
5748 if (CurContext->isRecord())
5749 return true;
5750
5751 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005752 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005753 break;
5754 }
5755
5756 Diag(Target->getLocation(), diag::note_using_decl_target);
5757 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5758 return true;
5759 }
5760
5761 // Target is not a function.
5762
John McCall9f54ad42009-12-10 09:41:52 +00005763 if (isa<TagDecl>(Target)) {
5764 // No conflict between a tag and a non-tag.
5765 if (!Tag) return false;
5766
John McCall41ce66f2009-12-10 19:51:03 +00005767 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005768 Diag(Target->getLocation(), diag::note_using_decl_target);
5769 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5770 return true;
5771 }
5772
5773 // No conflict between a tag and a non-tag.
5774 if (!NonTag) return false;
5775
John McCall41ce66f2009-12-10 19:51:03 +00005776 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005777 Diag(Target->getLocation(), diag::note_using_decl_target);
5778 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5779 return true;
5780}
5781
John McCall9488ea12009-11-17 05:59:44 +00005782/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005783UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005784 UsingDecl *UD,
5785 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005786
5787 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005788 NamedDecl *Target = Orig;
5789 if (isa<UsingShadowDecl>(Target)) {
5790 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5791 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005792 }
5793
5794 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005795 = UsingShadowDecl::Create(Context, CurContext,
5796 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005797 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005798
5799 Shadow->setAccess(UD->getAccess());
5800 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5801 Shadow->setInvalidDecl();
5802
John McCall9488ea12009-11-17 05:59:44 +00005803 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005804 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005805 else
John McCall604e7f12009-12-08 07:46:18 +00005806 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005807
John McCall604e7f12009-12-08 07:46:18 +00005808
John McCall9f54ad42009-12-10 09:41:52 +00005809 return Shadow;
5810}
John McCall604e7f12009-12-08 07:46:18 +00005811
John McCall9f54ad42009-12-10 09:41:52 +00005812/// Hides a using shadow declaration. This is required by the current
5813/// using-decl implementation when a resolvable using declaration in a
5814/// class is followed by a declaration which would hide or override
5815/// one or more of the using decl's targets; for example:
5816///
5817/// struct Base { void foo(int); };
5818/// struct Derived : Base {
5819/// using Base::foo;
5820/// void foo(int);
5821/// };
5822///
5823/// The governing language is C++03 [namespace.udecl]p12:
5824///
5825/// When a using-declaration brings names from a base class into a
5826/// derived class scope, member functions in the derived class
5827/// override and/or hide member functions with the same name and
5828/// parameter types in a base class (rather than conflicting).
5829///
5830/// There are two ways to implement this:
5831/// (1) optimistically create shadow decls when they're not hidden
5832/// by existing declarations, or
5833/// (2) don't create any shadow decls (or at least don't make them
5834/// visible) until we've fully parsed/instantiated the class.
5835/// The problem with (1) is that we might have to retroactively remove
5836/// a shadow decl, which requires several O(n) operations because the
5837/// decl structures are (very reasonably) not designed for removal.
5838/// (2) avoids this but is very fiddly and phase-dependent.
5839void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005840 if (Shadow->getDeclName().getNameKind() ==
5841 DeclarationName::CXXConversionFunctionName)
5842 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5843
John McCall9f54ad42009-12-10 09:41:52 +00005844 // Remove it from the DeclContext...
5845 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005846
John McCall9f54ad42009-12-10 09:41:52 +00005847 // ...and the scope, if applicable...
5848 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005849 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005850 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005851 }
5852
John McCall9f54ad42009-12-10 09:41:52 +00005853 // ...and the using decl.
5854 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5855
5856 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005857 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005858}
5859
John McCall7ba107a2009-11-18 02:36:19 +00005860/// Builds a using declaration.
5861///
5862/// \param IsInstantiation - Whether this call arises from an
5863/// instantiation of an unresolved using declaration. We treat
5864/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005865NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5866 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005867 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005868 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005869 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005870 bool IsInstantiation,
5871 bool IsTypeName,
5872 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005873 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005874 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005875 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005876
Anders Carlsson550b14b2009-08-28 05:49:21 +00005877 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005878
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005879 if (SS.isEmpty()) {
5880 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005881 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005882 }
Mike Stump1eb44332009-09-09 15:08:12 +00005883
John McCall9f54ad42009-12-10 09:41:52 +00005884 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005885 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005886 ForRedeclaration);
5887 Previous.setHideTags(false);
5888 if (S) {
5889 LookupName(Previous, S);
5890
5891 // It is really dumb that we have to do this.
5892 LookupResult::Filter F = Previous.makeFilter();
5893 while (F.hasNext()) {
5894 NamedDecl *D = F.next();
5895 if (!isDeclInScope(D, CurContext, S))
5896 F.erase();
5897 }
5898 F.done();
5899 } else {
5900 assert(IsInstantiation && "no scope in non-instantiation");
5901 assert(CurContext->isRecord() && "scope not record in instantiation");
5902 LookupQualifiedName(Previous, CurContext);
5903 }
5904
John McCall9f54ad42009-12-10 09:41:52 +00005905 // Check for invalid redeclarations.
5906 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5907 return 0;
5908
5909 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005910 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5911 return 0;
5912
John McCallaf8e6ed2009-11-12 03:15:40 +00005913 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005914 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005915 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005916 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005917 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005918 // FIXME: not all declaration name kinds are legal here
5919 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5920 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005921 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005922 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005923 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005924 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5925 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005926 }
John McCalled976492009-12-04 22:46:56 +00005927 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005928 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5929 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005930 }
John McCalled976492009-12-04 22:46:56 +00005931 D->setAccess(AS);
5932 CurContext->addDecl(D);
5933
5934 if (!LookupContext) return D;
5935 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005936
John McCall77bb1aa2010-05-01 00:40:08 +00005937 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005938 UD->setInvalidDecl();
5939 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005940 }
5941
Sebastian Redlf677ea32011-02-05 19:23:19 +00005942 // Constructor inheriting using decls get special treatment.
5943 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005944 if (CheckInheritedConstructorUsingDecl(UD))
5945 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005946 return UD;
5947 }
5948
5949 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005950
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005951 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00005952
John McCall604e7f12009-12-08 07:46:18 +00005953 // Unlike most lookups, we don't always want to hide tag
5954 // declarations: tag names are visible through the using declaration
5955 // even if hidden by ordinary names, *except* in a dependent context
5956 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005957 if (!IsInstantiation)
5958 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005959
John McCalla24dc2e2009-11-17 02:14:36 +00005960 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005961
John McCallf36e02d2009-10-09 21:13:30 +00005962 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005963 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005964 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005965 UD->setInvalidDecl();
5966 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005967 }
5968
John McCalled976492009-12-04 22:46:56 +00005969 if (R.isAmbiguous()) {
5970 UD->setInvalidDecl();
5971 return UD;
5972 }
Mike Stump1eb44332009-09-09 15:08:12 +00005973
John McCall7ba107a2009-11-18 02:36:19 +00005974 if (IsTypeName) {
5975 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005976 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005977 Diag(IdentLoc, diag::err_using_typename_non_type);
5978 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5979 Diag((*I)->getUnderlyingDecl()->getLocation(),
5980 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005981 UD->setInvalidDecl();
5982 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005983 }
5984 } else {
5985 // If we asked for a non-typename and we got a type, error out,
5986 // but only if this is an instantiation of an unresolved using
5987 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005988 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005989 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5990 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005991 UD->setInvalidDecl();
5992 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005993 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005994 }
5995
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005996 // C++0x N2914 [namespace.udecl]p6:
5997 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005998 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005999 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6000 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006001 UD->setInvalidDecl();
6002 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006003 }
Mike Stump1eb44332009-09-09 15:08:12 +00006004
John McCall9f54ad42009-12-10 09:41:52 +00006005 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6006 if (!CheckUsingShadowDecl(UD, *I, Previous))
6007 BuildUsingShadowDecl(S, UD, *I);
6008 }
John McCall9488ea12009-11-17 05:59:44 +00006009
6010 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006011}
6012
Sebastian Redlf677ea32011-02-05 19:23:19 +00006013/// Additional checks for a using declaration referring to a constructor name.
6014bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6015 if (UD->isTypeName()) {
6016 // FIXME: Cannot specify typename when specifying constructor
6017 return true;
6018 }
6019
Douglas Gregordc355712011-02-25 00:36:19 +00006020 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006021 assert(SourceType &&
6022 "Using decl naming constructor doesn't have type in scope spec.");
6023 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6024
6025 // Check whether the named type is a direct base class.
6026 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6027 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6028 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6029 BaseIt != BaseE; ++BaseIt) {
6030 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6031 if (CanonicalSourceType == BaseType)
6032 break;
6033 }
6034
6035 if (BaseIt == BaseE) {
6036 // Did not find SourceType in the bases.
6037 Diag(UD->getUsingLocation(),
6038 diag::err_using_decl_constructor_not_in_direct_base)
6039 << UD->getNameInfo().getSourceRange()
6040 << QualType(SourceType, 0) << TargetClass;
6041 return true;
6042 }
6043
6044 BaseIt->setInheritConstructors();
6045
6046 return false;
6047}
6048
John McCall9f54ad42009-12-10 09:41:52 +00006049/// Checks that the given using declaration is not an invalid
6050/// redeclaration. Note that this is checking only for the using decl
6051/// itself, not for any ill-formedness among the UsingShadowDecls.
6052bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6053 bool isTypeName,
6054 const CXXScopeSpec &SS,
6055 SourceLocation NameLoc,
6056 const LookupResult &Prev) {
6057 // C++03 [namespace.udecl]p8:
6058 // C++0x [namespace.udecl]p10:
6059 // A using-declaration is a declaration and can therefore be used
6060 // repeatedly where (and only where) multiple declarations are
6061 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006062 //
John McCall8a726212010-11-29 18:01:58 +00006063 // That's in non-member contexts.
6064 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006065 return false;
6066
6067 NestedNameSpecifier *Qual
6068 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6069
6070 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6071 NamedDecl *D = *I;
6072
6073 bool DTypename;
6074 NestedNameSpecifier *DQual;
6075 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6076 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006077 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006078 } else if (UnresolvedUsingValueDecl *UD
6079 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6080 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006081 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006082 } else if (UnresolvedUsingTypenameDecl *UD
6083 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6084 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006085 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006086 } else continue;
6087
6088 // using decls differ if one says 'typename' and the other doesn't.
6089 // FIXME: non-dependent using decls?
6090 if (isTypeName != DTypename) continue;
6091
6092 // using decls differ if they name different scopes (but note that
6093 // template instantiation can cause this check to trigger when it
6094 // didn't before instantiation).
6095 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6096 Context.getCanonicalNestedNameSpecifier(DQual))
6097 continue;
6098
6099 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006100 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006101 return true;
6102 }
6103
6104 return false;
6105}
6106
John McCall604e7f12009-12-08 07:46:18 +00006107
John McCalled976492009-12-04 22:46:56 +00006108/// Checks that the given nested-name qualifier used in a using decl
6109/// in the current context is appropriately related to the current
6110/// scope. If an error is found, diagnoses it and returns true.
6111bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6112 const CXXScopeSpec &SS,
6113 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006114 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006115
John McCall604e7f12009-12-08 07:46:18 +00006116 if (!CurContext->isRecord()) {
6117 // C++03 [namespace.udecl]p3:
6118 // C++0x [namespace.udecl]p8:
6119 // A using-declaration for a class member shall be a member-declaration.
6120
6121 // If we weren't able to compute a valid scope, it must be a
6122 // dependent class scope.
6123 if (!NamedContext || NamedContext->isRecord()) {
6124 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6125 << SS.getRange();
6126 return true;
6127 }
6128
6129 // Otherwise, everything is known to be fine.
6130 return false;
6131 }
6132
6133 // The current scope is a record.
6134
6135 // If the named context is dependent, we can't decide much.
6136 if (!NamedContext) {
6137 // FIXME: in C++0x, we can diagnose if we can prove that the
6138 // nested-name-specifier does not refer to a base class, which is
6139 // still possible in some cases.
6140
6141 // Otherwise we have to conservatively report that things might be
6142 // okay.
6143 return false;
6144 }
6145
6146 if (!NamedContext->isRecord()) {
6147 // Ideally this would point at the last name in the specifier,
6148 // but we don't have that level of source info.
6149 Diag(SS.getRange().getBegin(),
6150 diag::err_using_decl_nested_name_specifier_is_not_class)
6151 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6152 return true;
6153 }
6154
Douglas Gregor6fb07292010-12-21 07:41:49 +00006155 if (!NamedContext->isDependentContext() &&
6156 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6157 return true;
6158
John McCall604e7f12009-12-08 07:46:18 +00006159 if (getLangOptions().CPlusPlus0x) {
6160 // C++0x [namespace.udecl]p3:
6161 // In a using-declaration used as a member-declaration, the
6162 // nested-name-specifier shall name a base class of the class
6163 // being defined.
6164
6165 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6166 cast<CXXRecordDecl>(NamedContext))) {
6167 if (CurContext == NamedContext) {
6168 Diag(NameLoc,
6169 diag::err_using_decl_nested_name_specifier_is_current_class)
6170 << SS.getRange();
6171 return true;
6172 }
6173
6174 Diag(SS.getRange().getBegin(),
6175 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6176 << (NestedNameSpecifier*) SS.getScopeRep()
6177 << cast<CXXRecordDecl>(CurContext)
6178 << SS.getRange();
6179 return true;
6180 }
6181
6182 return false;
6183 }
6184
6185 // C++03 [namespace.udecl]p4:
6186 // A using-declaration used as a member-declaration shall refer
6187 // to a member of a base class of the class being defined [etc.].
6188
6189 // Salient point: SS doesn't have to name a base class as long as
6190 // lookup only finds members from base classes. Therefore we can
6191 // diagnose here only if we can prove that that can't happen,
6192 // i.e. if the class hierarchies provably don't intersect.
6193
6194 // TODO: it would be nice if "definitely valid" results were cached
6195 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6196 // need to be repeated.
6197
6198 struct UserData {
6199 llvm::DenseSet<const CXXRecordDecl*> Bases;
6200
6201 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6202 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6203 Data->Bases.insert(Base);
6204 return true;
6205 }
6206
6207 bool hasDependentBases(const CXXRecordDecl *Class) {
6208 return !Class->forallBases(collect, this);
6209 }
6210
6211 /// Returns true if the base is dependent or is one of the
6212 /// accumulated base classes.
6213 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6214 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6215 return !Data->Bases.count(Base);
6216 }
6217
6218 bool mightShareBases(const CXXRecordDecl *Class) {
6219 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6220 }
6221 };
6222
6223 UserData Data;
6224
6225 // Returns false if we find a dependent base.
6226 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6227 return false;
6228
6229 // Returns false if the class has a dependent base or if it or one
6230 // of its bases is present in the base set of the current context.
6231 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6232 return false;
6233
6234 Diag(SS.getRange().getBegin(),
6235 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6236 << (NestedNameSpecifier*) SS.getScopeRep()
6237 << cast<CXXRecordDecl>(CurContext)
6238 << SS.getRange();
6239
6240 return true;
John McCalled976492009-12-04 22:46:56 +00006241}
6242
Richard Smith162e1c12011-04-15 14:24:37 +00006243Decl *Sema::ActOnAliasDeclaration(Scope *S,
6244 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006245 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006246 SourceLocation UsingLoc,
6247 UnqualifiedId &Name,
6248 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006249 // Skip up to the relevant declaration scope.
6250 while (S->getFlags() & Scope::TemplateParamScope)
6251 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006252 assert((S->getFlags() & Scope::DeclScope) &&
6253 "got alias-declaration outside of declaration scope");
6254
6255 if (Type.isInvalid())
6256 return 0;
6257
6258 bool Invalid = false;
6259 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6260 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006261 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006262
6263 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6264 return 0;
6265
6266 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006267 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006268 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006269 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6270 TInfo->getTypeLoc().getBeginLoc());
6271 }
Richard Smith162e1c12011-04-15 14:24:37 +00006272
6273 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6274 LookupName(Previous, S);
6275
6276 // Warn about shadowing the name of a template parameter.
6277 if (Previous.isSingleResult() &&
6278 Previous.getFoundDecl()->isTemplateParameter()) {
6279 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6280 Previous.getFoundDecl()))
6281 Invalid = true;
6282 Previous.clear();
6283 }
6284
6285 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6286 "name in alias declaration must be an identifier");
6287 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6288 Name.StartLocation,
6289 Name.Identifier, TInfo);
6290
6291 NewTD->setAccess(AS);
6292
6293 if (Invalid)
6294 NewTD->setInvalidDecl();
6295
Richard Smith3e4c6c42011-05-05 21:57:07 +00006296 CheckTypedefForVariablyModifiedType(S, NewTD);
6297 Invalid |= NewTD->isInvalidDecl();
6298
Richard Smith162e1c12011-04-15 14:24:37 +00006299 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006300
6301 NamedDecl *NewND;
6302 if (TemplateParamLists.size()) {
6303 TypeAliasTemplateDecl *OldDecl = 0;
6304 TemplateParameterList *OldTemplateParams = 0;
6305
6306 if (TemplateParamLists.size() != 1) {
6307 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6308 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6309 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6310 }
6311 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6312
6313 // Only consider previous declarations in the same scope.
6314 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6315 /*ExplicitInstantiationOrSpecialization*/false);
6316 if (!Previous.empty()) {
6317 Redeclaration = true;
6318
6319 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6320 if (!OldDecl && !Invalid) {
6321 Diag(UsingLoc, diag::err_redefinition_different_kind)
6322 << Name.Identifier;
6323
6324 NamedDecl *OldD = Previous.getRepresentativeDecl();
6325 if (OldD->getLocation().isValid())
6326 Diag(OldD->getLocation(), diag::note_previous_definition);
6327
6328 Invalid = true;
6329 }
6330
6331 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6332 if (TemplateParameterListsAreEqual(TemplateParams,
6333 OldDecl->getTemplateParameters(),
6334 /*Complain=*/true,
6335 TPL_TemplateMatch))
6336 OldTemplateParams = OldDecl->getTemplateParameters();
6337 else
6338 Invalid = true;
6339
6340 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6341 if (!Invalid &&
6342 !Context.hasSameType(OldTD->getUnderlyingType(),
6343 NewTD->getUnderlyingType())) {
6344 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6345 // but we can't reasonably accept it.
6346 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6347 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6348 if (OldTD->getLocation().isValid())
6349 Diag(OldTD->getLocation(), diag::note_previous_definition);
6350 Invalid = true;
6351 }
6352 }
6353 }
6354
6355 // Merge any previous default template arguments into our parameters,
6356 // and check the parameter list.
6357 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6358 TPC_TypeAliasTemplate))
6359 return 0;
6360
6361 TypeAliasTemplateDecl *NewDecl =
6362 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6363 Name.Identifier, TemplateParams,
6364 NewTD);
6365
6366 NewDecl->setAccess(AS);
6367
6368 if (Invalid)
6369 NewDecl->setInvalidDecl();
6370 else if (OldDecl)
6371 NewDecl->setPreviousDeclaration(OldDecl);
6372
6373 NewND = NewDecl;
6374 } else {
6375 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6376 NewND = NewTD;
6377 }
Richard Smith162e1c12011-04-15 14:24:37 +00006378
6379 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006380 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006381
Richard Smith3e4c6c42011-05-05 21:57:07 +00006382 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006383}
6384
John McCalld226f652010-08-21 09:40:31 +00006385Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006386 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006387 SourceLocation AliasLoc,
6388 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006389 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006390 SourceLocation IdentLoc,
6391 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006392
Anders Carlsson81c85c42009-03-28 23:53:49 +00006393 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006394 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6395 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006396
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006397 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006398 NamedDecl *PrevDecl
6399 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6400 ForRedeclaration);
6401 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6402 PrevDecl = 0;
6403
6404 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006405 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006406 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006407 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006408 // FIXME: At some point, we'll want to create the (redundant)
6409 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006410 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006411 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006412 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006413 }
Mike Stump1eb44332009-09-09 15:08:12 +00006414
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006415 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6416 diag::err_redefinition_different_kind;
6417 Diag(AliasLoc, DiagID) << Alias;
6418 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006419 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006420 }
6421
John McCalla24dc2e2009-11-17 02:14:36 +00006422 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006423 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006424
John McCallf36e02d2009-10-09 21:13:30 +00006425 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006426 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006427 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006428 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006429 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006430 }
Mike Stump1eb44332009-09-09 15:08:12 +00006431
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006432 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006433 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006434 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006435 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006436
John McCall3dbd3d52010-02-16 06:53:13 +00006437 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006438 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006439}
6440
Douglas Gregor39957dc2010-05-01 15:04:51 +00006441namespace {
6442 /// \brief Scoped object used to handle the state changes required in Sema
6443 /// to implicitly define the body of a C++ member function;
6444 class ImplicitlyDefinedFunctionScope {
6445 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006446 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006447
6448 public:
6449 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006450 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006451 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006452 S.PushFunctionScope();
6453 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6454 }
6455
6456 ~ImplicitlyDefinedFunctionScope() {
6457 S.PopExpressionEvaluationContext();
6458 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006459 }
6460 };
6461}
6462
Sean Hunt001cad92011-05-10 00:49:42 +00006463Sema::ImplicitExceptionSpecification
6464Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006465 // C++ [except.spec]p14:
6466 // An implicitly declared special member function (Clause 12) shall have an
6467 // exception-specification. [...]
6468 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006469 if (ClassDecl->isInvalidDecl())
6470 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006471
Sebastian Redl60618fa2011-03-12 11:50:43 +00006472 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006473 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6474 BEnd = ClassDecl->bases_end();
6475 B != BEnd; ++B) {
6476 if (B->isVirtual()) // Handled below.
6477 continue;
6478
Douglas Gregor18274032010-07-03 00:47:00 +00006479 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6480 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006481 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6482 // If this is a deleted function, add it anyway. This might be conformant
6483 // with the standard. This might not. I'm not sure. It might not matter.
6484 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006485 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006486 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006487 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006488
6489 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006490 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6491 BEnd = ClassDecl->vbases_end();
6492 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006493 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6494 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006495 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6496 // If this is a deleted function, add it anyway. This might be conformant
6497 // with the standard. This might not. I'm not sure. It might not matter.
6498 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006499 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006500 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006501 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006502
6503 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006504 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6505 FEnd = ClassDecl->field_end();
6506 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006507 if (F->hasInClassInitializer()) {
6508 if (Expr *E = F->getInClassInitializer())
6509 ExceptSpec.CalledExpr(E);
6510 else if (!F->isInvalidDecl())
6511 ExceptSpec.SetDelayed();
6512 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006513 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006514 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6515 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6516 // If this is a deleted function, add it anyway. This might be conformant
6517 // with the standard. This might not. I'm not sure. It might not matter.
6518 // In particular, the problem is that this function never gets called. It
6519 // might just be ill-formed because this function attempts to refer to
6520 // a deleted function here.
6521 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006522 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006523 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006524 }
John McCalle23cf432010-12-14 08:05:40 +00006525
Sean Hunt001cad92011-05-10 00:49:42 +00006526 return ExceptSpec;
6527}
6528
6529CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6530 CXXRecordDecl *ClassDecl) {
6531 // C++ [class.ctor]p5:
6532 // A default constructor for a class X is a constructor of class X
6533 // that can be called without an argument. If there is no
6534 // user-declared constructor for class X, a default constructor is
6535 // implicitly declared. An implicitly-declared default constructor
6536 // is an inline public member of its class.
6537 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6538 "Should not build implicit default constructor!");
6539
6540 ImplicitExceptionSpecification Spec =
6541 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6542 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006543
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006544 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006545 CanQualType ClassType
6546 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006547 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006548 DeclarationName Name
6549 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006550 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006551 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006552 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00006553 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006554 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00006555 /*TInfo=*/0,
6556 /*isExplicit=*/false,
6557 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006558 /*isImplicitlyDeclared=*/true,
6559 // FIXME: apply the rules for definitions here
6560 /*isConstexpr=*/false);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006561 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006562 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006563 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006564 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006565
6566 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006567 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6568
Douglas Gregor23c94db2010-07-02 17:43:08 +00006569 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006570 PushOnScopeChains(DefaultCon, S, false);
6571 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006572
6573 if (ShouldDeleteDefaultConstructor(DefaultCon))
6574 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006575
Douglas Gregor32df23e2010-07-01 22:02:46 +00006576 return DefaultCon;
6577}
6578
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006579void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6580 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006581 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006582 !Constructor->doesThisDeclarationHaveABody() &&
6583 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006584 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006585
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006586 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006587 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006588
Douglas Gregor39957dc2010-05-01 15:04:51 +00006589 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006590 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006591 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006592 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006593 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006594 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006595 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006596 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006597 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006598
6599 SourceLocation Loc = Constructor->getLocation();
6600 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6601
6602 Constructor->setUsed();
6603 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006604
6605 if (ASTMutationListener *L = getASTMutationListener()) {
6606 L->CompletedImplicitDefinition(Constructor);
6607 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006608}
6609
Richard Smith7a614d82011-06-11 17:19:42 +00006610/// Get any existing defaulted default constructor for the given class. Do not
6611/// implicitly define one if it does not exist.
6612static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6613 CXXRecordDecl *D) {
6614 ASTContext &Context = Self.Context;
6615 QualType ClassType = Context.getTypeDeclType(D);
6616 DeclarationName ConstructorName
6617 = Context.DeclarationNames.getCXXConstructorName(
6618 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6619
6620 DeclContext::lookup_const_iterator Con, ConEnd;
6621 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6622 Con != ConEnd; ++Con) {
6623 // A function template cannot be defaulted.
6624 if (isa<FunctionTemplateDecl>(*Con))
6625 continue;
6626
6627 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6628 if (Constructor->isDefaultConstructor())
6629 return Constructor->isDefaulted() ? Constructor : 0;
6630 }
6631 return 0;
6632}
6633
6634void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6635 if (!D) return;
6636 AdjustDeclIfTemplate(D);
6637
6638 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6639 CXXConstructorDecl *CtorDecl
6640 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6641
6642 if (!CtorDecl) return;
6643
6644 // Compute the exception specification for the default constructor.
6645 const FunctionProtoType *CtorTy =
6646 CtorDecl->getType()->castAs<FunctionProtoType>();
6647 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6648 ImplicitExceptionSpecification Spec =
6649 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6650 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6651 assert(EPI.ExceptionSpecType != EST_Delayed);
6652
6653 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6654 }
6655
6656 // If the default constructor is explicitly defaulted, checking the exception
6657 // specification is deferred until now.
6658 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6659 !ClassDecl->isDependentType())
6660 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6661}
6662
Sebastian Redlf677ea32011-02-05 19:23:19 +00006663void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6664 // We start with an initial pass over the base classes to collect those that
6665 // inherit constructors from. If there are none, we can forgo all further
6666 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006667 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006668 BasesVector BasesToInheritFrom;
6669 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6670 BaseE = ClassDecl->bases_end();
6671 BaseIt != BaseE; ++BaseIt) {
6672 if (BaseIt->getInheritConstructors()) {
6673 QualType Base = BaseIt->getType();
6674 if (Base->isDependentType()) {
6675 // If we inherit constructors from anything that is dependent, just
6676 // abort processing altogether. We'll get another chance for the
6677 // instantiations.
6678 return;
6679 }
6680 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6681 }
6682 }
6683 if (BasesToInheritFrom.empty())
6684 return;
6685
6686 // Now collect the constructors that we already have in the current class.
6687 // Those take precedence over inherited constructors.
6688 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6689 // unless there is a user-declared constructor with the same signature in
6690 // the class where the using-declaration appears.
6691 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6692 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6693 CtorE = ClassDecl->ctor_end();
6694 CtorIt != CtorE; ++CtorIt) {
6695 ExistingConstructors.insert(
6696 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6697 }
6698
6699 Scope *S = getScopeForContext(ClassDecl);
6700 DeclarationName CreatedCtorName =
6701 Context.DeclarationNames.getCXXConstructorName(
6702 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6703
6704 // Now comes the true work.
6705 // First, we keep a map from constructor types to the base that introduced
6706 // them. Needed for finding conflicting constructors. We also keep the
6707 // actually inserted declarations in there, for pretty diagnostics.
6708 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6709 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6710 ConstructorToSourceMap InheritedConstructors;
6711 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6712 BaseE = BasesToInheritFrom.end();
6713 BaseIt != BaseE; ++BaseIt) {
6714 const RecordType *Base = *BaseIt;
6715 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6716 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6717 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6718 CtorE = BaseDecl->ctor_end();
6719 CtorIt != CtorE; ++CtorIt) {
6720 // Find the using declaration for inheriting this base's constructors.
6721 DeclarationName Name =
6722 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6723 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6724 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6725 SourceLocation UsingLoc = UD ? UD->getLocation() :
6726 ClassDecl->getLocation();
6727
6728 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6729 // from the class X named in the using-declaration consists of actual
6730 // constructors and notional constructors that result from the
6731 // transformation of defaulted parameters as follows:
6732 // - all non-template default constructors of X, and
6733 // - for each non-template constructor of X that has at least one
6734 // parameter with a default argument, the set of constructors that
6735 // results from omitting any ellipsis parameter specification and
6736 // successively omitting parameters with a default argument from the
6737 // end of the parameter-type-list.
6738 CXXConstructorDecl *BaseCtor = *CtorIt;
6739 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6740 const FunctionProtoType *BaseCtorType =
6741 BaseCtor->getType()->getAs<FunctionProtoType>();
6742
6743 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6744 maxParams = BaseCtor->getNumParams();
6745 params <= maxParams; ++params) {
6746 // Skip default constructors. They're never inherited.
6747 if (params == 0)
6748 continue;
6749 // Skip copy and move constructors for the same reason.
6750 if (CanBeCopyOrMove && params == 1)
6751 continue;
6752
6753 // Build up a function type for this particular constructor.
6754 // FIXME: The working paper does not consider that the exception spec
6755 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006756 // source. This code doesn't yet, either. When it does, this code will
6757 // need to be delayed until after exception specifications and in-class
6758 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006759 const Type *NewCtorType;
6760 if (params == maxParams)
6761 NewCtorType = BaseCtorType;
6762 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006763 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006764 for (unsigned i = 0; i < params; ++i) {
6765 Args.push_back(BaseCtorType->getArgType(i));
6766 }
6767 FunctionProtoType::ExtProtoInfo ExtInfo =
6768 BaseCtorType->getExtProtoInfo();
6769 ExtInfo.Variadic = false;
6770 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6771 Args.data(), params, ExtInfo)
6772 .getTypePtr();
6773 }
6774 const Type *CanonicalNewCtorType =
6775 Context.getCanonicalType(NewCtorType);
6776
6777 // Now that we have the type, first check if the class already has a
6778 // constructor with this signature.
6779 if (ExistingConstructors.count(CanonicalNewCtorType))
6780 continue;
6781
6782 // Then we check if we have already declared an inherited constructor
6783 // with this signature.
6784 std::pair<ConstructorToSourceMap::iterator, bool> result =
6785 InheritedConstructors.insert(std::make_pair(
6786 CanonicalNewCtorType,
6787 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6788 if (!result.second) {
6789 // Already in the map. If it came from a different class, that's an
6790 // error. Not if it's from the same.
6791 CanQualType PreviousBase = result.first->second.first;
6792 if (CanonicalBase != PreviousBase) {
6793 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6794 const CXXConstructorDecl *PrevBaseCtor =
6795 PrevCtor->getInheritedConstructor();
6796 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6797
6798 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6799 Diag(BaseCtor->getLocation(),
6800 diag::note_using_decl_constructor_conflict_current_ctor);
6801 Diag(PrevBaseCtor->getLocation(),
6802 diag::note_using_decl_constructor_conflict_previous_ctor);
6803 Diag(PrevCtor->getLocation(),
6804 diag::note_using_decl_constructor_conflict_previous_using);
6805 }
6806 continue;
6807 }
6808
6809 // OK, we're there, now add the constructor.
6810 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006811 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00006812 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6813 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006814 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6815 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00006816 /*ImplicitlyDeclared=*/true,
6817 // FIXME: Due to a defect in the standard, we treat inherited
6818 // constructors as constexpr even if that makes them ill-formed.
6819 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00006820 NewCtor->setAccess(BaseCtor->getAccess());
6821
6822 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006823 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006824 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006825 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6826 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006827 /*IdentifierInfo=*/0,
6828 BaseCtorType->getArgType(i),
6829 /*TInfo=*/0, SC_None,
6830 SC_None, /*DefaultArg=*/0));
6831 }
David Blaikie4278c652011-09-21 18:16:56 +00006832 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006833 NewCtor->setInheritedConstructor(BaseCtor);
6834
6835 PushOnScopeChains(NewCtor, S, false);
6836 ClassDecl->addDecl(NewCtor);
6837 result.first->second.second = NewCtor;
6838 }
6839 }
6840 }
6841}
6842
Sean Huntcb45a0f2011-05-12 22:46:25 +00006843Sema::ImplicitExceptionSpecification
6844Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006845 // C++ [except.spec]p14:
6846 // An implicitly declared special member function (Clause 12) shall have
6847 // an exception-specification.
6848 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006849 if (ClassDecl->isInvalidDecl())
6850 return ExceptSpec;
6851
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006852 // Direct base-class destructors.
6853 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6854 BEnd = ClassDecl->bases_end();
6855 B != BEnd; ++B) {
6856 if (B->isVirtual()) // Handled below.
6857 continue;
6858
6859 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6860 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006861 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006862 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006863
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006864 // Virtual base-class destructors.
6865 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6866 BEnd = ClassDecl->vbases_end();
6867 B != BEnd; ++B) {
6868 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6869 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006870 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006871 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006872
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006873 // Field destructors.
6874 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6875 FEnd = ClassDecl->field_end();
6876 F != FEnd; ++F) {
6877 if (const RecordType *RecordTy
6878 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6879 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006880 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006881 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006882
Sean Huntcb45a0f2011-05-12 22:46:25 +00006883 return ExceptSpec;
6884}
6885
6886CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6887 // C++ [class.dtor]p2:
6888 // If a class has no user-declared destructor, a destructor is
6889 // declared implicitly. An implicitly-declared destructor is an
6890 // inline public member of its class.
6891
6892 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006893 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006894 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6895
Douglas Gregor4923aa22010-07-02 20:37:36 +00006896 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006897 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006898
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006899 CanQualType ClassType
6900 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006901 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006902 DeclarationName Name
6903 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006904 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006905 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006906 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6907 /*isInline=*/true,
6908 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006909 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006910 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006911 Destructor->setImplicit();
6912 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006913
6914 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006915 ++ASTContext::NumImplicitDestructorsDeclared;
6916
6917 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006918 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006919 PushOnScopeChains(Destructor, S, false);
6920 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006921
6922 // This could be uniqued if it ever proves significant.
6923 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006924
6925 if (ShouldDeleteDestructor(Destructor))
6926 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006927
6928 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006929
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006930 return Destructor;
6931}
6932
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006933void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006934 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006935 assert((Destructor->isDefaulted() &&
6936 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006937 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006938 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006939 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006940
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006941 if (Destructor->isInvalidDecl())
6942 return;
6943
Douglas Gregor39957dc2010-05-01 15:04:51 +00006944 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006945
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006946 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006947 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6948 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006949
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006950 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006951 Diag(CurrentLocation, diag::note_member_synthesized_at)
6952 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6953
6954 Destructor->setInvalidDecl();
6955 return;
6956 }
6957
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006958 SourceLocation Loc = Destructor->getLocation();
6959 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00006960 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006961 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006962 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006963
6964 if (ASTMutationListener *L = getASTMutationListener()) {
6965 L->CompletedImplicitDefinition(Destructor);
6966 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006967}
6968
Sebastian Redl0ee33912011-05-19 05:13:44 +00006969void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6970 CXXDestructorDecl *destructor) {
6971 // C++11 [class.dtor]p3:
6972 // A declaration of a destructor that does not have an exception-
6973 // specification is implicitly considered to have the same exception-
6974 // specification as an implicit declaration.
6975 const FunctionProtoType *dtorType = destructor->getType()->
6976 getAs<FunctionProtoType>();
6977 if (dtorType->hasExceptionSpec())
6978 return;
6979
6980 ImplicitExceptionSpecification exceptSpec =
6981 ComputeDefaultedDtorExceptionSpec(classDecl);
6982
Chandler Carruth3f224b22011-09-20 04:55:26 +00006983 // Replace the destructor's type, building off the existing one. Fortunately,
6984 // the only thing of interest in the destructor type is its extended info.
6985 // The return and arguments are fixed.
6986 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00006987 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6988 epi.NumExceptions = exceptSpec.size();
6989 epi.Exceptions = exceptSpec.data();
6990 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6991
6992 destructor->setType(ty);
6993
6994 // FIXME: If the destructor has a body that could throw, and the newly created
6995 // spec doesn't allow exceptions, we should emit a warning, because this
6996 // change in behavior can break conforming C++03 programs at runtime.
6997 // However, we don't have a body yet, so it needs to be done somewhere else.
6998}
6999
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007000/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007001/// \c To.
7002///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007003/// This routine is used to copy/move the members of a class with an
7004/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007005/// copied are arrays, this routine builds for loops to copy them.
7006///
7007/// \param S The Sema object used for type-checking.
7008///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007009/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007010///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007011/// \param T The type of the expressions being copied/moved. Both expressions
7012/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007013///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007014/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007015///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007016/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007017///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007018/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007019/// Otherwise, it's a non-static member subobject.
7020///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007021/// \param Copying Whether we're copying or moving.
7022///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007023/// \param Depth Internal parameter recording the depth of the recursion.
7024///
7025/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007026static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007027BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007028 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007029 bool CopyingBaseSubobject, bool Copying,
7030 unsigned Depth = 0) {
7031 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007032 // Each subobject is assigned in the manner appropriate to its type:
7033 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007034 // - if the subobject is of class type, as if by a call to operator= with
7035 // the subobject as the object expression and the corresponding
7036 // subobject of x as a single function argument (as if by explicit
7037 // qualification; that is, ignoring any possible virtual overriding
7038 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007039 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7040 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7041
7042 // Look for operator=.
7043 DeclarationName Name
7044 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7045 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7046 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7047
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007048 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007049 LookupResult::Filter F = OpLookup.makeFilter();
7050 while (F.hasNext()) {
7051 NamedDecl *D = F.next();
7052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007053 if (Copying ? Method->isCopyAssignmentOperator() :
7054 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007055 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007056
Douglas Gregor06a9f362010-05-01 20:49:11 +00007057 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007058 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007059 F.done();
7060
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007061 // Suppress the protected check (C++ [class.protected]) for each of the
7062 // assignment operators we found. This strange dance is required when
7063 // we're assigning via a base classes's copy-assignment operator. To
7064 // ensure that we're getting the right base class subobject (without
7065 // ambiguities), we need to cast "this" to that subobject type; to
7066 // ensure that we don't go through the virtual call mechanism, we need
7067 // to qualify the operator= name with the base class (see below). However,
7068 // this means that if the base class has a protected copy assignment
7069 // operator, the protected member access check will fail. So, we
7070 // rewrite "protected" access to "public" access in this case, since we
7071 // know by construction that we're calling from a derived class.
7072 if (CopyingBaseSubobject) {
7073 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7074 L != LEnd; ++L) {
7075 if (L.getAccess() == AS_protected)
7076 L.setAccess(AS_public);
7077 }
7078 }
7079
Douglas Gregor06a9f362010-05-01 20:49:11 +00007080 // Create the nested-name-specifier that will be used to qualify the
7081 // reference to operator=; this is required to suppress the virtual
7082 // call mechanism.
7083 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007084 SS.MakeTrivial(S.Context,
7085 NestedNameSpecifier::Create(S.Context, 0, false,
7086 T.getTypePtr()),
7087 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007088
7089 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007090 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007091 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007092 /*FirstQualifierInScope=*/0, OpLookup,
7093 /*TemplateArgs=*/0,
7094 /*SuppressQualifierCheck=*/true);
7095 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007096 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007097
7098 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007099
John McCall60d7b3a2010-08-24 06:29:42 +00007100 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007101 OpEqualRef.takeAs<Expr>(),
7102 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007103 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007104 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007105
7106 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007107 }
John McCallb0207482010-03-16 06:11:48 +00007108
Douglas Gregor06a9f362010-05-01 20:49:11 +00007109 // - if the subobject is of scalar type, the built-in assignment
7110 // operator is used.
7111 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7112 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007113 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007114 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007115 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007116
7117 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007118 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007119
7120 // - if the subobject is an array, each element is assigned, in the
7121 // manner appropriate to the element type;
7122
7123 // Construct a loop over the array bounds, e.g.,
7124 //
7125 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7126 //
7127 // that will copy each of the array elements.
7128 QualType SizeType = S.Context.getSizeType();
7129
7130 // Create the iteration variable.
7131 IdentifierInfo *IterationVarName = 0;
7132 {
7133 llvm::SmallString<8> Str;
7134 llvm::raw_svector_ostream OS(Str);
7135 OS << "__i" << Depth;
7136 IterationVarName = &S.Context.Idents.get(OS.str());
7137 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007138 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007139 IterationVarName, SizeType,
7140 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007141 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007142
7143 // Initialize the iteration variable to zero.
7144 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007145 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007146
7147 // Create a reference to the iteration variable; we'll use this several
7148 // times throughout.
7149 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00007150 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007151 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7152
7153 // Create the DeclStmt that holds the iteration variable.
7154 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7155
7156 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007157 llvm::APInt Upper
7158 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007159 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00007160 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00007161 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7162 BO_NE, S.Context.BoolTy,
7163 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007164
7165 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007166 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007167 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7168 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007169
7170 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007171 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7172 IterationVarRef, Loc));
7173 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7174 IterationVarRef, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007175 if (!Copying) // Cast to rvalue
7176 From = CastForMoving(S, From);
7177
7178 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007179 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7180 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007181 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007182 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007183 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007184
7185 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007186 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007187 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007188 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007189 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007190}
7191
Sean Hunt30de05c2011-05-14 05:23:20 +00007192std::pair<Sema::ImplicitExceptionSpecification, bool>
7193Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7194 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007195 if (ClassDecl->isInvalidDecl())
7196 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7197
Douglas Gregord3c35902010-07-01 16:36:15 +00007198 // C++ [class.copy]p10:
7199 // If the class definition does not explicitly declare a copy
7200 // assignment operator, one is declared implicitly.
7201 // The implicitly-defined copy assignment operator for a class X
7202 // will have the form
7203 //
7204 // X& X::operator=(const X&)
7205 //
7206 // if
7207 bool HasConstCopyAssignment = true;
7208
7209 // -- each direct base class B of X has a copy assignment operator
7210 // whose parameter is of type const B&, const volatile B& or B,
7211 // and
7212 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7213 BaseEnd = ClassDecl->bases_end();
7214 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007215 // We'll handle this below
7216 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7217 continue;
7218
Douglas Gregord3c35902010-07-01 16:36:15 +00007219 assert(!Base->getType()->isDependentType() &&
7220 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007221 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7222 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7223 &HasConstCopyAssignment);
7224 }
7225
7226 // In C++0x, the above citation has "or virtual added"
7227 if (LangOpts.CPlusPlus0x) {
7228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7229 BaseEnd = ClassDecl->vbases_end();
7230 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7231 assert(!Base->getType()->isDependentType() &&
7232 "Cannot generate implicit members for class with dependent bases.");
7233 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7234 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7235 &HasConstCopyAssignment);
7236 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007237 }
7238
7239 // -- for all the nonstatic data members of X that are of a class
7240 // type M (or array thereof), each such class type has a copy
7241 // assignment operator whose parameter is of type const M&,
7242 // const volatile M& or M.
7243 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7244 FieldEnd = ClassDecl->field_end();
7245 HasConstCopyAssignment && Field != FieldEnd;
7246 ++Field) {
7247 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007248 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7249 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7250 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007251 }
7252 }
7253
7254 // Otherwise, the implicitly declared copy assignment operator will
7255 // have the form
7256 //
7257 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007258
Douglas Gregorb87786f2010-07-01 17:48:08 +00007259 // C++ [except.spec]p14:
7260 // An implicitly declared special member function (Clause 12) shall have an
7261 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007262
7263 // It is unspecified whether or not an implicit copy assignment operator
7264 // attempts to deduplicate calls to assignment operators of virtual bases are
7265 // made. As such, this exception specification is effectively unspecified.
7266 // Based on a similar decision made for constness in C++0x, we're erring on
7267 // the side of assuming such calls to be made regardless of whether they
7268 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007269 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007270 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007271 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7272 BaseEnd = ClassDecl->bases_end();
7273 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007274 if (Base->isVirtual())
7275 continue;
7276
Douglas Gregora376d102010-07-02 21:50:04 +00007277 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007278 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007279 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7280 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007281 ExceptSpec.CalledDecl(CopyAssign);
7282 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007283
7284 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7285 BaseEnd = ClassDecl->vbases_end();
7286 Base != BaseEnd; ++Base) {
7287 CXXRecordDecl *BaseClassDecl
7288 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7289 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7290 ArgQuals, false, 0))
7291 ExceptSpec.CalledDecl(CopyAssign);
7292 }
7293
Douglas Gregorb87786f2010-07-01 17:48:08 +00007294 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7295 FieldEnd = ClassDecl->field_end();
7296 Field != FieldEnd;
7297 ++Field) {
7298 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007299 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7300 if (CXXMethodDecl *CopyAssign =
7301 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7302 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007303 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007304 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007305
Sean Hunt30de05c2011-05-14 05:23:20 +00007306 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7307}
7308
7309CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7310 // Note: The following rules are largely analoguous to the copy
7311 // constructor rules. Note that virtual bases are not taken into account
7312 // for determining the argument type of the operator. Note also that
7313 // operators taking an object instead of a reference are allowed.
7314
7315 ImplicitExceptionSpecification Spec(Context);
7316 bool Const;
7317 llvm::tie(Spec, Const) =
7318 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7319
7320 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7321 QualType RetType = Context.getLValueReferenceType(ArgType);
7322 if (Const)
7323 ArgType = ArgType.withConst();
7324 ArgType = Context.getLValueReferenceType(ArgType);
7325
Douglas Gregord3c35902010-07-01 16:36:15 +00007326 // An implicitly-declared copy assignment operator is an inline public
7327 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007328 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007329 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007330 SourceLocation ClassLoc = ClassDecl->getLocation();
7331 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007332 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007333 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007334 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007335 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007336 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007337 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007338 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007339 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007340 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007341 CopyAssignment->setImplicit();
7342 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007343
7344 // Add the parameter to the operator.
7345 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007346 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007347 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007348 SC_None,
7349 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007350 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007351
Douglas Gregora376d102010-07-02 21:50:04 +00007352 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007353 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007354
Douglas Gregor23c94db2010-07-02 17:43:08 +00007355 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007356 PushOnScopeChains(CopyAssignment, S, false);
7357 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007358
Sean Hunt1ccbc542011-06-22 01:05:13 +00007359 // C++0x [class.copy]p18:
7360 // ... If the class definition declares a move constructor or move
7361 // assignment operator, the implicitly declared copy assignment operator is
7362 // defined as deleted; ...
7363 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7364 ClassDecl->hasUserDeclaredMoveAssignment() ||
7365 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007366 CopyAssignment->setDeletedAsWritten();
7367
Douglas Gregord3c35902010-07-01 16:36:15 +00007368 AddOverriddenMethods(ClassDecl, CopyAssignment);
7369 return CopyAssignment;
7370}
7371
Douglas Gregor06a9f362010-05-01 20:49:11 +00007372void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7373 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007374 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007375 CopyAssignOperator->isOverloadedOperator() &&
7376 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007377 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007378 "DefineImplicitCopyAssignment called for wrong function");
7379
7380 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7381
7382 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7383 CopyAssignOperator->setInvalidDecl();
7384 return;
7385 }
7386
7387 CopyAssignOperator->setUsed();
7388
7389 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007390 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007391
7392 // C++0x [class.copy]p30:
7393 // The implicitly-defined or explicitly-defaulted copy assignment operator
7394 // for a non-union class X performs memberwise copy assignment of its
7395 // subobjects. The direct base classes of X are assigned first, in the
7396 // order of their declaration in the base-specifier-list, and then the
7397 // immediate non-static data members of X are assigned, in the order in
7398 // which they were declared in the class definition.
7399
7400 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007401 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007402
7403 // The parameter for the "other" object, which we are copying from.
7404 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7405 Qualifiers OtherQuals = Other->getType().getQualifiers();
7406 QualType OtherRefType = Other->getType();
7407 if (const LValueReferenceType *OtherRef
7408 = OtherRefType->getAs<LValueReferenceType>()) {
7409 OtherRefType = OtherRef->getPointeeType();
7410 OtherQuals = OtherRefType.getQualifiers();
7411 }
7412
7413 // Our location for everything implicitly-generated.
7414 SourceLocation Loc = CopyAssignOperator->getLocation();
7415
7416 // Construct a reference to the "other" object. We'll be using this
7417 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007418 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007419 assert(OtherRef && "Reference to parameter cannot fail!");
7420
7421 // Construct the "this" pointer. We'll be using this throughout the generated
7422 // ASTs.
7423 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7424 assert(This && "Reference to this cannot fail!");
7425
7426 // Assign base classes.
7427 bool Invalid = false;
7428 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7429 E = ClassDecl->bases_end(); Base != E; ++Base) {
7430 // Form the assignment:
7431 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7432 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007433 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007434 Invalid = true;
7435 continue;
7436 }
7437
John McCallf871d0c2010-08-07 06:22:56 +00007438 CXXCastPath BasePath;
7439 BasePath.push_back(Base);
7440
Douglas Gregor06a9f362010-05-01 20:49:11 +00007441 // Construct the "from" expression, which is an implicit cast to the
7442 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007443 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007444 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7445 CK_UncheckedDerivedToBase,
7446 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007447
7448 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007449 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007450
7451 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007452 To = ImpCastExprToType(To.take(),
7453 Context.getCVRQualifiedType(BaseType,
7454 CopyAssignOperator->getTypeQualifiers()),
7455 CK_UncheckedDerivedToBase,
7456 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007457
7458 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007459 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007460 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007461 /*CopyingBaseSubobject=*/true,
7462 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007463 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007464 Diag(CurrentLocation, diag::note_member_synthesized_at)
7465 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7466 CopyAssignOperator->setInvalidDecl();
7467 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007468 }
7469
7470 // Success! Record the copy.
7471 Statements.push_back(Copy.takeAs<Expr>());
7472 }
7473
7474 // \brief Reference to the __builtin_memcpy function.
7475 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007476 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007477 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007478
7479 // Assign non-static members.
7480 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7481 FieldEnd = ClassDecl->field_end();
7482 Field != FieldEnd; ++Field) {
7483 // Check for members of reference type; we can't copy those.
7484 if (Field->getType()->isReferenceType()) {
7485 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7486 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7487 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007488 Diag(CurrentLocation, diag::note_member_synthesized_at)
7489 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007490 Invalid = true;
7491 continue;
7492 }
7493
7494 // Check for members of const-qualified, non-class type.
7495 QualType BaseType = Context.getBaseElementType(Field->getType());
7496 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7497 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7498 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7499 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007500 Diag(CurrentLocation, diag::note_member_synthesized_at)
7501 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007502 Invalid = true;
7503 continue;
7504 }
John McCallb77115d2011-06-17 00:18:42 +00007505
7506 // Suppress assigning zero-width bitfields.
7507 if (const Expr *Width = Field->getBitWidth())
7508 if (Width->EvaluateAsInt(Context) == 0)
7509 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007510
7511 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007512 if (FieldType->isIncompleteArrayType()) {
7513 assert(ClassDecl->hasFlexibleArrayMember() &&
7514 "Incomplete array type is not valid");
7515 continue;
7516 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007517
7518 // Build references to the field in the object we're copying from and to.
7519 CXXScopeSpec SS; // Intentionally empty
7520 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7521 LookupMemberName);
7522 MemberLookup.addDecl(*Field);
7523 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007524 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007525 Loc, /*IsArrow=*/false,
7526 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007527 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007528 Loc, /*IsArrow=*/true,
7529 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007530 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7531 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7532
7533 // If the field should be copied with __builtin_memcpy rather than via
7534 // explicit assignments, do so. This optimization only applies for arrays
7535 // of scalars and arrays of class type with trivial copy-assignment
7536 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007537 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007538 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007539 // Compute the size of the memory buffer to be copied.
7540 QualType SizeType = Context.getSizeType();
7541 llvm::APInt Size(Context.getTypeSize(SizeType),
7542 Context.getTypeSizeInChars(BaseType).getQuantity());
7543 for (const ConstantArrayType *Array
7544 = Context.getAsConstantArrayType(FieldType);
7545 Array;
7546 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007547 llvm::APInt ArraySize
7548 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007549 Size *= ArraySize;
7550 }
7551
7552 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007553 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7554 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007555
7556 bool NeedsCollectableMemCpy =
7557 (BaseType->isRecordType() &&
7558 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7559
7560 if (NeedsCollectableMemCpy) {
7561 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007562 // Create a reference to the __builtin_objc_memmove_collectable function.
7563 LookupResult R(*this,
7564 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007565 Loc, LookupOrdinaryName);
7566 LookupName(R, TUScope, true);
7567
7568 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7569 if (!CollectableMemCpy) {
7570 // Something went horribly wrong earlier, and we will have
7571 // complained about it.
7572 Invalid = true;
7573 continue;
7574 }
7575
7576 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7577 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007578 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007579 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7580 }
7581 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007582 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007583 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007584 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7585 LookupOrdinaryName);
7586 LookupName(R, TUScope, true);
7587
7588 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7589 if (!BuiltinMemCpy) {
7590 // Something went horribly wrong earlier, and we will have complained
7591 // about it.
7592 Invalid = true;
7593 continue;
7594 }
7595
7596 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7597 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007598 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007599 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7600 }
7601
John McCallca0408f2010-08-23 06:44:23 +00007602 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007603 CallArgs.push_back(To.takeAs<Expr>());
7604 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007605 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007606 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007607 if (NeedsCollectableMemCpy)
7608 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007609 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007610 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007611 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007612 else
7613 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007614 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007615 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007616 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007617
Douglas Gregor06a9f362010-05-01 20:49:11 +00007618 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7619 Statements.push_back(Call.takeAs<Expr>());
7620 continue;
7621 }
7622
7623 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007624 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007625 To.get(), From.get(),
7626 /*CopyingBaseSubobject=*/false,
7627 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007628 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007629 Diag(CurrentLocation, diag::note_member_synthesized_at)
7630 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7631 CopyAssignOperator->setInvalidDecl();
7632 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007633 }
7634
7635 // Success! Record the copy.
7636 Statements.push_back(Copy.takeAs<Stmt>());
7637 }
7638
7639 if (!Invalid) {
7640 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007641 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007642
John McCall60d7b3a2010-08-24 06:29:42 +00007643 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007644 if (Return.isInvalid())
7645 Invalid = true;
7646 else {
7647 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007648
7649 if (Trap.hasErrorOccurred()) {
7650 Diag(CurrentLocation, diag::note_member_synthesized_at)
7651 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7652 Invalid = true;
7653 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007654 }
7655 }
7656
7657 if (Invalid) {
7658 CopyAssignOperator->setInvalidDecl();
7659 return;
7660 }
7661
John McCall60d7b3a2010-08-24 06:29:42 +00007662 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007663 /*isStmtExpr=*/false);
7664 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7665 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007666
7667 if (ASTMutationListener *L = getASTMutationListener()) {
7668 L->CompletedImplicitDefinition(CopyAssignOperator);
7669 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007670}
7671
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007672Sema::ImplicitExceptionSpecification
7673Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7674 ImplicitExceptionSpecification ExceptSpec(Context);
7675
7676 if (ClassDecl->isInvalidDecl())
7677 return ExceptSpec;
7678
7679 // C++0x [except.spec]p14:
7680 // An implicitly declared special member function (Clause 12) shall have an
7681 // exception-specification. [...]
7682
7683 // It is unspecified whether or not an implicit move assignment operator
7684 // attempts to deduplicate calls to assignment operators of virtual bases are
7685 // made. As such, this exception specification is effectively unspecified.
7686 // Based on a similar decision made for constness in C++0x, we're erring on
7687 // the side of assuming such calls to be made regardless of whether they
7688 // actually happen.
7689 // Note that a move constructor is not implicitly declared when there are
7690 // virtual bases, but it can still be user-declared and explicitly defaulted.
7691 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7692 BaseEnd = ClassDecl->bases_end();
7693 Base != BaseEnd; ++Base) {
7694 if (Base->isVirtual())
7695 continue;
7696
7697 CXXRecordDecl *BaseClassDecl
7698 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7699 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7700 false, 0))
7701 ExceptSpec.CalledDecl(MoveAssign);
7702 }
7703
7704 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7705 BaseEnd = ClassDecl->vbases_end();
7706 Base != BaseEnd; ++Base) {
7707 CXXRecordDecl *BaseClassDecl
7708 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7709 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7710 false, 0))
7711 ExceptSpec.CalledDecl(MoveAssign);
7712 }
7713
7714 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7715 FieldEnd = ClassDecl->field_end();
7716 Field != FieldEnd;
7717 ++Field) {
7718 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7719 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7720 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7721 false, 0))
7722 ExceptSpec.CalledDecl(MoveAssign);
7723 }
7724 }
7725
7726 return ExceptSpec;
7727}
7728
7729CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7730 // Note: The following rules are largely analoguous to the move
7731 // constructor rules.
7732
7733 ImplicitExceptionSpecification Spec(
7734 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7735
7736 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7737 QualType RetType = Context.getLValueReferenceType(ArgType);
7738 ArgType = Context.getRValueReferenceType(ArgType);
7739
7740 // An implicitly-declared move assignment operator is an inline public
7741 // member of its class.
7742 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7743 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7744 SourceLocation ClassLoc = ClassDecl->getLocation();
7745 DeclarationNameInfo NameInfo(Name, ClassLoc);
7746 CXXMethodDecl *MoveAssignment
7747 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7748 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7749 /*TInfo=*/0, /*isStatic=*/false,
7750 /*StorageClassAsWritten=*/SC_None,
7751 /*isInline=*/true,
7752 /*isConstexpr=*/false,
7753 SourceLocation());
7754 MoveAssignment->setAccess(AS_public);
7755 MoveAssignment->setDefaulted();
7756 MoveAssignment->setImplicit();
7757 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7758
7759 // Add the parameter to the operator.
7760 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7761 ClassLoc, ClassLoc, /*Id=*/0,
7762 ArgType, /*TInfo=*/0,
7763 SC_None,
7764 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007765 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007766
7767 // Note that we have added this copy-assignment operator.
7768 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7769
7770 // C++0x [class.copy]p9:
7771 // If the definition of a class X does not explicitly declare a move
7772 // assignment operator, one will be implicitly declared as defaulted if and
7773 // only if:
7774 // [...]
7775 // - the move assignment operator would not be implicitly defined as
7776 // deleted.
7777 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7778 // Cache this result so that we don't try to generate this over and over
7779 // on every lookup, leaking memory and wasting time.
7780 ClassDecl->setFailedImplicitMoveAssignment();
7781 return 0;
7782 }
7783
7784 if (Scope *S = getScopeForContext(ClassDecl))
7785 PushOnScopeChains(MoveAssignment, S, false);
7786 ClassDecl->addDecl(MoveAssignment);
7787
7788 AddOverriddenMethods(ClassDecl, MoveAssignment);
7789 return MoveAssignment;
7790}
7791
7792void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7793 CXXMethodDecl *MoveAssignOperator) {
7794 assert((MoveAssignOperator->isDefaulted() &&
7795 MoveAssignOperator->isOverloadedOperator() &&
7796 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7797 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7798 "DefineImplicitMoveAssignment called for wrong function");
7799
7800 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7801
7802 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7803 MoveAssignOperator->setInvalidDecl();
7804 return;
7805 }
7806
7807 MoveAssignOperator->setUsed();
7808
7809 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7810 DiagnosticErrorTrap Trap(Diags);
7811
7812 // C++0x [class.copy]p28:
7813 // The implicitly-defined or move assignment operator for a non-union class
7814 // X performs memberwise move assignment of its subobjects. The direct base
7815 // classes of X are assigned first, in the order of their declaration in the
7816 // base-specifier-list, and then the immediate non-static data members of X
7817 // are assigned, in the order in which they were declared in the class
7818 // definition.
7819
7820 // The statements that form the synthesized function body.
7821 ASTOwningVector<Stmt*> Statements(*this);
7822
7823 // The parameter for the "other" object, which we are move from.
7824 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7825 QualType OtherRefType = Other->getType()->
7826 getAs<RValueReferenceType>()->getPointeeType();
7827 assert(OtherRefType.getQualifiers() == 0 &&
7828 "Bad argument type of defaulted move assignment");
7829
7830 // Our location for everything implicitly-generated.
7831 SourceLocation Loc = MoveAssignOperator->getLocation();
7832
7833 // Construct a reference to the "other" object. We'll be using this
7834 // throughout the generated ASTs.
7835 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7836 assert(OtherRef && "Reference to parameter cannot fail!");
7837 // Cast to rvalue.
7838 OtherRef = CastForMoving(*this, OtherRef);
7839
7840 // Construct the "this" pointer. We'll be using this throughout the generated
7841 // ASTs.
7842 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7843 assert(This && "Reference to this cannot fail!");
7844
7845 // Assign base classes.
7846 bool Invalid = false;
7847 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7848 E = ClassDecl->bases_end(); Base != E; ++Base) {
7849 // Form the assignment:
7850 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7851 QualType BaseType = Base->getType().getUnqualifiedType();
7852 if (!BaseType->isRecordType()) {
7853 Invalid = true;
7854 continue;
7855 }
7856
7857 CXXCastPath BasePath;
7858 BasePath.push_back(Base);
7859
7860 // Construct the "from" expression, which is an implicit cast to the
7861 // appropriately-qualified base type.
7862 Expr *From = OtherRef;
7863 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00007864 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007865
7866 // Dereference "this".
7867 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7868
7869 // Implicitly cast "this" to the appropriately-qualified base type.
7870 To = ImpCastExprToType(To.take(),
7871 Context.getCVRQualifiedType(BaseType,
7872 MoveAssignOperator->getTypeQualifiers()),
7873 CK_UncheckedDerivedToBase,
7874 VK_LValue, &BasePath);
7875
7876 // Build the move.
7877 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7878 To.get(), From,
7879 /*CopyingBaseSubobject=*/true,
7880 /*Copying=*/false);
7881 if (Move.isInvalid()) {
7882 Diag(CurrentLocation, diag::note_member_synthesized_at)
7883 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7884 MoveAssignOperator->setInvalidDecl();
7885 return;
7886 }
7887
7888 // Success! Record the move.
7889 Statements.push_back(Move.takeAs<Expr>());
7890 }
7891
7892 // \brief Reference to the __builtin_memcpy function.
7893 Expr *BuiltinMemCpyRef = 0;
7894 // \brief Reference to the __builtin_objc_memmove_collectable function.
7895 Expr *CollectableMemCpyRef = 0;
7896
7897 // Assign non-static members.
7898 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7899 FieldEnd = ClassDecl->field_end();
7900 Field != FieldEnd; ++Field) {
7901 // Check for members of reference type; we can't move those.
7902 if (Field->getType()->isReferenceType()) {
7903 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7904 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7905 Diag(Field->getLocation(), diag::note_declared_at);
7906 Diag(CurrentLocation, diag::note_member_synthesized_at)
7907 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7908 Invalid = true;
7909 continue;
7910 }
7911
7912 // Check for members of const-qualified, non-class type.
7913 QualType BaseType = Context.getBaseElementType(Field->getType());
7914 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7915 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7916 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7917 Diag(Field->getLocation(), diag::note_declared_at);
7918 Diag(CurrentLocation, diag::note_member_synthesized_at)
7919 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7920 Invalid = true;
7921 continue;
7922 }
7923
7924 // Suppress assigning zero-width bitfields.
7925 if (const Expr *Width = Field->getBitWidth())
7926 if (Width->EvaluateAsInt(Context) == 0)
7927 continue;
7928
7929 QualType FieldType = Field->getType().getNonReferenceType();
7930 if (FieldType->isIncompleteArrayType()) {
7931 assert(ClassDecl->hasFlexibleArrayMember() &&
7932 "Incomplete array type is not valid");
7933 continue;
7934 }
7935
7936 // Build references to the field in the object we're copying from and to.
7937 CXXScopeSpec SS; // Intentionally empty
7938 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7939 LookupMemberName);
7940 MemberLookup.addDecl(*Field);
7941 MemberLookup.resolveKind();
7942 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7943 Loc, /*IsArrow=*/false,
7944 SS, 0, MemberLookup, 0);
7945 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7946 Loc, /*IsArrow=*/true,
7947 SS, 0, MemberLookup, 0);
7948 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7949 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7950
7951 assert(!From.get()->isLValue() && // could be xvalue or prvalue
7952 "Member reference with rvalue base must be rvalue except for reference "
7953 "members, which aren't allowed for move assignment.");
7954
7955 // If the field should be copied with __builtin_memcpy rather than via
7956 // explicit assignments, do so. This optimization only applies for arrays
7957 // of scalars and arrays of class type with trivial move-assignment
7958 // operators.
7959 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7960 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7961 // Compute the size of the memory buffer to be copied.
7962 QualType SizeType = Context.getSizeType();
7963 llvm::APInt Size(Context.getTypeSize(SizeType),
7964 Context.getTypeSizeInChars(BaseType).getQuantity());
7965 for (const ConstantArrayType *Array
7966 = Context.getAsConstantArrayType(FieldType);
7967 Array;
7968 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7969 llvm::APInt ArraySize
7970 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7971 Size *= ArraySize;
7972 }
7973
Douglas Gregor45d3d712011-09-01 02:09:07 +00007974 // Take the address of the field references for "from" and "to". We
7975 // directly construct UnaryOperators here because semantic analysis
7976 // does not permit us to take the address of an xvalue.
7977 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
7978 Context.getPointerType(From.get()->getType()),
7979 VK_RValue, OK_Ordinary, Loc);
7980 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
7981 Context.getPointerType(To.get()->getType()),
7982 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007983
7984 bool NeedsCollectableMemCpy =
7985 (BaseType->isRecordType() &&
7986 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7987
7988 if (NeedsCollectableMemCpy) {
7989 if (!CollectableMemCpyRef) {
7990 // Create a reference to the __builtin_objc_memmove_collectable function.
7991 LookupResult R(*this,
7992 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7993 Loc, LookupOrdinaryName);
7994 LookupName(R, TUScope, true);
7995
7996 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7997 if (!CollectableMemCpy) {
7998 // Something went horribly wrong earlier, and we will have
7999 // complained about it.
8000 Invalid = true;
8001 continue;
8002 }
8003
8004 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8005 CollectableMemCpy->getType(),
8006 VK_LValue, Loc, 0).take();
8007 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8008 }
8009 }
8010 // Create a reference to the __builtin_memcpy builtin function.
8011 else if (!BuiltinMemCpyRef) {
8012 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8013 LookupOrdinaryName);
8014 LookupName(R, TUScope, true);
8015
8016 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8017 if (!BuiltinMemCpy) {
8018 // Something went horribly wrong earlier, and we will have complained
8019 // about it.
8020 Invalid = true;
8021 continue;
8022 }
8023
8024 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8025 BuiltinMemCpy->getType(),
8026 VK_LValue, Loc, 0).take();
8027 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8028 }
8029
8030 ASTOwningVector<Expr*> CallArgs(*this);
8031 CallArgs.push_back(To.takeAs<Expr>());
8032 CallArgs.push_back(From.takeAs<Expr>());
8033 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8034 ExprResult Call = ExprError();
8035 if (NeedsCollectableMemCpy)
8036 Call = ActOnCallExpr(/*Scope=*/0,
8037 CollectableMemCpyRef,
8038 Loc, move_arg(CallArgs),
8039 Loc);
8040 else
8041 Call = ActOnCallExpr(/*Scope=*/0,
8042 BuiltinMemCpyRef,
8043 Loc, move_arg(CallArgs),
8044 Loc);
8045
8046 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8047 Statements.push_back(Call.takeAs<Expr>());
8048 continue;
8049 }
8050
8051 // Build the move of this field.
8052 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8053 To.get(), From.get(),
8054 /*CopyingBaseSubobject=*/false,
8055 /*Copying=*/false);
8056 if (Move.isInvalid()) {
8057 Diag(CurrentLocation, diag::note_member_synthesized_at)
8058 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8059 MoveAssignOperator->setInvalidDecl();
8060 return;
8061 }
8062
8063 // Success! Record the copy.
8064 Statements.push_back(Move.takeAs<Stmt>());
8065 }
8066
8067 if (!Invalid) {
8068 // Add a "return *this;"
8069 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8070
8071 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8072 if (Return.isInvalid())
8073 Invalid = true;
8074 else {
8075 Statements.push_back(Return.takeAs<Stmt>());
8076
8077 if (Trap.hasErrorOccurred()) {
8078 Diag(CurrentLocation, diag::note_member_synthesized_at)
8079 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8080 Invalid = true;
8081 }
8082 }
8083 }
8084
8085 if (Invalid) {
8086 MoveAssignOperator->setInvalidDecl();
8087 return;
8088 }
8089
8090 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8091 /*isStmtExpr=*/false);
8092 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8093 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8094
8095 if (ASTMutationListener *L = getASTMutationListener()) {
8096 L->CompletedImplicitDefinition(MoveAssignOperator);
8097 }
8098}
8099
Sean Hunt49634cf2011-05-13 06:10:58 +00008100std::pair<Sema::ImplicitExceptionSpecification, bool>
8101Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008102 if (ClassDecl->isInvalidDecl())
8103 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8104
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008105 // C++ [class.copy]p5:
8106 // The implicitly-declared copy constructor for a class X will
8107 // have the form
8108 //
8109 // X::X(const X&)
8110 //
8111 // if
Sean Huntc530d172011-06-10 04:44:37 +00008112 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008113 bool HasConstCopyConstructor = true;
8114
8115 // -- each direct or virtual base class B of X has a copy
8116 // constructor whose first parameter is of type const B& or
8117 // const volatile B&, and
8118 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8119 BaseEnd = ClassDecl->bases_end();
8120 HasConstCopyConstructor && Base != BaseEnd;
8121 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008122 // Virtual bases are handled below.
8123 if (Base->isVirtual())
8124 continue;
8125
Douglas Gregor22584312010-07-02 23:41:54 +00008126 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008127 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008128 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8129 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008130 }
8131
8132 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8133 BaseEnd = ClassDecl->vbases_end();
8134 HasConstCopyConstructor && Base != BaseEnd;
8135 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008136 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008137 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008138 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8139 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008140 }
8141
8142 // -- for all the nonstatic data members of X that are of a
8143 // class type M (or array thereof), each such class type
8144 // has a copy constructor whose first parameter is of type
8145 // const M& or const volatile M&.
8146 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8147 FieldEnd = ClassDecl->field_end();
8148 HasConstCopyConstructor && Field != FieldEnd;
8149 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008150 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008151 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008152 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8153 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008154 }
8155 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008156 // Otherwise, the implicitly declared copy constructor will have
8157 // the form
8158 //
8159 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008160
Douglas Gregor0d405db2010-07-01 20:59:04 +00008161 // C++ [except.spec]p14:
8162 // An implicitly declared special member function (Clause 12) shall have an
8163 // exception-specification. [...]
8164 ImplicitExceptionSpecification ExceptSpec(Context);
8165 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8166 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8167 BaseEnd = ClassDecl->bases_end();
8168 Base != BaseEnd;
8169 ++Base) {
8170 // Virtual bases are handled below.
8171 if (Base->isVirtual())
8172 continue;
8173
Douglas Gregor22584312010-07-02 23:41:54 +00008174 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008175 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008176 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008177 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008178 ExceptSpec.CalledDecl(CopyConstructor);
8179 }
8180 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8181 BaseEnd = ClassDecl->vbases_end();
8182 Base != BaseEnd;
8183 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008184 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008185 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008186 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008187 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008188 ExceptSpec.CalledDecl(CopyConstructor);
8189 }
8190 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8191 FieldEnd = ClassDecl->field_end();
8192 Field != FieldEnd;
8193 ++Field) {
8194 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008195 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8196 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008197 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008198 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008199 }
8200 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008201
Sean Hunt49634cf2011-05-13 06:10:58 +00008202 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8203}
8204
8205CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8206 CXXRecordDecl *ClassDecl) {
8207 // C++ [class.copy]p4:
8208 // If the class definition does not explicitly declare a copy
8209 // constructor, one is declared implicitly.
8210
8211 ImplicitExceptionSpecification Spec(Context);
8212 bool Const;
8213 llvm::tie(Spec, Const) =
8214 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8215
8216 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8217 QualType ArgType = ClassType;
8218 if (Const)
8219 ArgType = ArgType.withConst();
8220 ArgType = Context.getLValueReferenceType(ArgType);
8221
8222 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8223
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008224 DeclarationName Name
8225 = Context.DeclarationNames.getCXXConstructorName(
8226 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008227 SourceLocation ClassLoc = ClassDecl->getLocation();
8228 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008229
8230 // An implicitly-declared copy constructor is an inline public
8231 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008232 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008233 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008234 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00008235 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008236 /*TInfo=*/0,
8237 /*isExplicit=*/false,
8238 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008239 /*isImplicitlyDeclared=*/true,
8240 // FIXME: apply the rules for definitions here
8241 /*isConstexpr=*/false);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008242 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008243 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008244 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8245
Douglas Gregor22584312010-07-02 23:41:54 +00008246 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008247 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8248
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008249 // Add the parameter to the constructor.
8250 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008251 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008252 /*IdentifierInfo=*/0,
8253 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008254 SC_None,
8255 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008256 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008257
Douglas Gregor23c94db2010-07-02 17:43:08 +00008258 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008259 PushOnScopeChains(CopyConstructor, S, false);
8260 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008261
Sean Hunt1ccbc542011-06-22 01:05:13 +00008262 // C++0x [class.copy]p7:
8263 // ... If the class definition declares a move constructor or move
8264 // assignment operator, the implicitly declared constructor is defined as
8265 // deleted; ...
8266 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8267 ClassDecl->hasUserDeclaredMoveAssignment() ||
8268 ShouldDeleteCopyConstructor(CopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008269 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008270
8271 return CopyConstructor;
8272}
8273
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008274void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008275 CXXConstructorDecl *CopyConstructor) {
8276 assert((CopyConstructor->isDefaulted() &&
8277 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008278 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008279 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008280
Anders Carlsson63010a72010-04-23 16:24:12 +00008281 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008282 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008283
Douglas Gregor39957dc2010-05-01 15:04:51 +00008284 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008285 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008286
Sean Huntcbb67482011-01-08 20:30:50 +00008287 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008288 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008289 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008290 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008291 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008292 } else {
8293 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8294 CopyConstructor->getLocation(),
8295 MultiStmtArg(*this, 0, 0),
8296 /*isStmtExpr=*/false)
8297 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008298 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008299 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008300
8301 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008302 if (ASTMutationListener *L = getASTMutationListener()) {
8303 L->CompletedImplicitDefinition(CopyConstructor);
8304 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008305}
8306
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008307Sema::ImplicitExceptionSpecification
8308Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8309 // C++ [except.spec]p14:
8310 // An implicitly declared special member function (Clause 12) shall have an
8311 // exception-specification. [...]
8312 ImplicitExceptionSpecification ExceptSpec(Context);
8313 if (ClassDecl->isInvalidDecl())
8314 return ExceptSpec;
8315
8316 // Direct base-class constructors.
8317 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8318 BEnd = ClassDecl->bases_end();
8319 B != BEnd; ++B) {
8320 if (B->isVirtual()) // Handled below.
8321 continue;
8322
8323 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8324 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8325 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8326 // If this is a deleted function, add it anyway. This might be conformant
8327 // with the standard. This might not. I'm not sure. It might not matter.
8328 if (Constructor)
8329 ExceptSpec.CalledDecl(Constructor);
8330 }
8331 }
8332
8333 // Virtual base-class constructors.
8334 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8335 BEnd = ClassDecl->vbases_end();
8336 B != BEnd; ++B) {
8337 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8338 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8339 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8340 // If this is a deleted function, add it anyway. This might be conformant
8341 // with the standard. This might not. I'm not sure. It might not matter.
8342 if (Constructor)
8343 ExceptSpec.CalledDecl(Constructor);
8344 }
8345 }
8346
8347 // Field constructors.
8348 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8349 FEnd = ClassDecl->field_end();
8350 F != FEnd; ++F) {
8351 if (F->hasInClassInitializer()) {
8352 if (Expr *E = F->getInClassInitializer())
8353 ExceptSpec.CalledExpr(E);
8354 else if (!F->isInvalidDecl())
8355 ExceptSpec.SetDelayed();
8356 } else if (const RecordType *RecordTy
8357 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8358 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8359 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8360 // If this is a deleted function, add it anyway. This might be conformant
8361 // with the standard. This might not. I'm not sure. It might not matter.
8362 // In particular, the problem is that this function never gets called. It
8363 // might just be ill-formed because this function attempts to refer to
8364 // a deleted function here.
8365 if (Constructor)
8366 ExceptSpec.CalledDecl(Constructor);
8367 }
8368 }
8369
8370 return ExceptSpec;
8371}
8372
8373CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8374 CXXRecordDecl *ClassDecl) {
8375 ImplicitExceptionSpecification Spec(
8376 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8377
8378 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8379 QualType ArgType = Context.getRValueReferenceType(ClassType);
8380
8381 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8382
8383 DeclarationName Name
8384 = Context.DeclarationNames.getCXXConstructorName(
8385 Context.getCanonicalType(ClassType));
8386 SourceLocation ClassLoc = ClassDecl->getLocation();
8387 DeclarationNameInfo NameInfo(Name, ClassLoc);
8388
8389 // C++0x [class.copy]p11:
8390 // An implicitly-declared copy/move constructor is an inline public
8391 // member of its class.
8392 CXXConstructorDecl *MoveConstructor
8393 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8394 Context.getFunctionType(Context.VoidTy,
8395 &ArgType, 1, EPI),
8396 /*TInfo=*/0,
8397 /*isExplicit=*/false,
8398 /*isInline=*/true,
8399 /*isImplicitlyDeclared=*/true,
8400 // FIXME: apply the rules for definitions here
8401 /*isConstexpr=*/false);
8402 MoveConstructor->setAccess(AS_public);
8403 MoveConstructor->setDefaulted();
8404 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8405
8406 // Add the parameter to the constructor.
8407 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8408 ClassLoc, ClassLoc,
8409 /*IdentifierInfo=*/0,
8410 ArgType, /*TInfo=*/0,
8411 SC_None,
8412 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008413 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008414
8415 // C++0x [class.copy]p9:
8416 // If the definition of a class X does not explicitly declare a move
8417 // constructor, one will be implicitly declared as defaulted if and only if:
8418 // [...]
8419 // - the move constructor would not be implicitly defined as deleted.
8420 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8421 // Cache this result so that we don't try to generate this over and over
8422 // on every lookup, leaking memory and wasting time.
8423 ClassDecl->setFailedImplicitMoveConstructor();
8424 return 0;
8425 }
8426
8427 // Note that we have declared this constructor.
8428 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8429
8430 if (Scope *S = getScopeForContext(ClassDecl))
8431 PushOnScopeChains(MoveConstructor, S, false);
8432 ClassDecl->addDecl(MoveConstructor);
8433
8434 return MoveConstructor;
8435}
8436
8437void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8438 CXXConstructorDecl *MoveConstructor) {
8439 assert((MoveConstructor->isDefaulted() &&
8440 MoveConstructor->isMoveConstructor() &&
8441 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8442 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8443
8444 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8445 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8446
8447 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8448 DiagnosticErrorTrap Trap(Diags);
8449
8450 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8451 Trap.hasErrorOccurred()) {
8452 Diag(CurrentLocation, diag::note_member_synthesized_at)
8453 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8454 MoveConstructor->setInvalidDecl();
8455 } else {
8456 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8457 MoveConstructor->getLocation(),
8458 MultiStmtArg(*this, 0, 0),
8459 /*isStmtExpr=*/false)
8460 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008461 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008462 }
8463
8464 MoveConstructor->setUsed();
8465
8466 if (ASTMutationListener *L = getASTMutationListener()) {
8467 L->CompletedImplicitDefinition(MoveConstructor);
8468 }
8469}
8470
John McCall60d7b3a2010-08-24 06:29:42 +00008471ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008472Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008473 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008474 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008475 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008476 unsigned ConstructKind,
8477 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008478 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008479
Douglas Gregor2f599792010-04-02 18:24:57 +00008480 // C++0x [class.copy]p34:
8481 // When certain criteria are met, an implementation is allowed to
8482 // omit the copy/move construction of a class object, even if the
8483 // copy/move constructor and/or destructor for the object have
8484 // side effects. [...]
8485 // - when a temporary class object that has not been bound to a
8486 // reference (12.2) would be copied/moved to a class object
8487 // with the same cv-unqualified type, the copy/move operation
8488 // can be omitted by constructing the temporary object
8489 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008490 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008491 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008492 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008493 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008494 }
Mike Stump1eb44332009-09-09 15:08:12 +00008495
8496 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008497 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008498 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008499}
8500
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008501/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8502/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008503ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008504Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8505 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008506 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008507 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008508 unsigned ConstructKind,
8509 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008510 unsigned NumExprs = ExprArgs.size();
8511 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008512
Nick Lewycky909a70d2011-03-25 01:44:32 +00008513 for (specific_attr_iterator<NonNullAttr>
8514 i = Constructor->specific_attr_begin<NonNullAttr>(),
8515 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8516 const NonNullAttr *NonNull = *i;
8517 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8518 }
8519
Douglas Gregor7edfb692009-11-23 12:27:39 +00008520 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008521 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00008522 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00008523 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008524 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8525 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008526}
8527
Mike Stump1eb44332009-09-09 15:08:12 +00008528bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008529 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00008530 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008531 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008532 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008533 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008534 move(Exprs), false, CXXConstructExpr::CK_Complete,
8535 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008536 if (TempResult.isInvalid())
8537 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008538
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008539 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008540 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008541 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008542 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008543 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008544
Anders Carlssonfe2de492009-08-25 05:18:00 +00008545 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008546}
8547
John McCall68c6c9a2010-02-02 09:10:11 +00008548void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008549 if (VD->isInvalidDecl()) return;
8550
John McCall68c6c9a2010-02-02 09:10:11 +00008551 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008552 if (ClassDecl->isInvalidDecl()) return;
8553 if (ClassDecl->hasTrivialDestructor()) return;
8554 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008555
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008556 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8557 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8558 CheckDestructorAccess(VD->getLocation(), Destructor,
8559 PDiag(diag::err_access_dtor_var)
8560 << VD->getDeclName()
8561 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008562
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008563 if (!VD->hasGlobalStorage()) return;
8564
8565 // Emit warning for non-trivial dtor in global scope (a real global,
8566 // class-static, function-static).
8567 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8568
8569 // TODO: this should be re-enabled for static locals by !CXAAtExit
8570 if (!VD->isStaticLocal())
8571 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008572}
8573
Mike Stump1eb44332009-09-09 15:08:12 +00008574/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008575/// ActOnDeclarator, when a C++ direct initializer is present.
8576/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00008577void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00008578 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008579 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00008580 SourceLocation RParenLoc,
8581 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00008582 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008583
8584 // If there is no declaration, there was an error parsing it. Just ignore
8585 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00008586 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008587 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008588
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008589 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8590 if (!VDecl) {
8591 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8592 RealDecl->setInvalidDecl();
8593 return;
8594 }
8595
Richard Smith34b41d92011-02-20 03:19:35 +00008596 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8597 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00008598 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8599 if (Exprs.size() > 1) {
8600 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8601 diag::err_auto_var_init_multiple_expressions)
8602 << VDecl->getDeclName() << VDecl->getType()
8603 << VDecl->getSourceRange();
8604 RealDecl->setInvalidDecl();
8605 return;
8606 }
8607
8608 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00008609 TypeSourceInfo *DeducedType = 0;
8610 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00008611 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8612 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8613 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00008614 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00008615 RealDecl->setInvalidDecl();
8616 return;
8617 }
Richard Smitha085da82011-03-17 16:11:59 +00008618 VDecl->setTypeSourceInfo(DeducedType);
8619 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00008620
John McCallf85e1932011-06-15 23:02:42 +00008621 // In ARC, infer lifetime.
8622 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8623 VDecl->setInvalidDecl();
8624
Richard Smith34b41d92011-02-20 03:19:35 +00008625 // If this is a redeclaration, check that the type we just deduced matches
8626 // the previously declared type.
8627 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8628 MergeVarDeclTypes(VDecl, Old);
8629 }
8630
Douglas Gregor83ddad32009-08-26 21:14:46 +00008631 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008632 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008633 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8634 //
8635 // Clients that want to distinguish between the two forms, can check for
8636 // direct initializer using VarDecl::hasCXXDirectInitializer().
8637 // A major benefit is that clients that don't particularly care about which
8638 // exactly form was it (like the CodeGen) can handle both cases without
8639 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008640
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008641 // C++ 8.5p11:
8642 // The form of initialization (using parentheses or '=') is generally
8643 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008644 // class type.
8645
Douglas Gregor4dffad62010-02-11 22:55:30 +00008646 if (!VDecl->getType()->isDependentType() &&
8647 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00008648 diag::err_typecheck_decl_incomplete_type)) {
8649 VDecl->setInvalidDecl();
8650 return;
8651 }
8652
Douglas Gregor90f93822009-12-22 22:17:25 +00008653 // The variable can not have an abstract class type.
8654 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8655 diag::err_abstract_type_in_decl,
8656 AbstractVariableType))
8657 VDecl->setInvalidDecl();
8658
Sebastian Redl31310a22010-02-01 20:16:42 +00008659 const VarDecl *Def;
8660 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00008661 Diag(VDecl->getLocation(), diag::err_redefinition)
8662 << VDecl->getDeclName();
8663 Diag(Def->getLocation(), diag::note_previous_definition);
8664 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008665 return;
8666 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00008667
Douglas Gregor3a91abf2010-08-24 05:27:49 +00008668 // C++ [class.static.data]p4
8669 // If a static data member is of const integral or const
8670 // enumeration type, its declaration in the class definition can
8671 // specify a constant-initializer which shall be an integral
8672 // constant expression (5.19). In that case, the member can appear
8673 // in integral constant expressions. The member shall still be
8674 // defined in a namespace scope if it is used in the program and the
8675 // namespace scope definition shall not contain an initializer.
8676 //
8677 // We already performed a redefinition check above, but for static
8678 // data members we also need to check whether there was an in-class
8679 // declaration with an initializer.
8680 const VarDecl* PrevInit = 0;
8681 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8682 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8683 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8684 return;
8685 }
8686
Douglas Gregora31040f2010-12-16 01:31:22 +00008687 bool IsDependent = false;
8688 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8689 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8690 VDecl->setInvalidDecl();
8691 return;
8692 }
8693
8694 if (Exprs.get()[I]->isTypeDependent())
8695 IsDependent = true;
8696 }
8697
Douglas Gregor4dffad62010-02-11 22:55:30 +00008698 // If either the declaration has a dependent type or if any of the
8699 // expressions is type-dependent, we represent the initialization
8700 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00008701 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00008702 // Let clients know that initialization was done with a direct initializer.
8703 VDecl->setCXXDirectInitializer(true);
8704
8705 // Store the initialization expressions as a ParenListExpr.
8706 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00008707 VDecl->setInit(new (Context) ParenListExpr(
8708 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8709 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00008710 return;
8711 }
Douglas Gregor90f93822009-12-22 22:17:25 +00008712
8713 // Capture the variable that is being initialized and the style of
8714 // initialization.
8715 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8716
8717 // FIXME: Poor source location information.
8718 InitializationKind Kind
8719 = InitializationKind::CreateDirect(VDecl->getLocation(),
8720 LParenLoc, RParenLoc);
8721
8722 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00008723 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00008724 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00008725 if (Result.isInvalid()) {
8726 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008727 return;
8728 }
John McCallb4eb64d2010-10-08 02:01:28 +00008729
8730 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00008731
Douglas Gregor53c374f2010-12-07 00:41:46 +00008732 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00008733 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008734 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008735
John McCall2998d6b2011-01-19 11:48:09 +00008736 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008737}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00008738
Douglas Gregor39da0b82009-09-09 23:08:42 +00008739/// \brief Given a constructor and the set of arguments provided for the
8740/// constructor, convert the arguments and add any required default arguments
8741/// to form a proper call to this constructor.
8742///
8743/// \returns true if an error occurred, false otherwise.
8744bool
8745Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8746 MultiExprArg ArgsPtr,
8747 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00008748 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00008749 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8750 unsigned NumArgs = ArgsPtr.size();
8751 Expr **Args = (Expr **)ArgsPtr.get();
8752
8753 const FunctionProtoType *Proto
8754 = Constructor->getType()->getAs<FunctionProtoType>();
8755 assert(Proto && "Constructor without a prototype?");
8756 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00008757
8758 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008759 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00008760 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008761 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00008762 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008763
8764 VariadicCallType CallType =
8765 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008766 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00008767 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8768 Proto, 0, Args, NumArgs, AllArgs,
8769 CallType);
8770 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8771 ConvertedArgs.push_back(AllArgs[i]);
8772 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00008773}
8774
Anders Carlsson20d45d22009-12-12 00:32:00 +00008775static inline bool
8776CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8777 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008778 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00008779 if (isa<NamespaceDecl>(DC)) {
8780 return SemaRef.Diag(FnDecl->getLocation(),
8781 diag::err_operator_new_delete_declared_in_namespace)
8782 << FnDecl->getDeclName();
8783 }
8784
8785 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00008786 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008787 return SemaRef.Diag(FnDecl->getLocation(),
8788 diag::err_operator_new_delete_declared_static)
8789 << FnDecl->getDeclName();
8790 }
8791
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00008792 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00008793}
8794
Anders Carlsson156c78e2009-12-13 17:53:43 +00008795static inline bool
8796CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8797 CanQualType ExpectedResultType,
8798 CanQualType ExpectedFirstParamType,
8799 unsigned DependentParamTypeDiag,
8800 unsigned InvalidParamTypeDiag) {
8801 QualType ResultType =
8802 FnDecl->getType()->getAs<FunctionType>()->getResultType();
8803
8804 // Check that the result type is not dependent.
8805 if (ResultType->isDependentType())
8806 return SemaRef.Diag(FnDecl->getLocation(),
8807 diag::err_operator_new_delete_dependent_result_type)
8808 << FnDecl->getDeclName() << ExpectedResultType;
8809
8810 // Check that the result type is what we expect.
8811 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8812 return SemaRef.Diag(FnDecl->getLocation(),
8813 diag::err_operator_new_delete_invalid_result_type)
8814 << FnDecl->getDeclName() << ExpectedResultType;
8815
8816 // A function template must have at least 2 parameters.
8817 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8818 return SemaRef.Diag(FnDecl->getLocation(),
8819 diag::err_operator_new_delete_template_too_few_parameters)
8820 << FnDecl->getDeclName();
8821
8822 // The function decl must have at least 1 parameter.
8823 if (FnDecl->getNumParams() == 0)
8824 return SemaRef.Diag(FnDecl->getLocation(),
8825 diag::err_operator_new_delete_too_few_parameters)
8826 << FnDecl->getDeclName();
8827
8828 // Check the the first parameter type is not dependent.
8829 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8830 if (FirstParamType->isDependentType())
8831 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8832 << FnDecl->getDeclName() << ExpectedFirstParamType;
8833
8834 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00008835 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00008836 ExpectedFirstParamType)
8837 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8838 << FnDecl->getDeclName() << ExpectedFirstParamType;
8839
8840 return false;
8841}
8842
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008843static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00008844CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00008845 // C++ [basic.stc.dynamic.allocation]p1:
8846 // A program is ill-formed if an allocation function is declared in a
8847 // namespace scope other than global scope or declared static in global
8848 // scope.
8849 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8850 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00008851
8852 CanQualType SizeTy =
8853 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8854
8855 // C++ [basic.stc.dynamic.allocation]p1:
8856 // The return type shall be void*. The first parameter shall have type
8857 // std::size_t.
8858 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8859 SizeTy,
8860 diag::err_operator_new_dependent_param_type,
8861 diag::err_operator_new_param_type))
8862 return true;
8863
8864 // C++ [basic.stc.dynamic.allocation]p1:
8865 // The first parameter shall not have an associated default argument.
8866 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00008867 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00008868 diag::err_operator_new_default_arg)
8869 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8870
8871 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00008872}
8873
8874static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008875CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8876 // C++ [basic.stc.dynamic.deallocation]p1:
8877 // A program is ill-formed if deallocation functions are declared in a
8878 // namespace scope other than global scope or declared static in global
8879 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00008880 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8881 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008882
8883 // C++ [basic.stc.dynamic.deallocation]p2:
8884 // Each deallocation function shall return void and its first parameter
8885 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00008886 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8887 SemaRef.Context.VoidPtrTy,
8888 diag::err_operator_delete_dependent_param_type,
8889 diag::err_operator_delete_param_type))
8890 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008891
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008892 return false;
8893}
8894
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008895/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8896/// of this overloaded operator is well-formed. If so, returns false;
8897/// otherwise, emits appropriate diagnostics and returns true.
8898bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008899 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008900 "Expected an overloaded operator declaration");
8901
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008902 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8903
Mike Stump1eb44332009-09-09 15:08:12 +00008904 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008905 // The allocation and deallocation functions, operator new,
8906 // operator new[], operator delete and operator delete[], are
8907 // described completely in 3.7.3. The attributes and restrictions
8908 // found in the rest of this subclause do not apply to them unless
8909 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00008910 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00008911 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00008912
Anders Carlssona3ccda52009-12-12 00:26:23 +00008913 if (Op == OO_New || Op == OO_Array_New)
8914 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008915
8916 // C++ [over.oper]p6:
8917 // An operator function shall either be a non-static member
8918 // function or be a non-member function and have at least one
8919 // parameter whose type is a class, a reference to a class, an
8920 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008921 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8922 if (MethodDecl->isStatic())
8923 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008924 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008925 } else {
8926 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008927 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8928 ParamEnd = FnDecl->param_end();
8929 Param != ParamEnd; ++Param) {
8930 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00008931 if (ParamType->isDependentType() || ParamType->isRecordType() ||
8932 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008933 ClassOrEnumParam = true;
8934 break;
8935 }
8936 }
8937
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008938 if (!ClassOrEnumParam)
8939 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00008940 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008941 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008942 }
8943
8944 // C++ [over.oper]p8:
8945 // An operator function cannot have default arguments (8.3.6),
8946 // except where explicitly stated below.
8947 //
Mike Stump1eb44332009-09-09 15:08:12 +00008948 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008949 // (C++ [over.call]p1).
8950 if (Op != OO_Call) {
8951 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8952 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00008953 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00008954 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00008955 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00008956 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008957 }
8958 }
8959
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008960 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8961 { false, false, false }
8962#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8963 , { Unary, Binary, MemberOnly }
8964#include "clang/Basic/OperatorKinds.def"
8965 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008966
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008967 bool CanBeUnaryOperator = OperatorUses[Op][0];
8968 bool CanBeBinaryOperator = OperatorUses[Op][1];
8969 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008970
8971 // C++ [over.oper]p8:
8972 // [...] Operator functions cannot have more or fewer parameters
8973 // than the number required for the corresponding operator, as
8974 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00008975 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008976 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008977 if (Op != OO_Call &&
8978 ((NumParams == 1 && !CanBeUnaryOperator) ||
8979 (NumParams == 2 && !CanBeBinaryOperator) ||
8980 (NumParams < 1) || (NumParams > 2))) {
8981 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00008982 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008983 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008984 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008985 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00008986 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008987 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00008988 assert(CanBeBinaryOperator &&
8989 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00008990 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00008991 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008992
Chris Lattner416e46f2008-11-21 07:57:12 +00008993 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00008994 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00008995 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00008996
Douglas Gregor43c7bad2008-11-17 16:14:12 +00008997 // Overloaded operators other than operator() cannot be variadic.
8998 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00008999 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009000 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009001 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009002 }
9003
9004 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009005 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9006 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009007 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009008 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009009 }
9010
9011 // C++ [over.inc]p1:
9012 // The user-defined function called operator++ implements the
9013 // prefix and postfix ++ operator. If this function is a member
9014 // function with no parameters, or a non-member function with one
9015 // parameter of class or enumeration type, it defines the prefix
9016 // increment operator ++ for objects of that type. If the function
9017 // is a member function with one parameter (which shall be of type
9018 // int) or a non-member function with two parameters (the second
9019 // of which shall be of type int), it defines the postfix
9020 // increment operator ++ for objects of that type.
9021 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9022 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9023 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009024 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009025 ParamIsInt = BT->getKind() == BuiltinType::Int;
9026
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009027 if (!ParamIsInt)
9028 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009029 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009030 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009031 }
9032
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009033 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009034}
Chris Lattner5a003a42008-12-17 07:09:26 +00009035
Sean Hunta6c058d2010-01-13 09:01:02 +00009036/// CheckLiteralOperatorDeclaration - Check whether the declaration
9037/// of this literal operator function is well-formed. If so, returns
9038/// false; otherwise, emits appropriate diagnostics and returns true.
9039bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9040 DeclContext *DC = FnDecl->getDeclContext();
9041 Decl::Kind Kind = DC->getDeclKind();
9042 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9043 Kind != Decl::LinkageSpec) {
9044 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9045 << FnDecl->getDeclName();
9046 return true;
9047 }
9048
9049 bool Valid = false;
9050
Sean Hunt216c2782010-04-07 23:11:06 +00009051 // template <char...> type operator "" name() is the only valid template
9052 // signature, and the only valid signature with no parameters.
9053 if (FnDecl->param_size() == 0) {
9054 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9055 // Must have only one template parameter
9056 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9057 if (Params->size() == 1) {
9058 NonTypeTemplateParmDecl *PmDecl =
9059 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009060
Sean Hunt216c2782010-04-07 23:11:06 +00009061 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009062 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9063 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9064 Valid = true;
9065 }
9066 }
9067 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009068 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009069 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9070
Sean Hunta6c058d2010-01-13 09:01:02 +00009071 QualType T = (*Param)->getType();
9072
Sean Hunt30019c02010-04-07 22:57:35 +00009073 // unsigned long long int, long double, and any character type are allowed
9074 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009075 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9076 Context.hasSameType(T, Context.LongDoubleTy) ||
9077 Context.hasSameType(T, Context.CharTy) ||
9078 Context.hasSameType(T, Context.WCharTy) ||
9079 Context.hasSameType(T, Context.Char16Ty) ||
9080 Context.hasSameType(T, Context.Char32Ty)) {
9081 if (++Param == FnDecl->param_end())
9082 Valid = true;
9083 goto FinishedParams;
9084 }
9085
Sean Hunt30019c02010-04-07 22:57:35 +00009086 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009087 const PointerType *PT = T->getAs<PointerType>();
9088 if (!PT)
9089 goto FinishedParams;
9090 T = PT->getPointeeType();
9091 if (!T.isConstQualified())
9092 goto FinishedParams;
9093 T = T.getUnqualifiedType();
9094
9095 // Move on to the second parameter;
9096 ++Param;
9097
9098 // If there is no second parameter, the first must be a const char *
9099 if (Param == FnDecl->param_end()) {
9100 if (Context.hasSameType(T, Context.CharTy))
9101 Valid = true;
9102 goto FinishedParams;
9103 }
9104
9105 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9106 // are allowed as the first parameter to a two-parameter function
9107 if (!(Context.hasSameType(T, Context.CharTy) ||
9108 Context.hasSameType(T, Context.WCharTy) ||
9109 Context.hasSameType(T, Context.Char16Ty) ||
9110 Context.hasSameType(T, Context.Char32Ty)))
9111 goto FinishedParams;
9112
9113 // The second and final parameter must be an std::size_t
9114 T = (*Param)->getType().getUnqualifiedType();
9115 if (Context.hasSameType(T, Context.getSizeType()) &&
9116 ++Param == FnDecl->param_end())
9117 Valid = true;
9118 }
9119
9120 // FIXME: This diagnostic is absolutely terrible.
9121FinishedParams:
9122 if (!Valid) {
9123 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9124 << FnDecl->getDeclName();
9125 return true;
9126 }
9127
Douglas Gregor1155c422011-08-30 22:40:35 +00009128 StringRef LiteralName
9129 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9130 if (LiteralName[0] != '_') {
9131 // C++0x [usrlit.suffix]p1:
9132 // Literal suffix identifiers that do not start with an underscore are
9133 // reserved for future standardization.
9134 bool IsHexFloat = true;
9135 if (LiteralName.size() > 1 &&
9136 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9137 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9138 if (!isdigit(LiteralName[I])) {
9139 IsHexFloat = false;
9140 break;
9141 }
9142 }
9143 }
9144
9145 if (IsHexFloat)
9146 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9147 << LiteralName;
9148 else
9149 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9150 }
9151
Sean Hunta6c058d2010-01-13 09:01:02 +00009152 return false;
9153}
9154
Douglas Gregor074149e2009-01-05 19:45:36 +00009155/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9156/// linkage specification, including the language and (if present)
9157/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9158/// the location of the language string literal, which is provided
9159/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9160/// the '{' brace. Otherwise, this linkage specification does not
9161/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009162Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9163 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009164 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009165 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009166 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009167 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009168 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009169 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009170 Language = LinkageSpecDecl::lang_cxx;
9171 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009172 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009173 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009174 }
Mike Stump1eb44332009-09-09 15:08:12 +00009175
Chris Lattnercc98eac2008-12-17 07:13:27 +00009176 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009177
Douglas Gregor074149e2009-01-05 19:45:36 +00009178 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009179 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009180 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009181 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009182 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009183}
9184
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009185/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009186/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9187/// valid, it's the position of the closing '}' brace in a linkage
9188/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009189Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009190 Decl *LinkageSpec,
9191 SourceLocation RBraceLoc) {
9192 if (LinkageSpec) {
9193 if (RBraceLoc.isValid()) {
9194 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9195 LSDecl->setRBraceLoc(RBraceLoc);
9196 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009197 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009198 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009199 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009200}
9201
Douglas Gregord308e622009-05-18 20:51:54 +00009202/// \brief Perform semantic analysis for the variable declaration that
9203/// occurs within a C++ catch clause, returning the newly-created
9204/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009205VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009206 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009207 SourceLocation StartLoc,
9208 SourceLocation Loc,
9209 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009210 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009211 QualType ExDeclType = TInfo->getType();
9212
Sebastian Redl4b07b292008-12-22 19:15:10 +00009213 // Arrays and functions decay.
9214 if (ExDeclType->isArrayType())
9215 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9216 else if (ExDeclType->isFunctionType())
9217 ExDeclType = Context.getPointerType(ExDeclType);
9218
9219 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9220 // The exception-declaration shall not denote a pointer or reference to an
9221 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009222 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009223 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009224 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009225 Invalid = true;
9226 }
Douglas Gregord308e622009-05-18 20:51:54 +00009227
Douglas Gregora2762912010-03-08 01:47:36 +00009228 // GCC allows catching pointers and references to incomplete types
9229 // as an extension; so do we, but we warn by default.
9230
Sebastian Redl4b07b292008-12-22 19:15:10 +00009231 QualType BaseType = ExDeclType;
9232 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009233 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00009234 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00009235 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009236 BaseType = Ptr->getPointeeType();
9237 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00009238 DK = diag::ext_catch_incomplete_ptr;
9239 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009240 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009241 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009242 BaseType = Ref->getPointeeType();
9243 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00009244 DK = diag::ext_catch_incomplete_ref;
9245 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009246 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009247 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00009248 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9249 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00009250 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009251
Mike Stump1eb44332009-09-09 15:08:12 +00009252 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009253 RequireNonAbstractType(Loc, ExDeclType,
9254 diag::err_abstract_type_in_decl,
9255 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009256 Invalid = true;
9257
John McCall5a180392010-07-24 00:37:23 +00009258 // Only the non-fragile NeXT runtime currently supports C++ catches
9259 // of ObjC types, and no runtime supports catching ObjC types by value.
9260 if (!Invalid && getLangOptions().ObjC1) {
9261 QualType T = ExDeclType;
9262 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9263 T = RT->getPointeeType();
9264
9265 if (T->isObjCObjectType()) {
9266 Diag(Loc, diag::err_objc_object_catch);
9267 Invalid = true;
9268 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009269 if (!getLangOptions().ObjCNonFragileABI)
9270 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009271 }
9272 }
9273
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009274 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9275 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009276 ExDecl->setExceptionVariable(true);
9277
Douglas Gregorc41b8782011-07-06 18:14:43 +00009278 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009279 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009280 // C++ [except.handle]p16:
9281 // The object declared in an exception-declaration or, if the
9282 // exception-declaration does not specify a name, a temporary (12.2) is
9283 // copy-initialized (8.5) from the exception object. [...]
9284 // The object is destroyed when the handler exits, after the destruction
9285 // of any automatic objects initialized within the handler.
9286 //
9287 // We just pretend to initialize the object with itself, then make sure
9288 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009289 QualType initType = ExDeclType;
9290
9291 InitializedEntity entity =
9292 InitializedEntity::InitializeVariable(ExDecl);
9293 InitializationKind initKind =
9294 InitializationKind::CreateCopy(Loc, SourceLocation());
9295
9296 Expr *opaqueValue =
9297 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9298 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9299 ExprResult result = sequence.Perform(*this, entity, initKind,
9300 MultiExprArg(&opaqueValue, 1));
9301 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009302 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009303 else {
9304 // If the constructor used was non-trivial, set this as the
9305 // "initializer".
9306 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9307 if (!construct->getConstructor()->isTrivial()) {
9308 Expr *init = MaybeCreateExprWithCleanups(construct);
9309 ExDecl->setInit(init);
9310 }
9311
9312 // And make sure it's destructable.
9313 FinalizeVarWithDestructor(ExDecl, recordType);
9314 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009315 }
9316 }
9317
Douglas Gregord308e622009-05-18 20:51:54 +00009318 if (Invalid)
9319 ExDecl->setInvalidDecl();
9320
9321 return ExDecl;
9322}
9323
9324/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9325/// handler.
John McCalld226f652010-08-21 09:40:31 +00009326Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009327 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009328 bool Invalid = D.isInvalidType();
9329
9330 // Check for unexpanded parameter packs.
9331 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9332 UPPC_ExceptionType)) {
9333 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9334 D.getIdentifierLoc());
9335 Invalid = true;
9336 }
9337
Sebastian Redl4b07b292008-12-22 19:15:10 +00009338 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009339 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009340 LookupOrdinaryName,
9341 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009342 // The scope should be freshly made just for us. There is just no way
9343 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009344 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009345 if (PrevDecl->isTemplateParameter()) {
9346 // Maybe we will complain about the shadowed template parameter.
9347 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009348 }
9349 }
9350
Chris Lattnereaaebc72009-04-25 08:06:05 +00009351 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009352 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9353 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009354 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009355 }
9356
Douglas Gregor83cb9422010-09-09 17:09:21 +00009357 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009358 D.getSourceRange().getBegin(),
9359 D.getIdentifierLoc(),
9360 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009361 if (Invalid)
9362 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009363
Sebastian Redl4b07b292008-12-22 19:15:10 +00009364 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009365 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009366 PushOnScopeChains(ExDecl, S);
9367 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009368 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009369
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009370 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009371 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009372}
Anders Carlssonfb311762009-03-14 00:25:26 +00009373
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009374Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009375 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009376 Expr *AssertMessageExpr_,
9377 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009378 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009379
Anders Carlssonc3082412009-03-14 00:33:21 +00009380 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9381 llvm::APSInt Value(32);
9382 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009383 Diag(StaticAssertLoc,
9384 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00009385 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009386 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00009387 }
Anders Carlssonfb311762009-03-14 00:25:26 +00009388
Anders Carlssonc3082412009-03-14 00:33:21 +00009389 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009390 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009391 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009392 }
9393 }
Mike Stump1eb44332009-09-09 15:08:12 +00009394
Douglas Gregor399ad972010-12-15 23:55:21 +00009395 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9396 return 0;
9397
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009398 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9399 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009400
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009401 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009402 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009403}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009404
Douglas Gregor1d869352010-04-07 16:53:43 +00009405/// \brief Perform semantic analysis of the given friend type declaration.
9406///
9407/// \returns A friend declaration that.
9408FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9409 TypeSourceInfo *TSInfo) {
9410 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9411
9412 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009413 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009414
Douglas Gregor06245bf2010-04-07 17:57:12 +00009415 if (!getLangOptions().CPlusPlus0x) {
9416 // C++03 [class.friend]p2:
9417 // An elaborated-type-specifier shall be used in a friend declaration
9418 // for a class.*
9419 //
9420 // * The class-key of the elaborated-type-specifier is required.
9421 if (!ActiveTemplateInstantiations.empty()) {
9422 // Do not complain about the form of friend template types during
9423 // template instantiation; we will already have complained when the
9424 // template was declared.
9425 } else if (!T->isElaboratedTypeSpecifier()) {
9426 // If we evaluated the type to a record type, suggest putting
9427 // a tag in front.
9428 if (const RecordType *RT = T->getAs<RecordType>()) {
9429 RecordDecl *RD = RT->getDecl();
9430
9431 std::string InsertionText = std::string(" ") + RD->getKindName();
9432
9433 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9434 << (unsigned) RD->getTagKind()
9435 << T
9436 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9437 InsertionText);
9438 } else {
9439 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9440 << T
9441 << SourceRange(FriendLoc, TypeRange.getEnd());
9442 }
9443 } else if (T->getAs<EnumType>()) {
9444 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009445 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009446 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009447 }
9448 }
9449
Douglas Gregor06245bf2010-04-07 17:57:12 +00009450 // C++0x [class.friend]p3:
9451 // If the type specifier in a friend declaration designates a (possibly
9452 // cv-qualified) class type, that class is declared as a friend; otherwise,
9453 // the friend declaration is ignored.
9454
9455 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9456 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009457
9458 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9459}
9460
John McCall9a34edb2010-10-19 01:40:49 +00009461/// Handle a friend tag declaration where the scope specifier was
9462/// templated.
9463Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9464 unsigned TagSpec, SourceLocation TagLoc,
9465 CXXScopeSpec &SS,
9466 IdentifierInfo *Name, SourceLocation NameLoc,
9467 AttributeList *Attr,
9468 MultiTemplateParamsArg TempParamLists) {
9469 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9470
9471 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009472 bool Invalid = false;
9473
9474 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009475 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009476 TempParamLists.get(),
9477 TempParamLists.size(),
9478 /*friend*/ true,
9479 isExplicitSpecialization,
9480 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009481 if (TemplateParams->size() > 0) {
9482 // This is a declaration of a class template.
9483 if (Invalid)
9484 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009485
Eric Christopher4110e132011-07-21 05:34:24 +00009486 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9487 SS, Name, NameLoc, Attr,
9488 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009489 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009490 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009491 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009492 } else {
9493 // The "template<>" header is extraneous.
9494 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9495 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9496 isExplicitSpecialization = true;
9497 }
9498 }
9499
9500 if (Invalid) return 0;
9501
9502 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9503
9504 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009505 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009506 if (TempParamLists.get()[I]->size()) {
9507 isAllExplicitSpecializations = false;
9508 break;
9509 }
9510 }
9511
9512 // FIXME: don't ignore attributes.
9513
9514 // If it's explicit specializations all the way down, just forget
9515 // about the template header and build an appropriate non-templated
9516 // friend. TODO: for source fidelity, remember the headers.
9517 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00009518 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009519 ElaboratedTypeKeyword Keyword
9520 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009521 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009522 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009523 if (T.isNull())
9524 return 0;
9525
9526 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9527 if (isa<DependentNameType>(T)) {
9528 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9529 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009530 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009531 TL.setNameLoc(NameLoc);
9532 } else {
9533 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9534 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009535 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009536 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9537 }
9538
9539 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9540 TSI, FriendLoc);
9541 Friend->setAccess(AS_public);
9542 CurContext->addDecl(Friend);
9543 return Friend;
9544 }
9545
9546 // Handle the case of a templated-scope friend class. e.g.
9547 // template <class T> class A<T>::B;
9548 // FIXME: we don't support these right now.
9549 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9550 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9551 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9552 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9553 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009554 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009555 TL.setNameLoc(NameLoc);
9556
9557 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9558 TSI, FriendLoc);
9559 Friend->setAccess(AS_public);
9560 Friend->setUnsupportedFriend(true);
9561 CurContext->addDecl(Friend);
9562 return Friend;
9563}
9564
9565
John McCalldd4a3b02009-09-16 22:47:08 +00009566/// Handle a friend type declaration. This works in tandem with
9567/// ActOnTag.
9568///
9569/// Notes on friend class templates:
9570///
9571/// We generally treat friend class declarations as if they were
9572/// declaring a class. So, for example, the elaborated type specifier
9573/// in a friend declaration is required to obey the restrictions of a
9574/// class-head (i.e. no typedefs in the scope chain), template
9575/// parameters are required to match up with simple template-ids, &c.
9576/// However, unlike when declaring a template specialization, it's
9577/// okay to refer to a template specialization without an empty
9578/// template parameter declaration, e.g.
9579/// friend class A<T>::B<unsigned>;
9580/// We permit this as a special case; if there are any template
9581/// parameters present at all, require proper matching, i.e.
9582/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009583Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009584 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00009585 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00009586
9587 assert(DS.isFriendSpecified());
9588 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9589
John McCalldd4a3b02009-09-16 22:47:08 +00009590 // Try to convert the decl specifier to a type. This works for
9591 // friend templates because ActOnTag never produces a ClassTemplateDecl
9592 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009593 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009594 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9595 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009596 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009597 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009598
Douglas Gregor6ccab972010-12-16 01:14:37 +00009599 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9600 return 0;
9601
John McCalldd4a3b02009-09-16 22:47:08 +00009602 // This is definitely an error in C++98. It's probably meant to
9603 // be forbidden in C++0x, too, but the specification is just
9604 // poorly written.
9605 //
9606 // The problem is with declarations like the following:
9607 // template <T> friend A<T>::foo;
9608 // where deciding whether a class C is a friend or not now hinges
9609 // on whether there exists an instantiation of A that causes
9610 // 'foo' to equal C. There are restrictions on class-heads
9611 // (which we declare (by fiat) elaborated friend declarations to
9612 // be) that makes this tractable.
9613 //
9614 // FIXME: handle "template <> friend class A<T>;", which
9615 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00009616 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00009617 Diag(Loc, diag::err_tagless_friend_type_template)
9618 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009619 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00009620 }
Douglas Gregor1d869352010-04-07 16:53:43 +00009621
John McCall02cace72009-08-28 07:59:38 +00009622 // C++98 [class.friend]p1: A friend of a class is a function
9623 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00009624 // This is fixed in DR77, which just barely didn't make the C++03
9625 // deadline. It's also a very silly restriction that seriously
9626 // affects inner classes and which nobody else seems to implement;
9627 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00009628 //
9629 // But note that we could warn about it: it's always useless to
9630 // friend one of your own members (it's not, however, worthless to
9631 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00009632
John McCalldd4a3b02009-09-16 22:47:08 +00009633 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00009634 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00009635 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009636 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00009637 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00009638 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00009639 DS.getFriendSpecLoc());
9640 else
Douglas Gregor1d869352010-04-07 16:53:43 +00009641 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9642
9643 if (!D)
John McCalld226f652010-08-21 09:40:31 +00009644 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00009645
John McCalldd4a3b02009-09-16 22:47:08 +00009646 D->setAccess(AS_public);
9647 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00009648
John McCalld226f652010-08-21 09:40:31 +00009649 return D;
John McCall02cace72009-08-28 07:59:38 +00009650}
9651
John McCall337ec3d2010-10-12 23:13:28 +00009652Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9653 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00009654 const DeclSpec &DS = D.getDeclSpec();
9655
9656 assert(DS.isFriendSpecified());
9657 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9658
9659 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00009660 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9661 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00009662
9663 // C++ [class.friend]p1
9664 // A friend of a class is a function or class....
9665 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00009666 // It *doesn't* see through dependent types, which is correct
9667 // according to [temp.arg.type]p3:
9668 // If a declaration acquires a function type through a
9669 // type dependent on a template-parameter and this causes
9670 // a declaration that does not use the syntactic form of a
9671 // function declarator to have a function type, the program
9672 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00009673 if (!T->isFunctionType()) {
9674 Diag(Loc, diag::err_unexpected_friend);
9675
9676 // It might be worthwhile to try to recover by creating an
9677 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00009678 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009679 }
9680
9681 // C++ [namespace.memdef]p3
9682 // - If a friend declaration in a non-local class first declares a
9683 // class or function, the friend class or function is a member
9684 // of the innermost enclosing namespace.
9685 // - The name of the friend is not found by simple name lookup
9686 // until a matching declaration is provided in that namespace
9687 // scope (either before or after the class declaration granting
9688 // friendship).
9689 // - If a friend function is called, its name may be found by the
9690 // name lookup that considers functions from namespaces and
9691 // classes associated with the types of the function arguments.
9692 // - When looking for a prior declaration of a class or a function
9693 // declared as a friend, scopes outside the innermost enclosing
9694 // namespace scope are not considered.
9695
John McCall337ec3d2010-10-12 23:13:28 +00009696 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00009697 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9698 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00009699 assert(Name);
9700
Douglas Gregor6ccab972010-12-16 01:14:37 +00009701 // Check for unexpanded parameter packs.
9702 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9703 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9704 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9705 return 0;
9706
John McCall67d1a672009-08-06 02:15:43 +00009707 // The context we found the declaration in, or in which we should
9708 // create the declaration.
9709 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00009710 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00009711 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00009712 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00009713
John McCall337ec3d2010-10-12 23:13:28 +00009714 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00009715
John McCall337ec3d2010-10-12 23:13:28 +00009716 // There are four cases here.
9717 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00009718 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00009719 // there as appropriate.
9720 // Recover from invalid scope qualifiers as if they just weren't there.
9721 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00009722 // C++0x [namespace.memdef]p3:
9723 // If the name in a friend declaration is neither qualified nor
9724 // a template-id and the declaration is a function or an
9725 // elaborated-type-specifier, the lookup to determine whether
9726 // the entity has been previously declared shall not consider
9727 // any scopes outside the innermost enclosing namespace.
9728 // C++0x [class.friend]p11:
9729 // If a friend declaration appears in a local class and the name
9730 // specified is an unqualified name, a prior declaration is
9731 // looked up without considering scopes that are outside the
9732 // innermost enclosing non-class scope. For a friend function
9733 // declaration, if there is no prior declaration, the program is
9734 // ill-formed.
9735 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00009736 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00009737
John McCall29ae6e52010-10-13 05:45:15 +00009738 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00009739 DC = CurContext;
9740 while (true) {
9741 // Skip class contexts. If someone can cite chapter and verse
9742 // for this behavior, that would be nice --- it's what GCC and
9743 // EDG do, and it seems like a reasonable intent, but the spec
9744 // really only says that checks for unqualified existing
9745 // declarations should stop at the nearest enclosing namespace,
9746 // not that they should only consider the nearest enclosing
9747 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00009748 while (DC->isRecord())
9749 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00009750
John McCall68263142009-11-18 22:49:29 +00009751 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00009752
9753 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00009754 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00009755 break;
John McCall29ae6e52010-10-13 05:45:15 +00009756
John McCall8a407372010-10-14 22:22:28 +00009757 if (isTemplateId) {
9758 if (isa<TranslationUnitDecl>(DC)) break;
9759 } else {
9760 if (DC->isFileContext()) break;
9761 }
John McCall67d1a672009-08-06 02:15:43 +00009762 DC = DC->getParent();
9763 }
9764
9765 // C++ [class.friend]p1: A friend of a class is a function or
9766 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00009767 // C++0x changes this for both friend types and functions.
9768 // Most C++ 98 compilers do seem to give an error here, so
9769 // we do, too.
John McCall68263142009-11-18 22:49:29 +00009770 if (!Previous.empty() && DC->Equals(CurContext)
9771 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00009772 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00009773
John McCall380aaa42010-10-13 06:22:15 +00009774 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00009775
John McCall337ec3d2010-10-12 23:13:28 +00009776 // - There's a non-dependent scope specifier, in which case we
9777 // compute it and do a previous lookup there for a function
9778 // or function template.
9779 } else if (!SS.getScopeRep()->isDependent()) {
9780 DC = computeDeclContext(SS);
9781 if (!DC) return 0;
9782
9783 if (RequireCompleteDeclContext(SS, DC)) return 0;
9784
9785 LookupQualifiedName(Previous, DC);
9786
9787 // Ignore things found implicitly in the wrong scope.
9788 // TODO: better diagnostics for this case. Suggesting the right
9789 // qualified scope would be nice...
9790 LookupResult::Filter F = Previous.makeFilter();
9791 while (F.hasNext()) {
9792 NamedDecl *D = F.next();
9793 if (!DC->InEnclosingNamespaceSetOf(
9794 D->getDeclContext()->getRedeclContext()))
9795 F.erase();
9796 }
9797 F.done();
9798
9799 if (Previous.empty()) {
9800 D.setInvalidType();
9801 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9802 return 0;
9803 }
9804
9805 // C++ [class.friend]p1: A friend of a class is a function or
9806 // class that is not a member of the class . . .
9807 if (DC->Equals(CurContext))
9808 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9809
9810 // - There's a scope specifier that does not match any template
9811 // parameter lists, in which case we use some arbitrary context,
9812 // create a method or method template, and wait for instantiation.
9813 // - There's a scope specifier that does match some template
9814 // parameter lists, which we don't handle right now.
9815 } else {
9816 DC = CurContext;
9817 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00009818 }
9819
John McCall29ae6e52010-10-13 05:45:15 +00009820 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00009821 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009822 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9823 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9824 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00009825 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00009826 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9827 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00009828 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009829 }
John McCall67d1a672009-08-06 02:15:43 +00009830 }
9831
Douglas Gregor182ddf02009-09-28 00:08:27 +00009832 bool Redeclaration = false;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009833 bool AddToScope = true;
John McCall380aaa42010-10-13 06:22:15 +00009834 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00009835 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00009836 IsDefinition,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00009837 Redeclaration, AddToScope);
John McCalld226f652010-08-21 09:40:31 +00009838 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00009839
Douglas Gregor182ddf02009-09-28 00:08:27 +00009840 assert(ND->getDeclContext() == DC);
9841 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00009842
John McCallab88d972009-08-31 22:39:49 +00009843 // Add the function declaration to the appropriate lookup tables,
9844 // adjusting the redeclarations list as necessary. We don't
9845 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00009846 //
John McCallab88d972009-08-31 22:39:49 +00009847 // Also update the scope-based lookup if the target context's
9848 // lookup context is in lexical scope.
9849 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009850 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00009851 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009852 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00009853 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00009854 }
John McCall02cace72009-08-28 07:59:38 +00009855
9856 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00009857 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00009858 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00009859 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00009860 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00009861
John McCall337ec3d2010-10-12 23:13:28 +00009862 if (ND->isInvalidDecl())
9863 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00009864 else {
9865 FunctionDecl *FD;
9866 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9867 FD = FTD->getTemplatedDecl();
9868 else
9869 FD = cast<FunctionDecl>(ND);
9870
9871 // Mark templated-scope function declarations as unsupported.
9872 if (FD->getNumTemplateParameterLists())
9873 FrD->setUnsupportedFriend(true);
9874 }
John McCall337ec3d2010-10-12 23:13:28 +00009875
John McCalld226f652010-08-21 09:40:31 +00009876 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00009877}
9878
John McCalld226f652010-08-21 09:40:31 +00009879void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9880 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00009881
Sebastian Redl50de12f2009-03-24 22:27:57 +00009882 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9883 if (!Fn) {
9884 Diag(DelLoc, diag::err_deleted_non_function);
9885 return;
9886 }
9887 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9888 Diag(DelLoc, diag::err_deleted_decl_not_first);
9889 Diag(Prev->getLocation(), diag::note_previous_declaration);
9890 // If the declaration wasn't the first, we delete the function anyway for
9891 // recovery.
9892 }
Sean Hunt10620eb2011-05-06 20:44:56 +00009893 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00009894}
Sebastian Redl13e88542009-04-27 21:33:24 +00009895
Sean Hunte4246a62011-05-12 06:15:49 +00009896void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9897 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9898
9899 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00009900 if (MD->getParent()->isDependentType()) {
9901 MD->setDefaulted();
9902 MD->setExplicitlyDefaulted();
9903 return;
9904 }
9905
Sean Hunte4246a62011-05-12 06:15:49 +00009906 CXXSpecialMember Member = getSpecialMember(MD);
9907 if (Member == CXXInvalid) {
9908 Diag(DefaultLoc, diag::err_default_special_members);
9909 return;
9910 }
9911
9912 MD->setDefaulted();
9913 MD->setExplicitlyDefaulted();
9914
Sean Huntcd10dec2011-05-23 23:14:04 +00009915 // If this definition appears within the record, do the checking when
9916 // the record is complete.
9917 const FunctionDecl *Primary = MD;
9918 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9919 // Find the uninstantiated declaration that actually had the '= default'
9920 // on it.
9921 MD->getTemplateInstantiationPattern()->isDefined(Primary);
9922
9923 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00009924 return;
9925
9926 switch (Member) {
9927 case CXXDefaultConstructor: {
9928 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9929 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009930 if (!CD->isInvalidDecl())
9931 DefineImplicitDefaultConstructor(DefaultLoc, CD);
9932 break;
9933 }
9934
9935 case CXXCopyConstructor: {
9936 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9937 CheckExplicitlyDefaultedCopyConstructor(CD);
9938 if (!CD->isInvalidDecl())
9939 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00009940 break;
9941 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00009942
Sean Hunt2b188082011-05-14 05:23:28 +00009943 case CXXCopyAssignment: {
9944 CheckExplicitlyDefaultedCopyAssignment(MD);
9945 if (!MD->isInvalidDecl())
9946 DefineImplicitCopyAssignment(DefaultLoc, MD);
9947 break;
9948 }
9949
Sean Huntcb45a0f2011-05-12 22:46:25 +00009950 case CXXDestructor: {
9951 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9952 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00009953 if (!DD->isInvalidDecl())
9954 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009955 break;
9956 }
9957
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009958 case CXXMoveConstructor: {
9959 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9960 CheckExplicitlyDefaultedMoveConstructor(CD);
9961 if (!CD->isInvalidDecl())
9962 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +00009963 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009964 }
Sean Hunt82713172011-05-25 23:16:36 +00009965
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009966 case CXXMoveAssignment: {
9967 CheckExplicitlyDefaultedMoveAssignment(MD);
9968 if (!MD->isInvalidDecl())
9969 DefineImplicitMoveAssignment(DefaultLoc, MD);
9970 break;
9971 }
9972
9973 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +00009974 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +00009975 }
9976 } else {
9977 Diag(DefaultLoc, diag::err_default_special_members);
9978 }
9979}
9980
Sebastian Redl13e88542009-04-27 21:33:24 +00009981static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00009982 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00009983 Stmt *SubStmt = *CI;
9984 if (!SubStmt)
9985 continue;
9986 if (isa<ReturnStmt>(SubStmt))
9987 Self.Diag(SubStmt->getSourceRange().getBegin(),
9988 diag::err_return_in_constructor_handler);
9989 if (!isa<Expr>(SubStmt))
9990 SearchForReturnInStmt(Self, SubStmt);
9991 }
9992}
9993
9994void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
9995 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
9996 CXXCatchStmt *Handler = TryBlock->getHandler(I);
9997 SearchForReturnInStmt(*this, Handler);
9998 }
9999}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010000
Mike Stump1eb44332009-09-09 15:08:12 +000010001bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010002 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010003 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10004 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010005
Chandler Carruth73857792010-02-15 11:53:20 +000010006 if (Context.hasSameType(NewTy, OldTy) ||
10007 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010008 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010009
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010010 // Check if the return types are covariant
10011 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010012
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010013 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010014 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10015 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010016 NewClassTy = NewPT->getPointeeType();
10017 OldClassTy = OldPT->getPointeeType();
10018 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010019 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10020 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10021 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10022 NewClassTy = NewRT->getPointeeType();
10023 OldClassTy = OldRT->getPointeeType();
10024 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010025 }
10026 }
Mike Stump1eb44332009-09-09 15:08:12 +000010027
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010028 // The return types aren't either both pointers or references to a class type.
10029 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010030 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010031 diag::err_different_return_type_for_overriding_virtual_function)
10032 << New->getDeclName() << NewTy << OldTy;
10033 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010034
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010035 return true;
10036 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010037
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010038 // C++ [class.virtual]p6:
10039 // If the return type of D::f differs from the return type of B::f, the
10040 // class type in the return type of D::f shall be complete at the point of
10041 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010042 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10043 if (!RT->isBeingDefined() &&
10044 RequireCompleteType(New->getLocation(), NewClassTy,
10045 PDiag(diag::err_covariant_return_incomplete)
10046 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010047 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010048 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010049
Douglas Gregora4923eb2009-11-16 21:35:15 +000010050 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010051 // Check if the new class derives from the old class.
10052 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10053 Diag(New->getLocation(),
10054 diag::err_covariant_return_not_derived)
10055 << New->getDeclName() << NewTy << OldTy;
10056 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10057 return true;
10058 }
Mike Stump1eb44332009-09-09 15:08:12 +000010059
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010060 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010061 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010062 diag::err_covariant_return_inaccessible_base,
10063 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10064 // FIXME: Should this point to the return type?
10065 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010066 // FIXME: this note won't trigger for delayed access control
10067 // diagnostics, and it's impossible to get an undelayed error
10068 // here from access control during the original parse because
10069 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010070 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10071 return true;
10072 }
10073 }
Mike Stump1eb44332009-09-09 15:08:12 +000010074
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010075 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010076 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010077 Diag(New->getLocation(),
10078 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010079 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010080 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10081 return true;
10082 };
Mike Stump1eb44332009-09-09 15:08:12 +000010083
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010084
10085 // The new class type must have the same or less qualifiers as the old type.
10086 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10087 Diag(New->getLocation(),
10088 diag::err_covariant_return_type_class_type_more_qualified)
10089 << New->getDeclName() << NewTy << OldTy;
10090 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10091 return true;
10092 };
Mike Stump1eb44332009-09-09 15:08:12 +000010093
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010094 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010095}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010096
Douglas Gregor4ba31362009-12-01 17:24:26 +000010097/// \brief Mark the given method pure.
10098///
10099/// \param Method the method to be marked pure.
10100///
10101/// \param InitRange the source range that covers the "0" initializer.
10102bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010103 SourceLocation EndLoc = InitRange.getEnd();
10104 if (EndLoc.isValid())
10105 Method->setRangeEnd(EndLoc);
10106
Douglas Gregor4ba31362009-12-01 17:24:26 +000010107 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10108 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010109 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010110 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010111
10112 if (!Method->isInvalidDecl())
10113 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10114 << Method->getDeclName() << InitRange;
10115 return true;
10116}
10117
John McCall731ad842009-12-19 09:28:58 +000010118/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10119/// an initializer for the out-of-line declaration 'Dcl'. The scope
10120/// is a fresh scope pushed for just this purpose.
10121///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010122/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10123/// static data member of class X, names should be looked up in the scope of
10124/// class X.
John McCalld226f652010-08-21 09:40:31 +000010125void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010126 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010127 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010128
John McCall731ad842009-12-19 09:28:58 +000010129 // We should only get called for declarations with scope specifiers, like:
10130 // int foo::bar;
10131 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010132 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010133}
10134
10135/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010136/// initializer for the out-of-line declaration 'D'.
10137void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010138 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010139 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010140
John McCall731ad842009-12-19 09:28:58 +000010141 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010142 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010143}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010144
10145/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10146/// C++ if/switch/while/for statement.
10147/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010148DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010149 // C++ 6.4p2:
10150 // The declarator shall not specify a function or an array.
10151 // The type-specifier-seq shall not contain typedef and shall not declare a
10152 // new class or enumeration.
10153 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10154 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010155
10156 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010157 if (!Dcl)
10158 return true;
10159
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010160 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10161 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010162 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010163 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010164 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010165
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010166 return Dcl;
10167}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010168
Douglas Gregordfe65432011-07-28 19:11:31 +000010169void Sema::LoadExternalVTableUses() {
10170 if (!ExternalSource)
10171 return;
10172
10173 SmallVector<ExternalVTableUse, 4> VTables;
10174 ExternalSource->ReadUsedVTables(VTables);
10175 SmallVector<VTableUse, 4> NewUses;
10176 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10177 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10178 = VTablesUsed.find(VTables[I].Record);
10179 // Even if a definition wasn't required before, it may be required now.
10180 if (Pos != VTablesUsed.end()) {
10181 if (!Pos->second && VTables[I].DefinitionRequired)
10182 Pos->second = true;
10183 continue;
10184 }
10185
10186 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10187 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10188 }
10189
10190 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10191}
10192
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010193void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10194 bool DefinitionRequired) {
10195 // Ignore any vtable uses in unevaluated operands or for classes that do
10196 // not have a vtable.
10197 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10198 CurContext->isDependentContext() ||
10199 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010200 return;
10201
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010202 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010203 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010204 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10205 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10206 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10207 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010208 // If we already had an entry, check to see if we are promoting this vtable
10209 // to required a definition. If so, we need to reappend to the VTableUses
10210 // list, since we may have already processed the first entry.
10211 if (DefinitionRequired && !Pos.first->second) {
10212 Pos.first->second = true;
10213 } else {
10214 // Otherwise, we can early exit.
10215 return;
10216 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010217 }
10218
10219 // Local classes need to have their virtual members marked
10220 // immediately. For all other classes, we mark their virtual members
10221 // at the end of the translation unit.
10222 if (Class->isLocalClass())
10223 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010224 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010225 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010226}
10227
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010228bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010229 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010230 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010231 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010232
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010233 // Note: The VTableUses vector could grow as a result of marking
10234 // the members of a class as "used", so we check the size each
10235 // time through the loop and prefer indices (with are stable) to
10236 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010237 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010238 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010239 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010240 if (!Class)
10241 continue;
10242
10243 SourceLocation Loc = VTableUses[I].second;
10244
10245 // If this class has a key function, but that key function is
10246 // defined in another translation unit, we don't need to emit the
10247 // vtable even though we're using it.
10248 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010249 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010250 switch (KeyFunction->getTemplateSpecializationKind()) {
10251 case TSK_Undeclared:
10252 case TSK_ExplicitSpecialization:
10253 case TSK_ExplicitInstantiationDeclaration:
10254 // The key function is in another translation unit.
10255 continue;
10256
10257 case TSK_ExplicitInstantiationDefinition:
10258 case TSK_ImplicitInstantiation:
10259 // We will be instantiating the key function.
10260 break;
10261 }
10262 } else if (!KeyFunction) {
10263 // If we have a class with no key function that is the subject
10264 // of an explicit instantiation declaration, suppress the
10265 // vtable; it will live with the explicit instantiation
10266 // definition.
10267 bool IsExplicitInstantiationDeclaration
10268 = Class->getTemplateSpecializationKind()
10269 == TSK_ExplicitInstantiationDeclaration;
10270 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10271 REnd = Class->redecls_end();
10272 R != REnd; ++R) {
10273 TemplateSpecializationKind TSK
10274 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10275 if (TSK == TSK_ExplicitInstantiationDeclaration)
10276 IsExplicitInstantiationDeclaration = true;
10277 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10278 IsExplicitInstantiationDeclaration = false;
10279 break;
10280 }
10281 }
10282
10283 if (IsExplicitInstantiationDeclaration)
10284 continue;
10285 }
10286
10287 // Mark all of the virtual members of this class as referenced, so
10288 // that we can build a vtable. Then, tell the AST consumer that a
10289 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010290 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010291 MarkVirtualMembersReferenced(Loc, Class);
10292 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10293 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10294
10295 // Optionally warn if we're emitting a weak vtable.
10296 if (Class->getLinkage() == ExternalLinkage &&
10297 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010298 const FunctionDecl *KeyFunctionDef = 0;
10299 if (!KeyFunction ||
10300 (KeyFunction->hasBody(KeyFunctionDef) &&
10301 KeyFunctionDef->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010302 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10303 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010304 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010305 VTableUses.clear();
10306
Douglas Gregor78844032011-04-22 22:25:37 +000010307 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010308}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010309
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010310void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10311 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010312 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10313 e = RD->method_end(); i != e; ++i) {
10314 CXXMethodDecl *MD = *i;
10315
10316 // C++ [basic.def.odr]p2:
10317 // [...] A virtual member function is used if it is not pure. [...]
10318 if (MD->isVirtual() && !MD->isPure())
10319 MarkDeclarationReferenced(Loc, MD);
10320 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010321
10322 // Only classes that have virtual bases need a VTT.
10323 if (RD->getNumVBases() == 0)
10324 return;
10325
10326 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10327 e = RD->bases_end(); i != e; ++i) {
10328 const CXXRecordDecl *Base =
10329 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010330 if (Base->getNumVBases() == 0)
10331 continue;
10332 MarkVirtualMembersReferenced(Loc, Base);
10333 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010334}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010335
10336/// SetIvarInitializers - This routine builds initialization ASTs for the
10337/// Objective-C implementation whose ivars need be initialized.
10338void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10339 if (!getLangOptions().CPlusPlus)
10340 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010341 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010342 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010343 CollectIvarsToConstructOrDestruct(OID, ivars);
10344 if (ivars.empty())
10345 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010346 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010347 for (unsigned i = 0; i < ivars.size(); i++) {
10348 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010349 if (Field->isInvalidDecl())
10350 continue;
10351
Sean Huntcbb67482011-01-08 20:30:50 +000010352 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010353 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10354 InitializationKind InitKind =
10355 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10356
10357 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010358 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010359 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010360 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010361 // Note, MemberInit could actually come back empty if no initialization
10362 // is required (e.g., because it would call a trivial default constructor)
10363 if (!MemberInit.get() || MemberInit.isInvalid())
10364 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010365
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010366 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010367 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10368 SourceLocation(),
10369 MemberInit.takeAs<Expr>(),
10370 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010371 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010372
10373 // Be sure that the destructor is accessible and is marked as referenced.
10374 if (const RecordType *RecordTy
10375 = Context.getBaseElementType(Field->getType())
10376 ->getAs<RecordType>()) {
10377 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010378 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010379 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10380 CheckDestructorAccess(Field->getLocation(), Destructor,
10381 PDiag(diag::err_access_dtor_ivar)
10382 << Context.getBaseElementType(Field->getType()));
10383 }
10384 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010385 }
10386 ObjCImplementation->setIvarInitializers(Context,
10387 AllToInit.data(), AllToInit.size());
10388 }
10389}
Sean Huntfe57eef2011-05-04 05:57:24 +000010390
Sean Huntebcbe1d2011-05-04 23:29:54 +000010391static
10392void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10393 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10394 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10395 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10396 Sema &S) {
10397 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10398 CE = Current.end();
10399 if (Ctor->isInvalidDecl())
10400 return;
10401
10402 const FunctionDecl *FNTarget = 0;
10403 CXXConstructorDecl *Target;
10404
10405 // We ignore the result here since if we don't have a body, Target will be
10406 // null below.
10407 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10408 Target
10409= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10410
10411 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10412 // Avoid dereferencing a null pointer here.
10413 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10414
10415 if (!Current.insert(Canonical))
10416 return;
10417
10418 // We know that beyond here, we aren't chaining into a cycle.
10419 if (!Target || !Target->isDelegatingConstructor() ||
10420 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10421 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10422 Valid.insert(*CI);
10423 Current.clear();
10424 // We've hit a cycle.
10425 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10426 Current.count(TCanonical)) {
10427 // If we haven't diagnosed this cycle yet, do so now.
10428 if (!Invalid.count(TCanonical)) {
10429 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010430 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010431 << Ctor;
10432
10433 // Don't add a note for a function delegating directo to itself.
10434 if (TCanonical != Canonical)
10435 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10436
10437 CXXConstructorDecl *C = Target;
10438 while (C->getCanonicalDecl() != Canonical) {
10439 (void)C->getTargetConstructor()->hasBody(FNTarget);
10440 assert(FNTarget && "Ctor cycle through bodiless function");
10441
10442 C
10443 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10444 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10445 }
10446 }
10447
10448 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10449 Invalid.insert(*CI);
10450 Current.clear();
10451 } else {
10452 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10453 }
10454}
10455
10456
Sean Huntfe57eef2011-05-04 05:57:24 +000010457void Sema::CheckDelegatingCtorCycles() {
10458 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10459
Sean Huntebcbe1d2011-05-04 23:29:54 +000010460 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10461 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010462
Douglas Gregor0129b562011-07-27 21:57:17 +000010463 for (DelegatingCtorDeclsType::iterator
10464 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010465 E = DelegatingCtorDecls.end();
10466 I != E; ++I) {
10467 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010468 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010469
10470 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10471 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010472}