blob: 918f97245e6be1a3ce66c9383fb22ba464b68476 [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.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000423 for (FunctionDecl *Older = Old->getPreviousDecl();
424 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000425 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
Richard Smith9f569cc2011-10-01 02:31:28 +0000505 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
506 // template has a constexpr specifier then all its declarations shall
507 // contain the constexpr specifier. [Note: An explicit specialization can
508 // differ from the template declaration with respect to the constexpr
509 // specifier. -- end note]
510 //
511 // FIXME: Don't reject changes in constexpr in explicit specializations.
512 if (New->isConstexpr() != Old->isConstexpr()) {
513 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
514 << New << New->isConstexpr();
515 Diag(Old->getLocation(), diag::note_previous_declaration);
516 Invalid = true;
517 }
518
Douglas Gregore13ad832010-02-12 07:32:17 +0000519 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000520 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000521
Douglas Gregorcda9c672009-02-16 17:45:42 +0000522 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000523}
524
Sebastian Redl60618fa2011-03-12 11:50:43 +0000525/// \brief Merge the exception specifications of two variable declarations.
526///
527/// This is called when there's a redeclaration of a VarDecl. The function
528/// checks if the redeclaration might have an exception specification and
529/// validates compatibility and merges the specs if necessary.
530void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
531 // Shortcut if exceptions are disabled.
532 if (!getLangOptions().CXXExceptions)
533 return;
534
535 assert(Context.hasSameType(New->getType(), Old->getType()) &&
536 "Should only be called if types are otherwise the same.");
537
538 QualType NewType = New->getType();
539 QualType OldType = Old->getType();
540
541 // We're only interested in pointers and references to functions, as well
542 // as pointers to member functions.
543 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
544 NewType = R->getPointeeType();
545 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
546 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
547 NewType = P->getPointeeType();
548 OldType = OldType->getAs<PointerType>()->getPointeeType();
549 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
550 NewType = M->getPointeeType();
551 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
552 }
553
554 if (!NewType->isFunctionProtoType())
555 return;
556
557 // There's lots of special cases for functions. For function pointers, system
558 // libraries are hopefully not as broken so that we don't need these
559 // workarounds.
560 if (CheckEquivalentExceptionSpec(
561 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
562 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
563 New->setInvalidDecl();
564 }
565}
566
Chris Lattner3d1cee32008-04-08 05:04:30 +0000567/// CheckCXXDefaultArguments - Verify that the default arguments for a
568/// function declaration are well-formed according to C++
569/// [dcl.fct.default].
570void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
571 unsigned NumParams = FD->getNumParams();
572 unsigned p;
573
574 // Find first parameter with a default argument
575 for (p = 0; p < NumParams; ++p) {
576 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000577 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000578 break;
579 }
580
581 // C++ [dcl.fct.default]p4:
582 // In a given function declaration, all parameters
583 // subsequent to a parameter with a default argument shall
584 // have default arguments supplied in this or previous
585 // declarations. A default argument shall not be redefined
586 // by a later declaration (not even to the same value).
587 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000588 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000589 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000590 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000591 if (Param->isInvalidDecl())
592 /* We already complained about this parameter. */;
593 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000594 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000595 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000596 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000597 else
Mike Stump1eb44332009-09-09 15:08:12 +0000598 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Chris Lattner3d1cee32008-04-08 05:04:30 +0000601 LastMissingDefaultArg = p;
602 }
603 }
604
605 if (LastMissingDefaultArg > 0) {
606 // Some default arguments were missing. Clear out all of the
607 // default arguments up to (and including) the last missing
608 // default argument, so that we leave the function parameters
609 // in a semantically valid state.
610 for (p = 0; p <= LastMissingDefaultArg; ++p) {
611 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000612 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000613 Param->setDefaultArg(0);
614 }
615 }
616 }
617}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000618
Richard Smith9f569cc2011-10-01 02:31:28 +0000619// CheckConstexprParameterTypes - Check whether a function's parameter types
620// are all literal types. If so, return true. If not, produce a suitable
621// diagnostic depending on @p CCK and return false.
622static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
623 Sema::CheckConstexprKind CCK) {
624 unsigned ArgIndex = 0;
625 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
626 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
627 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
628 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
629 SourceLocation ParamLoc = PD->getLocation();
630 if (!(*i)->isDependentType() &&
631 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
632 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
633 << ArgIndex+1 << PD->getSourceRange()
634 << isa<CXXConstructorDecl>(FD) :
635 SemaRef.PDiag(),
636 /*AllowIncompleteType*/ true)) {
637 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
638 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
639 << ArgIndex+1 << PD->getSourceRange()
640 << isa<CXXConstructorDecl>(FD) << *i;
641 return false;
642 }
643 }
644 return true;
645}
646
647// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
648// the requirements of a constexpr function declaration or a constexpr
649// constructor declaration. Return true if it does, false if not.
650//
Richard Smith35340502012-01-13 04:54:00 +0000651// This implements C++11 [dcl.constexpr]p3,4, as amended by N3308.
Richard Smith9f569cc2011-10-01 02:31:28 +0000652//
653// \param CCK Specifies whether to produce diagnostics if the function does not
654// satisfy the requirements.
655bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
656 CheckConstexprKind CCK) {
657 assert((CCK != CCK_NoteNonConstexprInstantiation ||
658 (NewFD->getTemplateInstantiationPattern() &&
659 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
660 "only constexpr templates can be instantiated non-constexpr");
661
Richard Smith35340502012-01-13 04:54:00 +0000662 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
663 if (MD && MD->isInstance()) {
664 // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor...
Richard Smith9f569cc2011-10-01 02:31:28 +0000665 // In addition, either its function-body shall be = delete or = default or
666 // it shall satisfy the following constraints:
667 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000668 //
669 // We apply this to constexpr member functions too: the class cannot be a
670 // literal type, so the members are not permitted to be constexpr.
671 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000672 if (RD->getNumVBases()) {
673 // Note, this is still illegal if the body is = default, since the
674 // implicit body does not satisfy the requirements of a constexpr
675 // constructor. We also reject cases where the body is = delete, as
676 // required by N3308.
677 if (CCK != CCK_Instantiation) {
678 Diag(NewFD->getLocation(),
679 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
680 : diag::note_constexpr_tmpl_virtual_base)
Richard Smith35340502012-01-13 04:54:00 +0000681 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
682 << RD->getNumVBases();
Richard Smith9f569cc2011-10-01 02:31:28 +0000683 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
684 E = RD->vbases_end(); I != E; ++I)
685 Diag(I->getSourceRange().getBegin(),
686 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
687 }
688 return false;
689 }
Richard Smith35340502012-01-13 04:54:00 +0000690 }
691
692 if (!isa<CXXConstructorDecl>(NewFD)) {
693 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000694 // The definition of a constexpr function shall satisfy the following
695 // constraints:
696 // - it shall not be virtual;
697 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
698 if (Method && Method->isVirtual()) {
699 if (CCK != CCK_Instantiation) {
700 Diag(NewFD->getLocation(),
701 CCK == CCK_Declaration ? diag::err_constexpr_virtual
702 : diag::note_constexpr_tmpl_virtual);
703
704 // If it's not obvious why this function is virtual, find an overridden
705 // function which uses the 'virtual' keyword.
706 const CXXMethodDecl *WrittenVirtual = Method;
707 while (!WrittenVirtual->isVirtualAsWritten())
708 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
709 if (WrittenVirtual != Method)
Richard Smith35340502012-01-13 04:54:00 +0000710 Diag(WrittenVirtual->getLocation(),
Richard Smith9f569cc2011-10-01 02:31:28 +0000711 diag::note_overridden_virtual_function);
712 }
713 return false;
714 }
715
716 // - its return type shall be a literal type;
717 QualType RT = NewFD->getResultType();
718 if (!RT->isDependentType() &&
719 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
720 PDiag(diag::err_constexpr_non_literal_return) :
721 PDiag(),
722 /*AllowIncompleteType*/ true)) {
723 if (CCK == CCK_NoteNonConstexprInstantiation)
724 Diag(NewFD->getLocation(),
725 diag::note_constexpr_tmpl_non_literal_return) << RT;
726 return false;
727 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 }
729
Richard Smith35340502012-01-13 04:54:00 +0000730 // - each of its parameter types shall be a literal type;
731 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
732 return false;
733
Richard Smith9f569cc2011-10-01 02:31:28 +0000734 return true;
735}
736
737/// Check the given declaration statement is legal within a constexpr function
738/// body. C++0x [dcl.constexpr]p3,p4.
739///
740/// \return true if the body is OK, false if we have diagnosed a problem.
741static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
742 DeclStmt *DS) {
743 // C++0x [dcl.constexpr]p3 and p4:
744 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
745 // contain only
746 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
747 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
748 switch ((*DclIt)->getKind()) {
749 case Decl::StaticAssert:
750 case Decl::Using:
751 case Decl::UsingShadow:
752 case Decl::UsingDirective:
753 case Decl::UnresolvedUsingTypename:
754 // - static_assert-declarations
755 // - using-declarations,
756 // - using-directives,
757 continue;
758
759 case Decl::Typedef:
760 case Decl::TypeAlias: {
761 // - typedef declarations and alias-declarations that do not define
762 // classes or enumerations,
763 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
764 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
765 // Don't allow variably-modified types in constexpr functions.
766 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
767 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
768 << TL.getSourceRange() << TL.getType()
769 << isa<CXXConstructorDecl>(Dcl);
770 return false;
771 }
772 continue;
773 }
774
775 case Decl::Enum:
776 case Decl::CXXRecord:
777 // As an extension, we allow the declaration (but not the definition) of
778 // classes and enumerations in all declarations, not just in typedef and
779 // alias declarations.
780 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
781 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
782 << isa<CXXConstructorDecl>(Dcl);
783 return false;
784 }
785 continue;
786
787 case Decl::Var:
788 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
789 << isa<CXXConstructorDecl>(Dcl);
790 return false;
791
792 default:
793 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
794 << isa<CXXConstructorDecl>(Dcl);
795 return false;
796 }
797 }
798
799 return true;
800}
801
802/// Check that the given field is initialized within a constexpr constructor.
803///
804/// \param Dcl The constexpr constructor being checked.
805/// \param Field The field being checked. This may be a member of an anonymous
806/// struct or union nested within the class being checked.
807/// \param Inits All declarations, including anonymous struct/union members and
808/// indirect members, for which any initialization was provided.
809/// \param Diagnosed Set to true if an error is produced.
810static void CheckConstexprCtorInitializer(Sema &SemaRef,
811 const FunctionDecl *Dcl,
812 FieldDecl *Field,
813 llvm::SmallSet<Decl*, 16> &Inits,
814 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000815 if (Field->isUnnamedBitfield())
816 return;
817
Richard Smith9f569cc2011-10-01 02:31:28 +0000818 if (!Inits.count(Field)) {
819 if (!Diagnosed) {
820 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
821 Diagnosed = true;
822 }
823 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
824 } else if (Field->isAnonymousStructOrUnion()) {
825 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
826 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
827 I != E; ++I)
828 // If an anonymous union contains an anonymous struct of which any member
829 // is initialized, all members must be initialized.
830 if (!RD->isUnion() || Inits.count(*I))
831 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
832 }
833}
834
835/// Check the body for the given constexpr function declaration only contains
836/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
837///
838/// \return true if the body is OK, false if we have diagnosed a problem.
839bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
840 if (isa<CXXTryStmt>(Body)) {
841 // C++0x [dcl.constexpr]p3:
842 // The definition of a constexpr function shall satisfy the following
843 // constraints: [...]
844 // - its function-body shall be = delete, = default, or a
845 // compound-statement
846 //
847 // C++0x [dcl.constexpr]p4:
848 // In the definition of a constexpr constructor, [...]
849 // - its function-body shall not be a function-try-block;
850 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
851 << isa<CXXConstructorDecl>(Dcl);
852 return false;
853 }
854
855 // - its function-body shall be [...] a compound-statement that contains only
856 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
857
858 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
859 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
860 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
861 switch ((*BodyIt)->getStmtClass()) {
862 case Stmt::NullStmtClass:
863 // - null statements,
864 continue;
865
866 case Stmt::DeclStmtClass:
867 // - static_assert-declarations
868 // - using-declarations,
869 // - using-directives,
870 // - typedef declarations and alias-declarations that do not define
871 // classes or enumerations,
872 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
873 return false;
874 continue;
875
876 case Stmt::ReturnStmtClass:
877 // - and exactly one return statement;
878 if (isa<CXXConstructorDecl>(Dcl))
879 break;
880
881 ReturnStmts.push_back((*BodyIt)->getLocStart());
882 // FIXME
883 // - every constructor call and implicit conversion used in initializing
884 // the return value shall be one of those allowed in a constant
885 // expression.
886 // Deal with this as part of a general check that the function can produce
887 // a constant expression (for [dcl.constexpr]p5).
888 continue;
889
890 default:
891 break;
892 }
893
894 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
895 << isa<CXXConstructorDecl>(Dcl);
896 return false;
897 }
898
899 if (const CXXConstructorDecl *Constructor
900 = dyn_cast<CXXConstructorDecl>(Dcl)) {
901 const CXXRecordDecl *RD = Constructor->getParent();
902 // - every non-static data member and base class sub-object shall be
903 // initialized;
904 if (RD->isUnion()) {
905 // DR1359: Exactly one member of a union shall be initialized.
906 if (Constructor->getNumCtorInitializers() == 0) {
907 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
908 return false;
909 }
Richard Smith6e433752011-10-10 16:38:04 +0000910 } else if (!Constructor->isDependentContext() &&
911 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000912 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
913
914 // Skip detailed checking if we have enough initializers, and we would
915 // allow at most one initializer per member.
916 bool AnyAnonStructUnionMembers = false;
917 unsigned Fields = 0;
918 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
919 E = RD->field_end(); I != E; ++I, ++Fields) {
920 if ((*I)->isAnonymousStructOrUnion()) {
921 AnyAnonStructUnionMembers = true;
922 break;
923 }
924 }
925 if (AnyAnonStructUnionMembers ||
926 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
927 // Check initialization of non-static data members. Base classes are
928 // always initialized so do not need to be checked. Dependent bases
929 // might not have initializers in the member initializer list.
930 llvm::SmallSet<Decl*, 16> Inits;
931 for (CXXConstructorDecl::init_const_iterator
932 I = Constructor->init_begin(), E = Constructor->init_end();
933 I != E; ++I) {
934 if (FieldDecl *FD = (*I)->getMember())
935 Inits.insert(FD);
936 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
937 Inits.insert(ID->chain_begin(), ID->chain_end());
938 }
939
940 bool Diagnosed = false;
941 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
942 E = RD->field_end(); I != E; ++I)
943 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
944 if (Diagnosed)
945 return false;
946 }
947 }
948
949 // FIXME
950 // - every constructor involved in initializing non-static data members
951 // and base class sub-objects shall be a constexpr constructor;
952 // - every assignment-expression that is an initializer-clause appearing
953 // directly or indirectly within a brace-or-equal-initializer for
954 // a non-static data member that is not named by a mem-initializer-id
955 // shall be a constant expression; and
956 // - every implicit conversion used in converting a constructor argument
957 // to the corresponding parameter type and converting
958 // a full-expression to the corresponding member type shall be one of
959 // those allowed in a constant expression.
960 // Deal with these as part of a general check that the function can produce
961 // a constant expression (for [dcl.constexpr]p5).
962 } else {
963 if (ReturnStmts.empty()) {
964 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
965 return false;
966 }
967 if (ReturnStmts.size() > 1) {
968 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
969 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
970 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
971 return false;
972 }
973 }
974
975 return true;
976}
977
Douglas Gregorb48fe382008-10-31 09:07:45 +0000978/// isCurrentClassName - Determine whether the identifier II is the
979/// name of the class type currently being defined. In the case of
980/// nested classes, this will only return true if II is the name of
981/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000982bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
983 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000984 assert(getLangOptions().CPlusPlus && "No class names in C!");
985
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000986 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000987 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000988 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000989 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
990 } else
991 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
992
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000993 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000994 return &II == CurDecl->getIdentifier();
995 else
996 return false;
997}
998
Mike Stump1eb44332009-09-09 15:08:12 +0000999/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001000///
1001/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1002/// and returns NULL otherwise.
1003CXXBaseSpecifier *
1004Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1005 SourceRange SpecifierRange,
1006 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001007 TypeSourceInfo *TInfo,
1008 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001009 QualType BaseType = TInfo->getType();
1010
Douglas Gregor2943aed2009-03-03 04:44:36 +00001011 // C++ [class.union]p1:
1012 // A union shall not have base classes.
1013 if (Class->isUnion()) {
1014 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1015 << SpecifierRange;
1016 return 0;
1017 }
1018
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001019 if (EllipsisLoc.isValid() &&
1020 !TInfo->getType()->containsUnexpandedParameterPack()) {
1021 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1022 << TInfo->getTypeLoc().getSourceRange();
1023 EllipsisLoc = SourceLocation();
1024 }
1025
Douglas Gregor2943aed2009-03-03 04:44:36 +00001026 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001027 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001028 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001029 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001030
1031 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001032
1033 // Base specifiers must be record types.
1034 if (!BaseType->isRecordType()) {
1035 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1036 return 0;
1037 }
1038
1039 // C++ [class.union]p1:
1040 // A union shall not be used as a base class.
1041 if (BaseType->isUnionType()) {
1042 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1043 return 0;
1044 }
1045
1046 // C++ [class.derived]p2:
1047 // The class-name in a base-specifier shall not be an incompletely
1048 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001049 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001050 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001051 << SpecifierRange)) {
1052 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001053 return 0;
John McCall572fc622010-08-17 07:23:57 +00001054 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001055
Eli Friedman1d954f62009-08-15 21:55:26 +00001056 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001057 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001058 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001059 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001060 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001061 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1062 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001063
Anders Carlsson1d209272011-03-25 14:55:14 +00001064 // C++ [class]p3:
1065 // If a class is marked final and it appears as a base-type-specifier in
1066 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001067 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001068 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1069 << CXXBaseDecl->getDeclName();
1070 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1071 << CXXBaseDecl->getDeclName();
1072 return 0;
1073 }
1074
John McCall572fc622010-08-17 07:23:57 +00001075 if (BaseDecl->isInvalidDecl())
1076 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001077
1078 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001079 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001080 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001081 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001082}
1083
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001084/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1085/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001086/// example:
1087/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001088/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001089BaseResult
John McCalld226f652010-08-21 09:40:31 +00001090Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001091 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001092 ParsedType basetype, SourceLocation BaseLoc,
1093 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001094 if (!classdecl)
1095 return true;
1096
Douglas Gregor40808ce2009-03-09 23:48:35 +00001097 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001098 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001099 if (!Class)
1100 return true;
1101
Nick Lewycky56062202010-07-26 16:56:01 +00001102 TypeSourceInfo *TInfo = 0;
1103 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001104
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001105 if (EllipsisLoc.isInvalid() &&
1106 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001107 UPPC_BaseType))
1108 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001109
Douglas Gregor2943aed2009-03-03 04:44:36 +00001110 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001111 Virtual, Access, TInfo,
1112 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001113 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Douglas Gregor2943aed2009-03-03 04:44:36 +00001115 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001116}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001117
Douglas Gregor2943aed2009-03-03 04:44:36 +00001118/// \brief Performs the actual work of attaching the given base class
1119/// specifiers to a C++ class.
1120bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1121 unsigned NumBases) {
1122 if (NumBases == 0)
1123 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001124
1125 // Used to keep track of which base types we have already seen, so
1126 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001127 // that the key is always the unqualified canonical type of the base
1128 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001129 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1130
1131 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001132 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001133 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001134 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001135 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001136 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001137 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001138 if (KnownBaseTypes[NewBaseType]) {
1139 // C++ [class.mi]p3:
1140 // A class shall not be specified as a direct base class of a
1141 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001143 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001144 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001145 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001146
1147 // Delete the duplicate base class specifier; we're going to
1148 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001149 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001150
1151 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001152 } else {
1153 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001154 KnownBaseTypes[NewBaseType] = Bases[idx];
1155 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001156 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001157 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1158 if (RD->hasAttr<WeakAttr>())
1159 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001160 }
1161 }
1162
1163 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001164 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001165
1166 // Delete the remaining (good) base class specifiers, since their
1167 // data has been copied into the CXXRecordDecl.
1168 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001169 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001170
1171 return Invalid;
1172}
1173
1174/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1175/// class, after checking whether there are any duplicate base
1176/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001177void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001178 unsigned NumBases) {
1179 if (!ClassDecl || !Bases || !NumBases)
1180 return;
1181
1182 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001183 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001184 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001185}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001186
John McCall3cb0ebd2010-03-10 03:28:59 +00001187static CXXRecordDecl *GetClassForType(QualType T) {
1188 if (const RecordType *RT = T->getAs<RecordType>())
1189 return cast<CXXRecordDecl>(RT->getDecl());
1190 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1191 return ICT->getDecl();
1192 else
1193 return 0;
1194}
1195
Douglas Gregora8f32e02009-10-06 17:59:45 +00001196/// \brief Determine whether the type \p Derived is a C++ class that is
1197/// derived from the type \p Base.
1198bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1199 if (!getLangOptions().CPlusPlus)
1200 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001201
1202 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1203 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001204 return false;
1205
John McCall3cb0ebd2010-03-10 03:28:59 +00001206 CXXRecordDecl *BaseRD = GetClassForType(Base);
1207 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001208 return false;
1209
John McCall86ff3082010-02-04 22:26:26 +00001210 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1211 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001212}
1213
1214/// \brief Determine whether the type \p Derived is a C++ class that is
1215/// derived from the type \p Base.
1216bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1217 if (!getLangOptions().CPlusPlus)
1218 return false;
1219
John McCall3cb0ebd2010-03-10 03:28:59 +00001220 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1221 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001222 return false;
1223
John McCall3cb0ebd2010-03-10 03:28:59 +00001224 CXXRecordDecl *BaseRD = GetClassForType(Base);
1225 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001226 return false;
1227
Douglas Gregora8f32e02009-10-06 17:59:45 +00001228 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1229}
1230
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001231void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001232 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001233 assert(BasePathArray.empty() && "Base path array must be empty!");
1234 assert(Paths.isRecordingPaths() && "Must record paths!");
1235
1236 const CXXBasePath &Path = Paths.front();
1237
1238 // We first go backward and check if we have a virtual base.
1239 // FIXME: It would be better if CXXBasePath had the base specifier for
1240 // the nearest virtual base.
1241 unsigned Start = 0;
1242 for (unsigned I = Path.size(); I != 0; --I) {
1243 if (Path[I - 1].Base->isVirtual()) {
1244 Start = I - 1;
1245 break;
1246 }
1247 }
1248
1249 // Now add all bases.
1250 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001251 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001252}
1253
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001254/// \brief Determine whether the given base path includes a virtual
1255/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001256bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1257 for (CXXCastPath::const_iterator B = BasePath.begin(),
1258 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001259 B != BEnd; ++B)
1260 if ((*B)->isVirtual())
1261 return true;
1262
1263 return false;
1264}
1265
Douglas Gregora8f32e02009-10-06 17:59:45 +00001266/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1267/// conversion (where Derived and Base are class types) is
1268/// well-formed, meaning that the conversion is unambiguous (and
1269/// that all of the base classes are accessible). Returns true
1270/// and emits a diagnostic if the code is ill-formed, returns false
1271/// otherwise. Loc is the location where this routine should point to
1272/// if there is an error, and Range is the source range to highlight
1273/// if there is an error.
1274bool
1275Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001276 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001277 unsigned AmbigiousBaseConvID,
1278 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001279 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001280 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001281 // First, determine whether the path from Derived to Base is
1282 // ambiguous. This is slightly more expensive than checking whether
1283 // the Derived to Base conversion exists, because here we need to
1284 // explore multiple paths to determine if there is an ambiguity.
1285 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1286 /*DetectVirtual=*/false);
1287 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1288 assert(DerivationOkay &&
1289 "Can only be used with a derived-to-base conversion");
1290 (void)DerivationOkay;
1291
1292 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001293 if (InaccessibleBaseID) {
1294 // Check that the base class can be accessed.
1295 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1296 InaccessibleBaseID)) {
1297 case AR_inaccessible:
1298 return true;
1299 case AR_accessible:
1300 case AR_dependent:
1301 case AR_delayed:
1302 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001303 }
John McCall6b2accb2010-02-10 09:31:12 +00001304 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001305
1306 // Build a base path if necessary.
1307 if (BasePath)
1308 BuildBasePathArray(Paths, *BasePath);
1309 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001310 }
1311
1312 // We know that the derived-to-base conversion is ambiguous, and
1313 // we're going to produce a diagnostic. Perform the derived-to-base
1314 // search just one more time to compute all of the possible paths so
1315 // that we can print them out. This is more expensive than any of
1316 // the previous derived-to-base checks we've done, but at this point
1317 // performance isn't as much of an issue.
1318 Paths.clear();
1319 Paths.setRecordingPaths(true);
1320 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1321 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1322 (void)StillOkay;
1323
1324 // Build up a textual representation of the ambiguous paths, e.g.,
1325 // D -> B -> A, that will be used to illustrate the ambiguous
1326 // conversions in the diagnostic. We only print one of the paths
1327 // to each base class subobject.
1328 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1329
1330 Diag(Loc, AmbigiousBaseConvID)
1331 << Derived << Base << PathDisplayStr << Range << Name;
1332 return true;
1333}
1334
1335bool
1336Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001337 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001338 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001339 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001340 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001341 IgnoreAccess ? 0
1342 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001343 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001344 Loc, Range, DeclarationName(),
1345 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001346}
1347
1348
1349/// @brief Builds a string representing ambiguous paths from a
1350/// specific derived class to different subobjects of the same base
1351/// class.
1352///
1353/// This function builds a string that can be used in error messages
1354/// to show the different paths that one can take through the
1355/// inheritance hierarchy to go from the derived class to different
1356/// subobjects of a base class. The result looks something like this:
1357/// @code
1358/// struct D -> struct B -> struct A
1359/// struct D -> struct C -> struct A
1360/// @endcode
1361std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1362 std::string PathDisplayStr;
1363 std::set<unsigned> DisplayedPaths;
1364 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1365 Path != Paths.end(); ++Path) {
1366 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1367 // We haven't displayed a path to this particular base
1368 // class subobject yet.
1369 PathDisplayStr += "\n ";
1370 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1371 for (CXXBasePath::const_iterator Element = Path->begin();
1372 Element != Path->end(); ++Element)
1373 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1374 }
1375 }
1376
1377 return PathDisplayStr;
1378}
1379
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001380//===----------------------------------------------------------------------===//
1381// C++ class member Handling
1382//===----------------------------------------------------------------------===//
1383
Abramo Bagnara6206d532010-06-05 05:09:32 +00001384/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001385bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1386 SourceLocation ASLoc,
1387 SourceLocation ColonLoc,
1388 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001389 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001390 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001391 ASLoc, ColonLoc);
1392 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001393 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001394}
1395
Anders Carlsson9e682d92011-01-20 05:57:14 +00001396/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001397void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001398 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001399 if (!MD || !MD->isVirtual())
1400 return;
1401
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001402 if (MD->isDependentContext())
1403 return;
1404
Anders Carlsson9e682d92011-01-20 05:57:14 +00001405 // C++0x [class.virtual]p3:
1406 // If a virtual function is marked with the virt-specifier override and does
1407 // not override a member function of a base class,
1408 // the program is ill-formed.
1409 bool HasOverriddenMethods =
1410 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001411 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001412 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001413 diag::err_function_marked_override_not_overriding)
1414 << MD->getDeclName();
1415 return;
1416 }
1417}
1418
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001419/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1420/// function overrides a virtual member function marked 'final', according to
1421/// C++0x [class.virtual]p3.
1422bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1423 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001424 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001425 return false;
1426
1427 Diag(New->getLocation(), diag::err_final_function_overridden)
1428 << New->getDeclName();
1429 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1430 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001431}
1432
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001433/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1434/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001435/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1436/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1437/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001438Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001439Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001440 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001441 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001442 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001443 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001444 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1445 DeclarationName Name = NameInfo.getName();
1446 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001447
1448 // For anonymous bitfields, the location should point to the type.
1449 if (Loc.isInvalid())
1450 Loc = D.getSourceRange().getBegin();
1451
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001452 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001453
John McCall4bde1e12010-06-04 08:34:12 +00001454 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001455 assert(!DS.isFriendSpecified());
1456
Richard Smith1ab0d902011-06-25 02:28:38 +00001457 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001458
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001459 // C++ 9.2p6: A member shall not be declared to have automatic storage
1460 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001461 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1462 // data members and cannot be applied to names declared const or static,
1463 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001464 switch (DS.getStorageClassSpec()) {
1465 case DeclSpec::SCS_unspecified:
1466 case DeclSpec::SCS_typedef:
1467 case DeclSpec::SCS_static:
1468 // FALL THROUGH.
1469 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001470 case DeclSpec::SCS_mutable:
1471 if (isFunc) {
1472 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001473 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001474 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001475 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Sebastian Redla11f42f2008-11-17 23:24:37 +00001477 // FIXME: It would be nicer if the keyword was ignored only for this
1478 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001479 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001480 }
1481 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001482 default:
1483 if (DS.getStorageClassSpecLoc().isValid())
1484 Diag(DS.getStorageClassSpecLoc(),
1485 diag::err_storageclass_invalid_for_member);
1486 else
1487 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1488 D.getMutableDeclSpec().ClearStorageClassSpecs();
1489 }
1490
Sebastian Redl669d5d72008-11-14 23:42:31 +00001491 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1492 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001493 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001494
1495 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001496 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001497 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001498
1499 // Data members must have identifiers for names.
1500 if (Name.getNameKind() != DeclarationName::Identifier) {
1501 Diag(Loc, diag::err_bad_variable_name)
1502 << Name;
1503 return 0;
1504 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001505
Douglas Gregorf2503652011-09-21 14:40:46 +00001506 IdentifierInfo *II = Name.getAsIdentifierInfo();
1507
1508 // Member field could not be with "template" keyword.
1509 // So TemplateParameterLists should be empty in this case.
1510 if (TemplateParameterLists.size()) {
1511 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1512 if (TemplateParams->size()) {
1513 // There is no such thing as a member field template.
1514 Diag(D.getIdentifierLoc(), diag::err_template_member)
1515 << II
1516 << SourceRange(TemplateParams->getTemplateLoc(),
1517 TemplateParams->getRAngleLoc());
1518 } else {
1519 // There is an extraneous 'template<>' for this member.
1520 Diag(TemplateParams->getTemplateLoc(),
1521 diag::err_template_member_noparams)
1522 << II
1523 << SourceRange(TemplateParams->getTemplateLoc(),
1524 TemplateParams->getRAngleLoc());
1525 }
1526 return 0;
1527 }
1528
Douglas Gregor922fff22010-10-13 22:19:53 +00001529 if (SS.isSet() && !SS.isInvalid()) {
1530 // The user provided a superfluous scope specifier inside a class
1531 // definition:
1532 //
1533 // class X {
1534 // int X::member;
1535 // };
1536 DeclContext *DC = 0;
1537 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1538 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001539 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001540 else
1541 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1542 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001543
Douglas Gregor922fff22010-10-13 22:19:53 +00001544 SS.clear();
1545 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001546
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001547 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001548 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001549 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001550 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001551 assert(!HasDeferredInit);
1552
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001553 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001554 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001555 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001556 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001557
1558 // Non-instance-fields can't have a bitfield.
1559 if (BitWidth) {
1560 if (Member->isInvalidDecl()) {
1561 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001562 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001563 // C++ 9.6p3: A bit-field shall not be a static member.
1564 // "static member 'A' cannot be a bit-field"
1565 Diag(Loc, diag::err_static_not_bitfield)
1566 << Name << BitWidth->getSourceRange();
1567 } else if (isa<TypedefDecl>(Member)) {
1568 // "typedef member 'x' cannot be a bit-field"
1569 Diag(Loc, diag::err_typedef_not_bitfield)
1570 << Name << BitWidth->getSourceRange();
1571 } else {
1572 // A function typedef ("typedef int f(); f a;").
1573 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1574 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001575 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001576 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001577 }
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Chris Lattner8b963ef2009-03-05 23:01:03 +00001579 BitWidth = 0;
1580 Member->setInvalidDecl();
1581 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001582
1583 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Douglas Gregor37b372b2009-08-20 22:52:58 +00001585 // If we have declared a member function template, set the access of the
1586 // templated declaration as well.
1587 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1588 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001589 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001590
Anders Carlssonaae5af22011-01-20 04:34:22 +00001591 if (VS.isOverrideSpecified()) {
1592 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1593 if (!MD || !MD->isVirtual()) {
1594 Diag(Member->getLocStart(),
1595 diag::override_keyword_only_allowed_on_virtual_member_functions)
1596 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001597 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001598 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001599 }
1600 if (VS.isFinalSpecified()) {
1601 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1602 if (!MD || !MD->isVirtual()) {
1603 Diag(Member->getLocStart(),
1604 diag::override_keyword_only_allowed_on_virtual_member_functions)
1605 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001606 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001607 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001608 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001609
Douglas Gregorf5251602011-03-08 17:10:18 +00001610 if (VS.getLastLocation().isValid()) {
1611 // Update the end location of a method that has a virt-specifiers.
1612 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1613 MD->setRangeEnd(VS.getLastLocation());
1614 }
1615
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001616 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001617
Douglas Gregor10bd3682008-11-17 22:58:34 +00001618 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001619
John McCallb25b2952011-02-15 07:12:36 +00001620 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001621 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001622 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001623}
1624
Richard Smith7a614d82011-06-11 17:19:42 +00001625/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001626/// in-class initializer for a non-static C++ class member, and after
1627/// instantiating an in-class initializer in a class template. Such actions
1628/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001629void
1630Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1631 Expr *InitExpr) {
1632 FieldDecl *FD = cast<FieldDecl>(D);
1633
1634 if (!InitExpr) {
1635 FD->setInvalidDecl();
1636 FD->removeInClassInitializer();
1637 return;
1638 }
1639
Peter Collingbournefef21892011-10-23 18:59:44 +00001640 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1641 FD->setInvalidDecl();
1642 FD->removeInClassInitializer();
1643 return;
1644 }
1645
Richard Smith7a614d82011-06-11 17:19:42 +00001646 ExprResult Init = InitExpr;
1647 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1648 // FIXME: if there is no EqualLoc, this is list-initialization.
1649 Init = PerformCopyInitialization(
1650 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1651 if (Init.isInvalid()) {
1652 FD->setInvalidDecl();
1653 return;
1654 }
1655
1656 CheckImplicitConversions(Init.get(), EqualLoc);
1657 }
1658
1659 // C++0x [class.base.init]p7:
1660 // The initialization of each base and member constitutes a
1661 // full-expression.
1662 Init = MaybeCreateExprWithCleanups(Init);
1663 if (Init.isInvalid()) {
1664 FD->setInvalidDecl();
1665 return;
1666 }
1667
1668 InitExpr = Init.release();
1669
1670 FD->setInClassInitializer(InitExpr);
1671}
1672
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001673/// \brief Find the direct and/or virtual base specifiers that
1674/// correspond to the given base type, for use in base initialization
1675/// within a constructor.
1676static bool FindBaseInitializer(Sema &SemaRef,
1677 CXXRecordDecl *ClassDecl,
1678 QualType BaseType,
1679 const CXXBaseSpecifier *&DirectBaseSpec,
1680 const CXXBaseSpecifier *&VirtualBaseSpec) {
1681 // First, check for a direct base class.
1682 DirectBaseSpec = 0;
1683 for (CXXRecordDecl::base_class_const_iterator Base
1684 = ClassDecl->bases_begin();
1685 Base != ClassDecl->bases_end(); ++Base) {
1686 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1687 // We found a direct base of this type. That's what we're
1688 // initializing.
1689 DirectBaseSpec = &*Base;
1690 break;
1691 }
1692 }
1693
1694 // Check for a virtual base class.
1695 // FIXME: We might be able to short-circuit this if we know in advance that
1696 // there are no virtual bases.
1697 VirtualBaseSpec = 0;
1698 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1699 // We haven't found a base yet; search the class hierarchy for a
1700 // virtual base class.
1701 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1702 /*DetectVirtual=*/false);
1703 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1704 BaseType, Paths)) {
1705 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1706 Path != Paths.end(); ++Path) {
1707 if (Path->back().Base->isVirtual()) {
1708 VirtualBaseSpec = Path->back().Base;
1709 break;
1710 }
1711 }
1712 }
1713 }
1714
1715 return DirectBaseSpec || VirtualBaseSpec;
1716}
1717
Sebastian Redl6df65482011-09-24 17:48:25 +00001718/// \brief Handle a C++ member initializer using braced-init-list syntax.
1719MemInitResult
1720Sema::ActOnMemInitializer(Decl *ConstructorD,
1721 Scope *S,
1722 CXXScopeSpec &SS,
1723 IdentifierInfo *MemberOrBase,
1724 ParsedType TemplateTypeTy,
1725 SourceLocation IdLoc,
1726 Expr *InitList,
1727 SourceLocation EllipsisLoc) {
1728 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1729 IdLoc, MultiInitializer(InitList), EllipsisLoc);
1730}
1731
1732/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001733MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001734Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001735 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001736 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001737 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001738 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001739 SourceLocation IdLoc,
1740 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001741 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001742 SourceLocation RParenLoc,
1743 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001744 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1745 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs,
1746 RParenLoc),
1747 EllipsisLoc);
1748}
1749
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001750namespace {
1751
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001752// Callback to only accept typo corrections that can be a valid C++ member
1753// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001754class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1755 public:
1756 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1757 : ClassDecl(ClassDecl) {}
1758
1759 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1760 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1761 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1762 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1763 else
1764 return isa<TypeDecl>(ND);
1765 }
1766 return false;
1767 }
1768
1769 private:
1770 CXXRecordDecl *ClassDecl;
1771};
1772
1773}
1774
Sebastian Redl6df65482011-09-24 17:48:25 +00001775/// \brief Handle a C++ member initializer.
1776MemInitResult
1777Sema::BuildMemInitializer(Decl *ConstructorD,
1778 Scope *S,
1779 CXXScopeSpec &SS,
1780 IdentifierInfo *MemberOrBase,
1781 ParsedType TemplateTypeTy,
1782 SourceLocation IdLoc,
1783 const MultiInitializer &Args,
1784 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001785 if (!ConstructorD)
1786 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001788 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001789
1790 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001791 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001792 if (!Constructor) {
1793 // The user wrote a constructor initializer on a function that is
1794 // not a C++ constructor. Ignore the error for now, because we may
1795 // have more member initializers coming; we'll diagnose it just
1796 // once in ActOnMemInitializers.
1797 return true;
1798 }
1799
1800 CXXRecordDecl *ClassDecl = Constructor->getParent();
1801
1802 // C++ [class.base.init]p2:
1803 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001804 // constructor's class and, if not found in that scope, are looked
1805 // up in the scope containing the constructor's definition.
1806 // [Note: if the constructor's class contains a member with the
1807 // same name as a direct or virtual base class of the class, a
1808 // mem-initializer-id naming the member or base class and composed
1809 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001810 // mem-initializer-id for the hidden base class may be specified
1811 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001812 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001813 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001814 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001815 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001816 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001817 ValueDecl *Member;
1818 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1819 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001820 if (EllipsisLoc.isValid())
1821 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001822 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1823
1824 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001825 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001826 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001827 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001828 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001829 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001830 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001831
1832 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001833 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001834 } else {
1835 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1836 LookupParsedName(R, S, &SS);
1837
1838 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1839 if (!TyD) {
1840 if (R.isAmbiguous()) return true;
1841
John McCallfd225442010-04-09 19:01:14 +00001842 // We don't want access-control diagnostics here.
1843 R.suppressDiagnostics();
1844
Douglas Gregor7a886e12010-01-19 06:46:48 +00001845 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1846 bool NotUnknownSpecialization = false;
1847 DeclContext *DC = computeDeclContext(SS, false);
1848 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1849 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1850
1851 if (!NotUnknownSpecialization) {
1852 // When the scope specifier can refer to a member of an unknown
1853 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001854 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1855 SS.getWithLocInContext(Context),
1856 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001857 if (BaseType.isNull())
1858 return true;
1859
Douglas Gregor7a886e12010-01-19 06:46:48 +00001860 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001861 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001862 }
1863 }
1864
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001865 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001866 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001867 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001868 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001869 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001870 &Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001871 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1872 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1873 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001874 // We have found a non-static data member with a similar
1875 // name to what was typed; complain and initialize that
1876 // member.
1877 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1878 << MemberOrBase << true << CorrectedQuotedStr
1879 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1880 Diag(Member->getLocation(), diag::note_previous_decl)
1881 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001882
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001883 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001884 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001885 const CXXBaseSpecifier *DirectBaseSpec;
1886 const CXXBaseSpecifier *VirtualBaseSpec;
1887 if (FindBaseInitializer(*this, ClassDecl,
1888 Context.getTypeDeclType(Type),
1889 DirectBaseSpec, VirtualBaseSpec)) {
1890 // We have found a direct or virtual base class with a
1891 // similar name to what was typed; complain and initialize
1892 // that base class.
1893 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001894 << MemberOrBase << false << CorrectedQuotedStr
1895 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001896
1897 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1898 : VirtualBaseSpec;
1899 Diag(BaseSpec->getSourceRange().getBegin(),
1900 diag::note_base_class_specified_here)
1901 << BaseSpec->getType()
1902 << BaseSpec->getSourceRange();
1903
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001904 TyD = Type;
1905 }
1906 }
1907 }
1908
Douglas Gregor7a886e12010-01-19 06:46:48 +00001909 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001910 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001911 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001912 return true;
1913 }
John McCall2b194412009-12-21 10:41:20 +00001914 }
1915
Douglas Gregor7a886e12010-01-19 06:46:48 +00001916 if (BaseType.isNull()) {
1917 BaseType = Context.getTypeDeclType(TyD);
1918 if (SS.isSet()) {
1919 NestedNameSpecifier *Qualifier =
1920 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001921
Douglas Gregor7a886e12010-01-19 06:46:48 +00001922 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001923 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001924 }
John McCall2b194412009-12-21 10:41:20 +00001925 }
1926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
John McCalla93c9342009-12-07 02:54:59 +00001928 if (!TInfo)
1929 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001930
Sebastian Redl6df65482011-09-24 17:48:25 +00001931 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001932}
1933
Chandler Carruth81c64772011-09-03 01:14:15 +00001934/// Checks a member initializer expression for cases where reference (or
1935/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001936static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1937 Expr *Init,
1938 SourceLocation IdLoc) {
1939 QualType MemberTy = Member->getType();
1940
1941 // We only handle pointers and references currently.
1942 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1943 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1944 return;
1945
1946 const bool IsPointer = MemberTy->isPointerType();
1947 if (IsPointer) {
1948 if (const UnaryOperator *Op
1949 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1950 // The only case we're worried about with pointers requires taking the
1951 // address.
1952 if (Op->getOpcode() != UO_AddrOf)
1953 return;
1954
1955 Init = Op->getSubExpr();
1956 } else {
1957 // We only handle address-of expression initializers for pointers.
1958 return;
1959 }
1960 }
1961
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001962 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1963 // Taking the address of a temporary will be diagnosed as a hard error.
1964 if (IsPointer)
1965 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001966
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001967 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1968 << Member << Init->getSourceRange();
1969 } else if (const DeclRefExpr *DRE
1970 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1971 // We only warn when referring to a non-reference parameter declaration.
1972 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1973 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001974 return;
1975
1976 S.Diag(Init->getExprLoc(),
1977 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1978 : diag::warn_bind_ref_member_to_parameter)
1979 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001980 } else {
1981 // Other initializers are fine.
1982 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001983 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001984
1985 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1986 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00001987}
1988
John McCallb4190042009-11-04 23:02:40 +00001989/// Checks an initializer expression for use of uninitialized fields, such as
1990/// containing the field that is being initialized. Returns true if there is an
1991/// uninitialized field was used an updates the SourceLocation parameter; false
1992/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001993static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001994 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001995 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001996 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1997
Nick Lewycky43ad1822010-06-15 07:32:55 +00001998 if (isa<CallExpr>(S)) {
1999 // Do not descend into function calls or constructors, as the use
2000 // of an uninitialized field may be valid. One would have to inspect
2001 // the contents of the function/ctor to determine if it is safe or not.
2002 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2003 // may be safe, depending on what the function/ctor does.
2004 return false;
2005 }
2006 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2007 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002008
2009 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2010 // The member expression points to a static data member.
2011 assert(VD->isStaticDataMember() &&
2012 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002013 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002014 return false;
2015 }
2016
2017 if (isa<EnumConstantDecl>(RhsField)) {
2018 // The member expression points to an enum.
2019 return false;
2020 }
2021
John McCallb4190042009-11-04 23:02:40 +00002022 if (RhsField == LhsField) {
2023 // Initializing a field with itself. Throw a warning.
2024 // But wait; there are exceptions!
2025 // Exception #1: The field may not belong to this record.
2026 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002027 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002028 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2029 // Even though the field matches, it does not belong to this record.
2030 return false;
2031 }
2032 // None of the exceptions triggered; return true to indicate an
2033 // uninitialized field was used.
2034 *L = ME->getMemberLoc();
2035 return true;
2036 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002037 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002038 // sizeof/alignof doesn't reference contents, do not warn.
2039 return false;
2040 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2041 // address-of doesn't reference contents (the pointer may be dereferenced
2042 // in the same expression but it would be rare; and weird).
2043 if (UOE->getOpcode() == UO_AddrOf)
2044 return false;
John McCallb4190042009-11-04 23:02:40 +00002045 }
John McCall7502c1d2011-02-13 04:07:26 +00002046 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002047 if (!*it) {
2048 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002049 continue;
2050 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002051 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2052 return true;
John McCallb4190042009-11-04 23:02:40 +00002053 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002054 return false;
John McCallb4190042009-11-04 23:02:40 +00002055}
2056
John McCallf312b1e2010-08-26 23:41:50 +00002057MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002058Sema::BuildMemberInitializer(ValueDecl *Member,
2059 const MultiInitializer &Args,
2060 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002061 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2062 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2063 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002064 "Member must be a FieldDecl or IndirectFieldDecl");
2065
Peter Collingbournefef21892011-10-23 18:59:44 +00002066 if (Args.DiagnoseUnexpandedParameterPack(*this))
2067 return true;
2068
Douglas Gregor464b2f02010-11-05 22:21:31 +00002069 if (Member->isInvalidDecl())
2070 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002071
John McCallb4190042009-11-04 23:02:40 +00002072 // Diagnose value-uses of fields to initialize themselves, e.g.
2073 // foo(foo)
2074 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002075 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00002076 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2077 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002078 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002079 Expr *Arg = *I;
2080 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2081 Arg = DIE->getInit();
2082 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002083 // FIXME: Return true in the case when other fields are used before being
2084 // uninitialized. For example, let this field be the i'th field. When
2085 // initializing the i'th field, throw a warning if any of the >= i'th
2086 // fields are used, as they are not yet initialized.
2087 // Right now we are only handling the case where the i'th field uses
2088 // itself in its initializer.
2089 Diag(L, diag::warn_field_is_uninit);
2090 }
2091 }
2092
Sebastian Redl6df65482011-09-24 17:48:25 +00002093 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002094
Chandler Carruth894aed92010-12-06 09:23:57 +00002095 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002096 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002097 // Can't check initialization for a member of dependent type or when
2098 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002099 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002100
John McCallf85e1932011-06-15 23:02:42 +00002101 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002102 } else {
2103 // Initialize the member.
2104 InitializedEntity MemberEntity =
2105 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2106 : InitializedEntity::InitializeMember(IndirectMember, 0);
2107 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002108 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2109 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002110
Sebastian Redl6df65482011-09-24 17:48:25 +00002111 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002112 if (MemberInit.isInvalid())
2113 return true;
2114
Sebastian Redl6df65482011-09-24 17:48:25 +00002115 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002116
2117 // C++0x [class.base.init]p7:
2118 // The initialization of each base and member constitutes a
2119 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002120 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002121 if (MemberInit.isInvalid())
2122 return true;
2123
2124 // If we are in a dependent context, template instantiation will
2125 // perform this type-checking again. Just save the arguments that we
2126 // received in a ParenListExpr.
2127 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2128 // of the information that we have about the member
2129 // initializer. However, deconstructing the ASTs is a dicey process,
2130 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002131 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002132 Init = Args.CreateInitExpr(Context,
2133 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002134 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002135 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002136 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2137 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002138 }
2139
Chandler Carruth894aed92010-12-06 09:23:57 +00002140 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002141 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002142 IdLoc, Args.getStartLoc(),
2143 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002144 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002145 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002146 IdLoc, Args.getStartLoc(),
2147 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002148 }
Eli Friedman59c04372009-07-29 19:44:27 +00002149}
2150
John McCallf312b1e2010-08-26 23:41:50 +00002151MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002152Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002153 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002154 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002155 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002156 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002157 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002158 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002159 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002160
Sean Hunt41717662011-02-26 19:13:13 +00002161 // Initialize the object.
2162 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2163 QualType(ClassDecl->getTypeForDecl(), 0));
2164 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002165 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2166 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002167
Sebastian Redl6df65482011-09-24 17:48:25 +00002168 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002169 if (DelegationInit.isInvalid())
2170 return true;
2171
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002172 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2173 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002174
Sebastian Redl6df65482011-09-24 17:48:25 +00002175 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002176
2177 // C++0x [class.base.init]p7:
2178 // The initialization of each base and member constitutes a
2179 // full-expression.
2180 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2181 if (DelegationInit.isInvalid())
2182 return true;
2183
Douglas Gregor76852c22011-11-01 01:16:03 +00002184 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Sean Hunt41717662011-02-26 19:13:13 +00002185 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002186 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002187}
2188
2189MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002190Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002191 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002192 CXXRecordDecl *ClassDecl,
2193 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002194 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002195
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002196 SourceLocation BaseLoc
2197 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002198
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002199 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2200 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2201 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2202
2203 // C++ [class.base.init]p2:
2204 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002205 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002206 // of that class, the mem-initializer is ill-formed. A
2207 // mem-initializer-list can initialize a base class using any
2208 // name that denotes that base class type.
2209 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2210
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002211 if (EllipsisLoc.isValid()) {
2212 // This is a pack expansion.
2213 if (!BaseType->containsUnexpandedParameterPack()) {
2214 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002215 << SourceRange(BaseLoc, Args.getEndLoc());
2216
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002217 EllipsisLoc = SourceLocation();
2218 }
2219 } else {
2220 // Check for any unexpanded parameter packs.
2221 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2222 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002223
2224 if (Args.DiagnoseUnexpandedParameterPack(*this))
2225 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002226 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002227
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002228 // Check for direct and virtual base classes.
2229 const CXXBaseSpecifier *DirectBaseSpec = 0;
2230 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2231 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002232 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2233 BaseType))
Douglas Gregor76852c22011-11-01 01:16:03 +00002234 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002235
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002236 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2237 VirtualBaseSpec);
2238
2239 // C++ [base.class.init]p2:
2240 // Unless the mem-initializer-id names a nonstatic data member of the
2241 // constructor's class or a direct or virtual base of that class, the
2242 // mem-initializer is ill-formed.
2243 if (!DirectBaseSpec && !VirtualBaseSpec) {
2244 // If the class has any dependent bases, then it's possible that
2245 // one of those types will resolve to the same type as
2246 // BaseType. Therefore, just treat this as a dependent base
2247 // class initialization. FIXME: Should we try to check the
2248 // initialization anyway? It seems odd.
2249 if (ClassDecl->hasAnyDependentBases())
2250 Dependent = true;
2251 else
2252 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2253 << BaseType << Context.getTypeDeclType(ClassDecl)
2254 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2255 }
2256 }
2257
2258 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002259 // Can't check initialization for a base of dependent type or when
2260 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002261 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002262
John McCallf85e1932011-06-15 23:02:42 +00002263 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Sebastian Redl6df65482011-09-24 17:48:25 +00002265 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2266 /*IsVirtual=*/false,
2267 Args.getStartLoc(), BaseInit,
2268 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002269 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002270
2271 // C++ [base.class.init]p2:
2272 // If a mem-initializer-id is ambiguous because it designates both
2273 // a direct non-virtual base class and an inherited virtual base
2274 // class, the mem-initializer is ill-formed.
2275 if (DirectBaseSpec && VirtualBaseSpec)
2276 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002277 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002278
2279 CXXBaseSpecifier *BaseSpec
2280 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2281 if (!BaseSpec)
2282 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2283
2284 // Initialize the base.
2285 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002286 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002287 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002288 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2289 Args.getEndLoc());
2290
2291 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002292 if (BaseInit.isInvalid())
2293 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002294
Sebastian Redl6df65482011-09-24 17:48:25 +00002295 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2296
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002297 // C++0x [class.base.init]p7:
2298 // The initialization of each base and member constitutes a
2299 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002300 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002301 if (BaseInit.isInvalid())
2302 return true;
2303
2304 // If we are in a dependent context, template instantiation will
2305 // perform this type-checking again. Just save the arguments that we
2306 // received in a ParenListExpr.
2307 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2308 // of the information that we have about the base
2309 // initializer. However, deconstructing the ASTs is a dicey process,
2310 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002311 if (CurContext->isDependentContext())
2312 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002313
Sean Huntcbb67482011-01-08 20:30:50 +00002314 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002315 BaseSpec->isVirtual(),
2316 Args.getStartLoc(),
2317 BaseInit.takeAs<Expr>(),
2318 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002319}
2320
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002321// Create a static_cast\<T&&>(expr).
2322static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2323 QualType ExprType = E->getType();
2324 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2325 SourceLocation ExprLoc = E->getLocStart();
2326 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2327 TargetType, ExprLoc);
2328
2329 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2330 SourceRange(ExprLoc, ExprLoc),
2331 E->getSourceRange()).take();
2332}
2333
Anders Carlssone5ef7402010-04-23 03:10:23 +00002334/// ImplicitInitializerKind - How an implicit base or member initializer should
2335/// initialize its base or member.
2336enum ImplicitInitializerKind {
2337 IIK_Default,
2338 IIK_Copy,
2339 IIK_Move
2340};
2341
Anders Carlssondefefd22010-04-23 02:00:02 +00002342static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002343BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002344 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002345 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002346 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002347 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002348 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002349 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2350 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002351
John McCall60d7b3a2010-08-24 06:29:42 +00002352 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002353
2354 switch (ImplicitInitKind) {
2355 case IIK_Default: {
2356 InitializationKind InitKind
2357 = InitializationKind::CreateDefault(Constructor->getLocation());
2358 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2359 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002360 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002361 break;
2362 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002363
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002364 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002365 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002366 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002367 ParmVarDecl *Param = Constructor->getParamDecl(0);
2368 QualType ParamType = Param->getType().getNonReferenceType();
2369
2370 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002371 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002372 Constructor->getLocation(), ParamType,
2373 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002374
Anders Carlssonc7957502010-04-24 22:02:54 +00002375 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002376 QualType ArgTy =
2377 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2378 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002379
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002380 if (Moving) {
2381 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2382 }
2383
John McCallf871d0c2010-08-07 06:22:56 +00002384 CXXCastPath BasePath;
2385 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002386 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2387 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002388 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002389 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002390
Anders Carlssone5ef7402010-04-23 03:10:23 +00002391 InitializationKind InitKind
2392 = InitializationKind::CreateDirect(Constructor->getLocation(),
2393 SourceLocation(), SourceLocation());
2394 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2395 &CopyCtorArg, 1);
2396 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002397 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002398 break;
2399 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002400 }
John McCall9ae2f072010-08-23 23:25:46 +00002401
Douglas Gregor53c374f2010-12-07 00:41:46 +00002402 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002403 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002404 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002405
Anders Carlssondefefd22010-04-23 02:00:02 +00002406 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002407 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002408 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2409 SourceLocation()),
2410 BaseSpec->isVirtual(),
2411 SourceLocation(),
2412 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002413 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002414 SourceLocation());
2415
Anders Carlssondefefd22010-04-23 02:00:02 +00002416 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002417}
2418
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002419static bool RefersToRValueRef(Expr *MemRef) {
2420 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2421 return Referenced->getType()->isRValueReferenceType();
2422}
2423
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002424static bool
2425BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002426 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002427 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002428 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002429 if (Field->isInvalidDecl())
2430 return true;
2431
Chandler Carruthf186b542010-06-29 23:50:44 +00002432 SourceLocation Loc = Constructor->getLocation();
2433
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002434 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2435 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002436 ParmVarDecl *Param = Constructor->getParamDecl(0);
2437 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002438
2439 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002440 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2441 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002442
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002443 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002444 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002445 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002446
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002447 if (Moving) {
2448 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2449 }
2450
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002451 // Build a reference to this field within the parameter.
2452 CXXScopeSpec SS;
2453 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2454 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002455 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2456 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002457 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002458 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002459 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002460 ParamType, Loc,
2461 /*IsArrow=*/false,
2462 SS,
2463 /*FirstQualifierInScope=*/0,
2464 MemberLookup,
2465 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002466 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002467 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002468
2469 // C++11 [class.copy]p15:
2470 // - if a member m has rvalue reference type T&&, it is direct-initialized
2471 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002472 if (RefersToRValueRef(CtorArg.get())) {
2473 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002474 }
2475
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002476 // When the field we are copying is an array, create index variables for
2477 // each dimension of the array. We use these index variables to subscript
2478 // the source array, and other clients (e.g., CodeGen) will perform the
2479 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002480 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002481 QualType BaseType = Field->getType();
2482 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002483 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002484 while (const ConstantArrayType *Array
2485 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002486 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002487 // Create the iteration variable for this array index.
2488 IdentifierInfo *IterationVarName = 0;
2489 {
2490 llvm::SmallString<8> Str;
2491 llvm::raw_svector_ostream OS(Str);
2492 OS << "__i" << IndexVariables.size();
2493 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2494 }
2495 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002496 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002497 IterationVarName, SizeType,
2498 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002499 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002500 IndexVariables.push_back(IterationVar);
2501
2502 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002503 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002504 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002505 assert(!IterationVarRef.isInvalid() &&
2506 "Reference to invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002507
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002508 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002509 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002510 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002511 Loc);
2512 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002513 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002514
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002515 BaseType = Array->getElementType();
2516 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002517
2518 // The array subscript expression is an lvalue, which is wrong for moving.
2519 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002520 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002521
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002522 // Construct the entity that we will be initializing. For an array, this
2523 // will be first element in the array, which may require several levels
2524 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002525 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002526 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002527 if (Indirect)
2528 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2529 else
2530 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002531 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2532 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2533 0,
2534 Entities.back()));
2535
2536 // Direct-initialize to use the copy constructor.
2537 InitializationKind InitKind =
2538 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2539
Sebastian Redl74e611a2011-09-04 18:14:28 +00002540 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002541 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002542 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002543
John McCall60d7b3a2010-08-24 06:29:42 +00002544 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002545 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002546 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002547 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002548 if (MemberInit.isInvalid())
2549 return true;
2550
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002551 if (Indirect) {
2552 assert(IndexVariables.size() == 0 &&
2553 "Indirect field improperly initialized");
2554 CXXMemberInit
2555 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2556 Loc, Loc,
2557 MemberInit.takeAs<Expr>(),
2558 Loc);
2559 } else
2560 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2561 Loc, MemberInit.takeAs<Expr>(),
2562 Loc,
2563 IndexVariables.data(),
2564 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002565 return false;
2566 }
2567
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002568 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2569
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002570 QualType FieldBaseElementType =
2571 SemaRef.Context.getBaseElementType(Field->getType());
2572
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002573 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002574 InitializedEntity InitEntity
2575 = Indirect? InitializedEntity::InitializeMember(Indirect)
2576 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002577 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002578 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002579
2580 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002581 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002582 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002583
Douglas Gregor53c374f2010-12-07 00:41:46 +00002584 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002585 if (MemberInit.isInvalid())
2586 return true;
2587
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002588 if (Indirect)
2589 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2590 Indirect, Loc,
2591 Loc,
2592 MemberInit.get(),
2593 Loc);
2594 else
2595 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2596 Field, Loc, Loc,
2597 MemberInit.get(),
2598 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002599 return false;
2600 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002601
Sean Hunt1f2f3842011-05-17 00:19:05 +00002602 if (!Field->getParent()->isUnion()) {
2603 if (FieldBaseElementType->isReferenceType()) {
2604 SemaRef.Diag(Constructor->getLocation(),
2605 diag::err_uninitialized_member_in_ctor)
2606 << (int)Constructor->isImplicit()
2607 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2608 << 0 << Field->getDeclName();
2609 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2610 return true;
2611 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002612
Sean Hunt1f2f3842011-05-17 00:19:05 +00002613 if (FieldBaseElementType.isConstQualified()) {
2614 SemaRef.Diag(Constructor->getLocation(),
2615 diag::err_uninitialized_member_in_ctor)
2616 << (int)Constructor->isImplicit()
2617 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2618 << 1 << Field->getDeclName();
2619 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2620 return true;
2621 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002622 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002623
John McCallf85e1932011-06-15 23:02:42 +00002624 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2625 FieldBaseElementType->isObjCRetainableType() &&
2626 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2627 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2628 // Instant objects:
2629 // Default-initialize Objective-C pointers to NULL.
2630 CXXMemberInit
2631 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2632 Loc, Loc,
2633 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2634 Loc);
2635 return false;
2636 }
2637
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002638 // Nothing to initialize.
2639 CXXMemberInit = 0;
2640 return false;
2641}
John McCallf1860e52010-05-20 23:23:51 +00002642
2643namespace {
2644struct BaseAndFieldInfo {
2645 Sema &S;
2646 CXXConstructorDecl *Ctor;
2647 bool AnyErrorsInInits;
2648 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002649 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002650 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002651
2652 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2653 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002654 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2655 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002656 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002657 else if (Generated && Ctor->isMoveConstructor())
2658 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002659 else
2660 IIK = IIK_Default;
2661 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002662
2663 bool isImplicitCopyOrMove() const {
2664 switch (IIK) {
2665 case IIK_Copy:
2666 case IIK_Move:
2667 return true;
2668
2669 case IIK_Default:
2670 return false;
2671 }
2672
2673 return false;
2674 }
John McCallf1860e52010-05-20 23:23:51 +00002675};
2676}
2677
Richard Smitha4950662011-09-19 13:34:43 +00002678/// \brief Determine whether the given indirect field declaration is somewhere
2679/// within an anonymous union.
2680static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2681 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2682 CEnd = F->chain_end();
2683 C != CEnd; ++C)
2684 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2685 if (Record->isUnion())
2686 return true;
2687
2688 return false;
2689}
2690
Douglas Gregorddb21472011-11-02 23:04:16 +00002691/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2692/// array type.
2693static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2694 if (T->isIncompleteArrayType())
2695 return true;
2696
2697 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2698 if (!ArrayT->getSize())
2699 return true;
2700
2701 T = ArrayT->getElementType();
2702 }
2703
2704 return false;
2705}
2706
Richard Smith7a614d82011-06-11 17:19:42 +00002707static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002708 FieldDecl *Field,
2709 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002710
Chandler Carruthe861c602010-06-30 02:59:29 +00002711 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002712 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002713 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002714 return false;
2715 }
2716
Richard Smith7a614d82011-06-11 17:19:42 +00002717 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2718 // has a brace-or-equal-initializer, the entity is initialized as specified
2719 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002720 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002721 CXXCtorInitializer *Init;
2722 if (Indirect)
2723 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2724 SourceLocation(),
2725 SourceLocation(), 0,
2726 SourceLocation());
2727 else
2728 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2729 SourceLocation(),
2730 SourceLocation(), 0,
2731 SourceLocation());
2732 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002733 return false;
2734 }
2735
Richard Smithc115f632011-09-18 11:14:50 +00002736 // Don't build an implicit initializer for union members if none was
2737 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002738 if (Field->getParent()->isUnion() ||
2739 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002740 return false;
2741
Douglas Gregorddb21472011-11-02 23:04:16 +00002742 // Don't initialize incomplete or zero-length arrays.
2743 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2744 return false;
2745
John McCallf1860e52010-05-20 23:23:51 +00002746 // Don't try to build an implicit initializer if there were semantic
2747 // errors in any of the initializers (and therefore we might be
2748 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002749 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002750 return false;
2751
Sean Huntcbb67482011-01-08 20:30:50 +00002752 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002753 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2754 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002755 return true;
John McCallf1860e52010-05-20 23:23:51 +00002756
Francois Pichet00eb3f92010-12-04 09:14:42 +00002757 if (Init)
2758 Info.AllToInit.push_back(Init);
2759
John McCallf1860e52010-05-20 23:23:51 +00002760 return false;
2761}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002762
2763bool
2764Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2765 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002766 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002767 Constructor->setNumCtorInitializers(1);
2768 CXXCtorInitializer **initializer =
2769 new (Context) CXXCtorInitializer*[1];
2770 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2771 Constructor->setCtorInitializers(initializer);
2772
Sean Huntb76af9c2011-05-03 23:05:34 +00002773 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2774 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2775 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2776 }
2777
Sean Huntc1598702011-05-05 00:05:47 +00002778 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002779
Sean Hunt059ce0d2011-05-01 07:04:31 +00002780 return false;
2781}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002782
John McCallb77115d2011-06-17 00:18:42 +00002783bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2784 CXXCtorInitializer **Initializers,
2785 unsigned NumInitializers,
2786 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002787 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002788 // Just store the initializers as written, they will be checked during
2789 // instantiation.
2790 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002791 Constructor->setNumCtorInitializers(NumInitializers);
2792 CXXCtorInitializer **baseOrMemberInitializers =
2793 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002794 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002795 NumInitializers * sizeof(CXXCtorInitializer*));
2796 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002797 }
2798
2799 return false;
2800 }
2801
John McCallf1860e52010-05-20 23:23:51 +00002802 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002803
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002804 // We need to build the initializer AST according to order of construction
2805 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002806 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002807 if (!ClassDecl)
2808 return true;
2809
Eli Friedman80c30da2009-11-09 19:20:36 +00002810 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002812 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002813 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002814
2815 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002816 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002817 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002818 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002819 }
2820
Anders Carlsson711f34a2010-04-21 19:52:01 +00002821 // Keep track of the direct virtual bases.
2822 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2823 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2824 E = ClassDecl->bases_end(); I != E; ++I) {
2825 if (I->isVirtual())
2826 DirectVBases.insert(I);
2827 }
2828
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002829 // Push virtual bases before others.
2830 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2831 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2832
Sean Huntcbb67482011-01-08 20:30:50 +00002833 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002834 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2835 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002836 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002837 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002838 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002839 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002840 VBase, IsInheritedVirtualBase,
2841 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002842 HadError = true;
2843 continue;
2844 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002845
John McCallf1860e52010-05-20 23:23:51 +00002846 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002847 }
2848 }
Mike Stump1eb44332009-09-09 15:08:12 +00002849
John McCallf1860e52010-05-20 23:23:51 +00002850 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002851 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2852 E = ClassDecl->bases_end(); Base != E; ++Base) {
2853 // Virtuals are in the virtual base list and already constructed.
2854 if (Base->isVirtual())
2855 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Sean Huntcbb67482011-01-08 20:30:50 +00002857 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002858 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2859 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002860 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002861 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002862 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002863 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002864 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002865 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002866 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002867 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002868
John McCallf1860e52010-05-20 23:23:51 +00002869 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002870 }
2871 }
Mike Stump1eb44332009-09-09 15:08:12 +00002872
John McCallf1860e52010-05-20 23:23:51 +00002873 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002874 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2875 MemEnd = ClassDecl->decls_end();
2876 Mem != MemEnd; ++Mem) {
2877 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002878 // C++ [class.bit]p2:
2879 // A declaration for a bit-field that omits the identifier declares an
2880 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2881 // initialized.
2882 if (F->isUnnamedBitfield())
2883 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002884
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002885 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002886 // handle anonymous struct/union fields based on their individual
2887 // indirect fields.
2888 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2889 continue;
2890
2891 if (CollectFieldInitializer(*this, Info, F))
2892 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002893 continue;
2894 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002895
2896 // Beyond this point, we only consider default initialization.
2897 if (Info.IIK != IIK_Default)
2898 continue;
2899
2900 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2901 if (F->getType()->isIncompleteArrayType()) {
2902 assert(ClassDecl->hasFlexibleArrayMember() &&
2903 "Incomplete array type is not valid");
2904 continue;
2905 }
2906
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002907 // Initialize each field of an anonymous struct individually.
2908 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2909 HadError = true;
2910
2911 continue;
2912 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002913 }
Mike Stump1eb44332009-09-09 15:08:12 +00002914
John McCallf1860e52010-05-20 23:23:51 +00002915 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002916 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002917 Constructor->setNumCtorInitializers(NumInitializers);
2918 CXXCtorInitializer **baseOrMemberInitializers =
2919 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002920 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002921 NumInitializers * sizeof(CXXCtorInitializer*));
2922 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002923
John McCallef027fe2010-03-16 21:39:52 +00002924 // Constructors implicitly reference the base and member
2925 // destructors.
2926 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2927 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002928 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002929
2930 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002931}
2932
Eli Friedman6347f422009-07-21 19:28:10 +00002933static void *GetKeyForTopLevelField(FieldDecl *Field) {
2934 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002935 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002936 if (RT->getDecl()->isAnonymousStructOrUnion())
2937 return static_cast<void *>(RT->getDecl());
2938 }
2939 return static_cast<void *>(Field);
2940}
2941
Anders Carlssonea356fb2010-04-02 05:42:15 +00002942static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002943 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002944}
2945
Anders Carlssonea356fb2010-04-02 05:42:15 +00002946static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002947 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002948 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002949 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002950
Eli Friedman6347f422009-07-21 19:28:10 +00002951 // For fields injected into the class via declaration of an anonymous union,
2952 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002953 FieldDecl *Field = Member->getAnyMember();
2954
John McCall3c3ccdb2010-04-10 09:28:51 +00002955 // If the field is a member of an anonymous struct or union, our key
2956 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002957 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002958 if (RD->isAnonymousStructOrUnion()) {
2959 while (true) {
2960 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2961 if (Parent->isAnonymousStructOrUnion())
2962 RD = Parent;
2963 else
2964 break;
2965 }
2966
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002967 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002968 }
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002970 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002971}
2972
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002973static void
2974DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002975 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002976 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002977 unsigned NumInits) {
2978 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002979 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002980
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002981 // Don't check initializers order unless the warning is enabled at the
2982 // location of at least one initializer.
2983 bool ShouldCheckOrder = false;
2984 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002985 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002986 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2987 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00002988 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002989 ShouldCheckOrder = true;
2990 break;
2991 }
2992 }
2993 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002994 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002995
John McCalld6ca8da2010-04-10 07:37:23 +00002996 // Build the list of bases and members in the order that they'll
2997 // actually be initialized. The explicit initializers should be in
2998 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002999 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003000
Anders Carlsson071d6102010-04-02 03:38:04 +00003001 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3002
John McCalld6ca8da2010-04-10 07:37:23 +00003003 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003004 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003005 ClassDecl->vbases_begin(),
3006 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003007 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003008
John McCalld6ca8da2010-04-10 07:37:23 +00003009 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003010 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003011 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003012 if (Base->isVirtual())
3013 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003014 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003015 }
Mike Stump1eb44332009-09-09 15:08:12 +00003016
John McCalld6ca8da2010-04-10 07:37:23 +00003017 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003018 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003019 E = ClassDecl->field_end(); Field != E; ++Field) {
3020 if (Field->isUnnamedBitfield())
3021 continue;
3022
John McCalld6ca8da2010-04-10 07:37:23 +00003023 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003024 }
3025
John McCalld6ca8da2010-04-10 07:37:23 +00003026 unsigned NumIdealInits = IdealInitKeys.size();
3027 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003028
Sean Huntcbb67482011-01-08 20:30:50 +00003029 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003030 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003031 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003032 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003033
3034 // Scan forward to try to find this initializer in the idealized
3035 // initializers list.
3036 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3037 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003038 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003039
3040 // If we didn't find this initializer, it must be because we
3041 // scanned past it on a previous iteration. That can only
3042 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003043 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003044 Sema::SemaDiagnosticBuilder D =
3045 SemaRef.Diag(PrevInit->getSourceLocation(),
3046 diag::warn_initializer_out_of_order);
3047
Francois Pichet00eb3f92010-12-04 09:14:42 +00003048 if (PrevInit->isAnyMemberInitializer())
3049 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003050 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003051 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003052
Francois Pichet00eb3f92010-12-04 09:14:42 +00003053 if (Init->isAnyMemberInitializer())
3054 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003055 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003056 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003057
3058 // Move back to the initializer's location in the ideal list.
3059 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3060 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003061 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003062
3063 assert(IdealIndex != NumIdealInits &&
3064 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003065 }
John McCalld6ca8da2010-04-10 07:37:23 +00003066
3067 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003068 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003069}
3070
John McCall3c3ccdb2010-04-10 09:28:51 +00003071namespace {
3072bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003073 CXXCtorInitializer *Init,
3074 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003075 if (!PrevInit) {
3076 PrevInit = Init;
3077 return false;
3078 }
3079
3080 if (FieldDecl *Field = Init->getMember())
3081 S.Diag(Init->getSourceLocation(),
3082 diag::err_multiple_mem_initialization)
3083 << Field->getDeclName()
3084 << Init->getSourceRange();
3085 else {
John McCallf4c73712011-01-19 06:33:43 +00003086 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003087 assert(BaseClass && "neither field nor base");
3088 S.Diag(Init->getSourceLocation(),
3089 diag::err_multiple_base_initialization)
3090 << QualType(BaseClass, 0)
3091 << Init->getSourceRange();
3092 }
3093 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3094 << 0 << PrevInit->getSourceRange();
3095
3096 return true;
3097}
3098
Sean Huntcbb67482011-01-08 20:30:50 +00003099typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003100typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3101
3102bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003103 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003104 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003105 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003106 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003107 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003108
3109 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003110 if (Parent->isUnion()) {
3111 UnionEntry &En = Unions[Parent];
3112 if (En.first && En.first != Child) {
3113 S.Diag(Init->getSourceLocation(),
3114 diag::err_multiple_mem_union_initialization)
3115 << Field->getDeclName()
3116 << Init->getSourceRange();
3117 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3118 << 0 << En.second->getSourceRange();
3119 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003120 }
3121 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003122 En.first = Child;
3123 En.second = Init;
3124 }
David Blaikie6fe29652011-11-17 06:01:57 +00003125 if (!Parent->isAnonymousStructOrUnion())
3126 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003127 }
3128
3129 Child = Parent;
3130 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003131 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003132
3133 return false;
3134}
3135}
3136
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003137/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003138void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003139 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003140 CXXCtorInitializer **meminits,
3141 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003142 bool AnyErrors) {
3143 if (!ConstructorDecl)
3144 return;
3145
3146 AdjustDeclIfTemplate(ConstructorDecl);
3147
3148 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003149 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003150
3151 if (!Constructor) {
3152 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3153 return;
3154 }
3155
Sean Huntcbb67482011-01-08 20:30:50 +00003156 CXXCtorInitializer **MemInits =
3157 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003158
3159 // Mapping for the duplicate initializers check.
3160 // For member initializers, this is keyed with a FieldDecl*.
3161 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003162 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003163
3164 // Mapping for the inconsistent anonymous-union initializers check.
3165 RedundantUnionMap MemberUnions;
3166
Anders Carlssonea356fb2010-04-02 05:42:15 +00003167 bool HadError = false;
3168 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003169 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003170
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003171 // Set the source order index.
3172 Init->setSourceOrder(i);
3173
Francois Pichet00eb3f92010-12-04 09:14:42 +00003174 if (Init->isAnyMemberInitializer()) {
3175 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003176 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3177 CheckRedundantUnionInit(*this, Init, MemberUnions))
3178 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003179 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003180 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3181 if (CheckRedundantInit(*this, Init, Members[Key]))
3182 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003183 } else {
3184 assert(Init->isDelegatingInitializer());
3185 // This must be the only initializer
3186 if (i != 0 || NumMemInits > 1) {
3187 Diag(MemInits[0]->getSourceLocation(),
3188 diag::err_delegating_initializer_alone)
3189 << MemInits[0]->getSourceRange();
3190 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003191 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003192 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003193 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003194 // Return immediately as the initializer is set.
3195 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003196 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003197 }
3198
Anders Carlssonea356fb2010-04-02 05:42:15 +00003199 if (HadError)
3200 return;
3201
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003202 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003203
Sean Huntcbb67482011-01-08 20:30:50 +00003204 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003205}
3206
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003207void
John McCallef027fe2010-03-16 21:39:52 +00003208Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3209 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003210 // Ignore dependent contexts. Also ignore unions, since their members never
3211 // have destructors implicitly called.
3212 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003213 return;
John McCall58e6f342010-03-16 05:22:47 +00003214
3215 // FIXME: all the access-control diagnostics are positioned on the
3216 // field/base declaration. That's probably good; that said, the
3217 // user might reasonably want to know why the destructor is being
3218 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003219
Anders Carlsson9f853df2009-11-17 04:44:12 +00003220 // Non-static data members.
3221 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3222 E = ClassDecl->field_end(); I != E; ++I) {
3223 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003224 if (Field->isInvalidDecl())
3225 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003226
3227 // Don't destroy incomplete or zero-length arrays.
3228 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3229 continue;
3230
Anders Carlsson9f853df2009-11-17 04:44:12 +00003231 QualType FieldType = Context.getBaseElementType(Field->getType());
3232
3233 const RecordType* RT = FieldType->getAs<RecordType>();
3234 if (!RT)
3235 continue;
3236
3237 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003238 if (FieldClassDecl->isInvalidDecl())
3239 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003240 if (FieldClassDecl->hasTrivialDestructor())
3241 continue;
3242
Douglas Gregordb89f282010-07-01 22:47:18 +00003243 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003244 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003245 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003246 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003247 << Field->getDeclName()
3248 << FieldType);
3249
John McCallef027fe2010-03-16 21:39:52 +00003250 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003251 }
3252
John McCall58e6f342010-03-16 05:22:47 +00003253 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3254
Anders Carlsson9f853df2009-11-17 04:44:12 +00003255 // Bases.
3256 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3257 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003258 // Bases are always records in a well-formed non-dependent class.
3259 const RecordType *RT = Base->getType()->getAs<RecordType>();
3260
3261 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003262 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003263 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003264
John McCall58e6f342010-03-16 05:22:47 +00003265 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003266 // If our base class is invalid, we probably can't get its dtor anyway.
3267 if (BaseClassDecl->isInvalidDecl())
3268 continue;
3269 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003270 if (BaseClassDecl->hasTrivialDestructor())
3271 continue;
John McCall58e6f342010-03-16 05:22:47 +00003272
Douglas Gregordb89f282010-07-01 22:47:18 +00003273 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003274 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003275
3276 // FIXME: caret should be on the start of the class name
3277 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003278 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003279 << Base->getType()
3280 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003281
John McCallef027fe2010-03-16 21:39:52 +00003282 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003283 }
3284
3285 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003286 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3287 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003288
3289 // Bases are always records in a well-formed non-dependent class.
3290 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3291
3292 // Ignore direct virtual bases.
3293 if (DirectVirtualBases.count(RT))
3294 continue;
3295
John McCall58e6f342010-03-16 05:22:47 +00003296 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003297 // If our base class is invalid, we probably can't get its dtor anyway.
3298 if (BaseClassDecl->isInvalidDecl())
3299 continue;
3300 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003301 if (BaseClassDecl->hasTrivialDestructor())
3302 continue;
John McCall58e6f342010-03-16 05:22:47 +00003303
Douglas Gregordb89f282010-07-01 22:47:18 +00003304 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003305 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003306 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003307 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003308 << VBase->getType());
3309
John McCallef027fe2010-03-16 21:39:52 +00003310 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003311 }
3312}
3313
John McCalld226f652010-08-21 09:40:31 +00003314void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003315 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003316 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003317
Mike Stump1eb44332009-09-09 15:08:12 +00003318 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003319 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003320 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003321}
3322
Mike Stump1eb44332009-09-09 15:08:12 +00003323bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003324 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003325 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003326 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003327 else
John McCall94c3b562010-08-18 09:41:07 +00003328 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003329}
3330
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003331bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003332 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003333 if (!getLangOptions().CPlusPlus)
3334 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Anders Carlsson11f21a02009-03-23 19:10:31 +00003336 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003337 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Ted Kremenek6217b802009-07-29 21:53:49 +00003339 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003340 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003341 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003342 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003343
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003344 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003345 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003346 }
Mike Stump1eb44332009-09-09 15:08:12 +00003347
Ted Kremenek6217b802009-07-29 21:53:49 +00003348 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003349 if (!RT)
3350 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003351
John McCall86ff3082010-02-04 22:26:26 +00003352 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003353
John McCall94c3b562010-08-18 09:41:07 +00003354 // We can't answer whether something is abstract until it has a
3355 // definition. If it's currently being defined, we'll walk back
3356 // over all the declarations when we have a full definition.
3357 const CXXRecordDecl *Def = RD->getDefinition();
3358 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003359 return false;
3360
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003361 if (!RD->isAbstract())
3362 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003363
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003364 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003365 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003366
John McCall94c3b562010-08-18 09:41:07 +00003367 return true;
3368}
3369
3370void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3371 // Check if we've already emitted the list of pure virtual functions
3372 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003373 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003374 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003376 CXXFinalOverriderMap FinalOverriders;
3377 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003378
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003379 // Keep a set of seen pure methods so we won't diagnose the same method
3380 // more than once.
3381 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3382
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003383 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3384 MEnd = FinalOverriders.end();
3385 M != MEnd;
3386 ++M) {
3387 for (OverridingMethods::iterator SO = M->second.begin(),
3388 SOEnd = M->second.end();
3389 SO != SOEnd; ++SO) {
3390 // C++ [class.abstract]p4:
3391 // A class is abstract if it contains or inherits at least one
3392 // pure virtual function for which the final overrider is pure
3393 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003394
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003395 //
3396 if (SO->second.size() != 1)
3397 continue;
3398
3399 if (!SO->second.front().Method->isPure())
3400 continue;
3401
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003402 if (!SeenPureMethods.insert(SO->second.front().Method))
3403 continue;
3404
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003405 Diag(SO->second.front().Method->getLocation(),
3406 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003407 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003408 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003409 }
3410
3411 if (!PureVirtualClassDiagSet)
3412 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3413 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003414}
3415
Anders Carlsson8211eff2009-03-24 01:19:16 +00003416namespace {
John McCall94c3b562010-08-18 09:41:07 +00003417struct AbstractUsageInfo {
3418 Sema &S;
3419 CXXRecordDecl *Record;
3420 CanQualType AbstractType;
3421 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003422
John McCall94c3b562010-08-18 09:41:07 +00003423 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3424 : S(S), Record(Record),
3425 AbstractType(S.Context.getCanonicalType(
3426 S.Context.getTypeDeclType(Record))),
3427 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003428
John McCall94c3b562010-08-18 09:41:07 +00003429 void DiagnoseAbstractType() {
3430 if (Invalid) return;
3431 S.DiagnoseAbstractType(Record);
3432 Invalid = true;
3433 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003434
John McCall94c3b562010-08-18 09:41:07 +00003435 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3436};
3437
3438struct CheckAbstractUsage {
3439 AbstractUsageInfo &Info;
3440 const NamedDecl *Ctx;
3441
3442 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3443 : Info(Info), Ctx(Ctx) {}
3444
3445 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3446 switch (TL.getTypeLocClass()) {
3447#define ABSTRACT_TYPELOC(CLASS, PARENT)
3448#define TYPELOC(CLASS, PARENT) \
3449 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3450#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003451 }
John McCall94c3b562010-08-18 09:41:07 +00003452 }
Mike Stump1eb44332009-09-09 15:08:12 +00003453
John McCall94c3b562010-08-18 09:41:07 +00003454 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3455 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3456 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003457 if (!TL.getArg(I))
3458 continue;
3459
John McCall94c3b562010-08-18 09:41:07 +00003460 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3461 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003462 }
John McCall94c3b562010-08-18 09:41:07 +00003463 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003464
John McCall94c3b562010-08-18 09:41:07 +00003465 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3466 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3467 }
Mike Stump1eb44332009-09-09 15:08:12 +00003468
John McCall94c3b562010-08-18 09:41:07 +00003469 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3470 // Visit the type parameters from a permissive context.
3471 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3472 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3473 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3474 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3475 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3476 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003477 }
John McCall94c3b562010-08-18 09:41:07 +00003478 }
Mike Stump1eb44332009-09-09 15:08:12 +00003479
John McCall94c3b562010-08-18 09:41:07 +00003480 // Visit pointee types from a permissive context.
3481#define CheckPolymorphic(Type) \
3482 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3483 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3484 }
3485 CheckPolymorphic(PointerTypeLoc)
3486 CheckPolymorphic(ReferenceTypeLoc)
3487 CheckPolymorphic(MemberPointerTypeLoc)
3488 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003489 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003490
John McCall94c3b562010-08-18 09:41:07 +00003491 /// Handle all the types we haven't given a more specific
3492 /// implementation for above.
3493 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3494 // Every other kind of type that we haven't called out already
3495 // that has an inner type is either (1) sugar or (2) contains that
3496 // inner type in some way as a subobject.
3497 if (TypeLoc Next = TL.getNextTypeLoc())
3498 return Visit(Next, Sel);
3499
3500 // If there's no inner type and we're in a permissive context,
3501 // don't diagnose.
3502 if (Sel == Sema::AbstractNone) return;
3503
3504 // Check whether the type matches the abstract type.
3505 QualType T = TL.getType();
3506 if (T->isArrayType()) {
3507 Sel = Sema::AbstractArrayType;
3508 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003509 }
John McCall94c3b562010-08-18 09:41:07 +00003510 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3511 if (CT != Info.AbstractType) return;
3512
3513 // It matched; do some magic.
3514 if (Sel == Sema::AbstractArrayType) {
3515 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3516 << T << TL.getSourceRange();
3517 } else {
3518 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3519 << Sel << T << TL.getSourceRange();
3520 }
3521 Info.DiagnoseAbstractType();
3522 }
3523};
3524
3525void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3526 Sema::AbstractDiagSelID Sel) {
3527 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3528}
3529
3530}
3531
3532/// Check for invalid uses of an abstract type in a method declaration.
3533static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3534 CXXMethodDecl *MD) {
3535 // No need to do the check on definitions, which require that
3536 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003537 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003538 return;
3539
3540 // For safety's sake, just ignore it if we don't have type source
3541 // information. This should never happen for non-implicit methods,
3542 // but...
3543 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3544 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3545}
3546
3547/// Check for invalid uses of an abstract type within a class definition.
3548static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3549 CXXRecordDecl *RD) {
3550 for (CXXRecordDecl::decl_iterator
3551 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3552 Decl *D = *I;
3553 if (D->isImplicit()) continue;
3554
3555 // Methods and method templates.
3556 if (isa<CXXMethodDecl>(D)) {
3557 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3558 } else if (isa<FunctionTemplateDecl>(D)) {
3559 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3560 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3561
3562 // Fields and static variables.
3563 } else if (isa<FieldDecl>(D)) {
3564 FieldDecl *FD = cast<FieldDecl>(D);
3565 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3566 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3567 } else if (isa<VarDecl>(D)) {
3568 VarDecl *VD = cast<VarDecl>(D);
3569 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3570 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3571
3572 // Nested classes and class templates.
3573 } else if (isa<CXXRecordDecl>(D)) {
3574 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3575 } else if (isa<ClassTemplateDecl>(D)) {
3576 CheckAbstractClassUsage(Info,
3577 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3578 }
3579 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003580}
3581
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003582/// \brief Perform semantic checks on a class definition that has been
3583/// completing, introducing implicitly-declared members, checking for
3584/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003585void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003586 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003587 return;
3588
John McCall94c3b562010-08-18 09:41:07 +00003589 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3590 AbstractUsageInfo Info(*this, Record);
3591 CheckAbstractClassUsage(Info, Record);
3592 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003593
3594 // If this is not an aggregate type and has no user-declared constructor,
3595 // complain about any non-static data members of reference or const scalar
3596 // type, since they will never get initializers.
3597 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3598 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3599 bool Complained = false;
3600 for (RecordDecl::field_iterator F = Record->field_begin(),
3601 FEnd = Record->field_end();
3602 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003603 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003604 continue;
3605
Douglas Gregor325e5932010-04-15 00:00:53 +00003606 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003607 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003608 if (!Complained) {
3609 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3610 << Record->getTagKind() << Record;
3611 Complained = true;
3612 }
3613
3614 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3615 << F->getType()->isReferenceType()
3616 << F->getDeclName();
3617 }
3618 }
3619 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003620
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003621 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003622 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003623
3624 if (Record->getIdentifier()) {
3625 // C++ [class.mem]p13:
3626 // If T is the name of a class, then each of the following shall have a
3627 // name different from T:
3628 // - every member of every anonymous union that is a member of class T.
3629 //
3630 // C++ [class.mem]p14:
3631 // In addition, if class T has a user-declared constructor (12.1), every
3632 // non-static data member of class T shall have a name different from T.
3633 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003634 R.first != R.second; ++R.first) {
3635 NamedDecl *D = *R.first;
3636 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3637 isa<IndirectFieldDecl>(D)) {
3638 Diag(D->getLocation(), diag::err_member_name_of_class)
3639 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003640 break;
3641 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003642 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003643 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003644
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003645 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003646 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003647 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003648 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003649 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3650 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3651 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003652
3653 // See if a method overloads virtual methods in a base
3654 /// class without overriding any.
3655 if (!Record->isDependentType()) {
3656 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3657 MEnd = Record->method_end();
3658 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003659 if (!(*M)->isStatic())
3660 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003661 }
3662 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003663
Richard Smith9f569cc2011-10-01 02:31:28 +00003664 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3665 // function that is not a constructor declares that member function to be
3666 // const. [...] The class of which that function is a member shall be
3667 // a literal type.
3668 //
3669 // It's fine to diagnose constructors here too: such constructors cannot
3670 // produce a constant expression, so are ill-formed (no diagnostic required).
3671 //
3672 // If the class has virtual bases, any constexpr members will already have
3673 // been diagnosed by the checks performed on the member declaration, so
3674 // suppress this (less useful) diagnostic.
3675 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3676 !Record->isLiteral() && !Record->getNumVBases()) {
3677 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3678 MEnd = Record->method_end();
3679 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003680 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003681 switch (Record->getTemplateSpecializationKind()) {
3682 case TSK_ImplicitInstantiation:
3683 case TSK_ExplicitInstantiationDeclaration:
3684 case TSK_ExplicitInstantiationDefinition:
3685 // If a template instantiates to a non-literal type, but its members
3686 // instantiate to constexpr functions, the template is technically
3687 // ill-formed, but we allow it for sanity. Such members are treated as
3688 // non-constexpr.
3689 (*M)->setConstexpr(false);
3690 continue;
3691
3692 case TSK_Undeclared:
3693 case TSK_ExplicitSpecialization:
3694 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3695 PDiag(diag::err_constexpr_method_non_literal));
3696 break;
3697 }
3698
3699 // Only produce one error per class.
3700 break;
3701 }
3702 }
3703 }
3704
Sebastian Redlf677ea32011-02-05 19:23:19 +00003705 // Declare inherited constructors. We do this eagerly here because:
3706 // - The standard requires an eager diagnostic for conflicting inherited
3707 // constructors from different classes.
3708 // - The lazy declaration of the other implicit constructors is so as to not
3709 // waste space and performance on classes that are not meant to be
3710 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3711 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003712 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003713
Sean Hunteb88ae52011-05-23 21:07:59 +00003714 if (!Record->isDependentType())
3715 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003716}
3717
3718void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003719 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3720 ME = Record->method_end();
3721 MI != ME; ++MI) {
3722 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3723 switch (getSpecialMember(*MI)) {
3724 case CXXDefaultConstructor:
3725 CheckExplicitlyDefaultedDefaultConstructor(
3726 cast<CXXConstructorDecl>(*MI));
3727 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003728
Sean Huntcb45a0f2011-05-12 22:46:25 +00003729 case CXXDestructor:
3730 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3731 break;
3732
3733 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003734 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3735 break;
3736
Sean Huntcb45a0f2011-05-12 22:46:25 +00003737 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003738 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003739 break;
3740
Sean Hunt82713172011-05-25 23:16:36 +00003741 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003742 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003743 break;
3744
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003745 case CXXMoveAssignment:
3746 CheckExplicitlyDefaultedMoveAssignment(*MI);
3747 break;
3748
3749 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003750 llvm_unreachable("non-special member explicitly defaulted!");
3751 }
Sean Hunt001cad92011-05-10 00:49:42 +00003752 }
3753 }
3754
Sean Hunt001cad92011-05-10 00:49:42 +00003755}
3756
3757void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3758 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3759
3760 // Whether this was the first-declared instance of the constructor.
3761 // This affects whether we implicitly add an exception spec (and, eventually,
3762 // constexpr). It is also ill-formed to explicitly default a constructor such
3763 // that it would be deleted. (C++0x [decl.fct.def.default])
3764 bool First = CD == CD->getCanonicalDecl();
3765
Sean Hunt49634cf2011-05-13 06:10:58 +00003766 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003767 if (CD->getNumParams() != 0) {
3768 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3769 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003770 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003771 }
3772
3773 ImplicitExceptionSpecification Spec
3774 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3775 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003776 if (EPI.ExceptionSpecType == EST_Delayed) {
3777 // Exception specification depends on some deferred part of the class. We'll
3778 // try again when the class's definition has been fully processed.
3779 return;
3780 }
Sean Hunt001cad92011-05-10 00:49:42 +00003781 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3782 *ExceptionType = Context.getFunctionType(
3783 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3784
Richard Smith61802452011-12-22 02:22:31 +00003785 // C++11 [dcl.fct.def.default]p2:
3786 // An explicitly-defaulted function may be declared constexpr only if it
3787 // would have been implicitly declared as constexpr,
3788 if (CD->isConstexpr()) {
3789 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3790 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3791 << CXXDefaultConstructor;
3792 HadError = true;
3793 }
3794 }
3795 // and may have an explicit exception-specification only if it is compatible
3796 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003797 if (CtorType->hasExceptionSpec()) {
3798 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003799 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003800 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003801 PDiag(),
3802 ExceptionType, SourceLocation(),
3803 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003804 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003805 }
Richard Smith61802452011-12-22 02:22:31 +00003806 }
3807
3808 // If a function is explicitly defaulted on its first declaration,
3809 if (First) {
3810 // -- it is implicitly considered to be constexpr if the implicit
3811 // definition would be,
3812 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3813
3814 // -- it is implicitly considered to have the same
3815 // exception-specification as if it had been implicitly declared
3816 //
3817 // FIXME: a compatible, but different, explicit exception specification
3818 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003819 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003820 }
Sean Huntca46d132011-05-12 03:51:48 +00003821
Sean Hunt49634cf2011-05-13 06:10:58 +00003822 if (HadError) {
3823 CD->setInvalidDecl();
3824 return;
3825 }
3826
Sean Hunte16da072011-10-10 06:18:57 +00003827 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003828 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003829 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003830 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003831 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003832 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003833 CD->setInvalidDecl();
3834 }
3835 }
3836}
3837
3838void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3839 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3840
3841 // Whether this was the first-declared instance of the constructor.
3842 bool First = CD == CD->getCanonicalDecl();
3843
3844 bool HadError = false;
3845 if (CD->getNumParams() != 1) {
3846 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3847 << CD->getSourceRange();
3848 HadError = true;
3849 }
3850
3851 ImplicitExceptionSpecification Spec(Context);
3852 bool Const;
3853 llvm::tie(Spec, Const) =
3854 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3855
3856 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3857 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3858 *ExceptionType = Context.getFunctionType(
3859 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3860
3861 // Check for parameter type matching.
3862 // This is a copy ctor so we know it's a cv-qualified reference to T.
3863 QualType ArgType = CtorType->getArgType(0);
3864 if (ArgType->getPointeeType().isVolatileQualified()) {
3865 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3866 HadError = true;
3867 }
3868 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3869 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3870 HadError = true;
3871 }
3872
Richard Smith61802452011-12-22 02:22:31 +00003873 // C++11 [dcl.fct.def.default]p2:
3874 // An explicitly-defaulted function may be declared constexpr only if it
3875 // would have been implicitly declared as constexpr,
3876 if (CD->isConstexpr()) {
3877 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3878 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3879 << CXXCopyConstructor;
3880 HadError = true;
3881 }
3882 }
3883 // and may have an explicit exception-specification only if it is compatible
3884 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003885 if (CtorType->hasExceptionSpec()) {
3886 if (CheckEquivalentExceptionSpec(
3887 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003888 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003889 PDiag(),
3890 ExceptionType, SourceLocation(),
3891 CtorType, CD->getLocation())) {
3892 HadError = true;
3893 }
Richard Smith61802452011-12-22 02:22:31 +00003894 }
3895
3896 // If a function is explicitly defaulted on its first declaration,
3897 if (First) {
3898 // -- it is implicitly considered to be constexpr if the implicit
3899 // definition would be,
3900 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3901
3902 // -- it is implicitly considered to have the same
3903 // exception-specification as if it had been implicitly declared, and
3904 //
3905 // FIXME: a compatible, but different, explicit exception specification
3906 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003907 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003908
3909 // -- [...] it shall have the same parameter type as if it had been
3910 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003911 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3912 }
3913
3914 if (HadError) {
3915 CD->setInvalidDecl();
3916 return;
3917 }
3918
Sean Huntc32d6842011-10-11 04:55:36 +00003919 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003920 if (First) {
3921 CD->setDeletedAsWritten();
3922 } else {
3923 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003924 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003925 CD->setInvalidDecl();
3926 }
Sean Huntca46d132011-05-12 03:51:48 +00003927 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003928}
Sean Hunt001cad92011-05-10 00:49:42 +00003929
Sean Hunt2b188082011-05-14 05:23:28 +00003930void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3931 assert(MD->isExplicitlyDefaulted());
3932
3933 // Whether this was the first-declared instance of the operator
3934 bool First = MD == MD->getCanonicalDecl();
3935
3936 bool HadError = false;
3937 if (MD->getNumParams() != 1) {
3938 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3939 << MD->getSourceRange();
3940 HadError = true;
3941 }
3942
3943 QualType ReturnType =
3944 MD->getType()->getAs<FunctionType>()->getResultType();
3945 if (!ReturnType->isLValueReferenceType() ||
3946 !Context.hasSameType(
3947 Context.getCanonicalType(ReturnType->getPointeeType()),
3948 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3949 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3950 HadError = true;
3951 }
3952
3953 ImplicitExceptionSpecification Spec(Context);
3954 bool Const;
3955 llvm::tie(Spec, Const) =
3956 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3957
3958 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3959 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3960 *ExceptionType = Context.getFunctionType(
3961 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3962
Sean Hunt2b188082011-05-14 05:23:28 +00003963 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003964 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003965 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003966 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003967 } else {
3968 if (ArgType->getPointeeType().isVolatileQualified()) {
3969 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3970 HadError = true;
3971 }
3972 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3973 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3974 HadError = true;
3975 }
Sean Hunt2b188082011-05-14 05:23:28 +00003976 }
Sean Huntbe631222011-05-17 20:44:43 +00003977
Sean Hunt2b188082011-05-14 05:23:28 +00003978 if (OperType->getTypeQuals()) {
3979 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3980 HadError = true;
3981 }
3982
3983 if (OperType->hasExceptionSpec()) {
3984 if (CheckEquivalentExceptionSpec(
3985 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003986 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003987 PDiag(),
3988 ExceptionType, SourceLocation(),
3989 OperType, MD->getLocation())) {
3990 HadError = true;
3991 }
Richard Smith61802452011-12-22 02:22:31 +00003992 }
3993 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00003994 // We set the declaration to have the computed exception spec here.
3995 // We duplicate the one parameter type.
3996 EPI.RefQualifier = OperType->getRefQualifier();
3997 EPI.ExtInfo = OperType->getExtInfo();
3998 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3999 }
4000
4001 if (HadError) {
4002 MD->setInvalidDecl();
4003 return;
4004 }
4005
4006 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4007 if (First) {
4008 MD->setDeletedAsWritten();
4009 } else {
4010 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004011 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004012 MD->setInvalidDecl();
4013 }
4014 }
4015}
4016
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004017void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4018 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4019
4020 // Whether this was the first-declared instance of the constructor.
4021 bool First = CD == CD->getCanonicalDecl();
4022
4023 bool HadError = false;
4024 if (CD->getNumParams() != 1) {
4025 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4026 << CD->getSourceRange();
4027 HadError = true;
4028 }
4029
4030 ImplicitExceptionSpecification Spec(
4031 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4032
4033 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4034 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4035 *ExceptionType = Context.getFunctionType(
4036 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4037
4038 // Check for parameter type matching.
4039 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4040 QualType ArgType = CtorType->getArgType(0);
4041 if (ArgType->getPointeeType().isVolatileQualified()) {
4042 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4043 HadError = true;
4044 }
4045 if (ArgType->getPointeeType().isConstQualified()) {
4046 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4047 HadError = true;
4048 }
4049
Richard Smith61802452011-12-22 02:22:31 +00004050 // C++11 [dcl.fct.def.default]p2:
4051 // An explicitly-defaulted function may be declared constexpr only if it
4052 // would have been implicitly declared as constexpr,
4053 if (CD->isConstexpr()) {
4054 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4055 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4056 << CXXMoveConstructor;
4057 HadError = true;
4058 }
4059 }
4060 // and may have an explicit exception-specification only if it is compatible
4061 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004062 if (CtorType->hasExceptionSpec()) {
4063 if (CheckEquivalentExceptionSpec(
4064 PDiag(diag::err_incorrect_defaulted_exception_spec)
4065 << CXXMoveConstructor,
4066 PDiag(),
4067 ExceptionType, SourceLocation(),
4068 CtorType, CD->getLocation())) {
4069 HadError = true;
4070 }
Richard Smith61802452011-12-22 02:22:31 +00004071 }
4072
4073 // If a function is explicitly defaulted on its first declaration,
4074 if (First) {
4075 // -- it is implicitly considered to be constexpr if the implicit
4076 // definition would be,
4077 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4078
4079 // -- it is implicitly considered to have the same
4080 // exception-specification as if it had been implicitly declared, and
4081 //
4082 // FIXME: a compatible, but different, explicit exception specification
4083 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004084 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004085
4086 // -- [...] it shall have the same parameter type as if it had been
4087 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004088 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4089 }
4090
4091 if (HadError) {
4092 CD->setInvalidDecl();
4093 return;
4094 }
4095
Sean Hunt769bb2d2011-10-11 06:43:29 +00004096 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004097 if (First) {
4098 CD->setDeletedAsWritten();
4099 } else {
4100 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4101 << CXXMoveConstructor;
4102 CD->setInvalidDecl();
4103 }
4104 }
4105}
4106
4107void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4108 assert(MD->isExplicitlyDefaulted());
4109
4110 // Whether this was the first-declared instance of the operator
4111 bool First = MD == MD->getCanonicalDecl();
4112
4113 bool HadError = false;
4114 if (MD->getNumParams() != 1) {
4115 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4116 << MD->getSourceRange();
4117 HadError = true;
4118 }
4119
4120 QualType ReturnType =
4121 MD->getType()->getAs<FunctionType>()->getResultType();
4122 if (!ReturnType->isLValueReferenceType() ||
4123 !Context.hasSameType(
4124 Context.getCanonicalType(ReturnType->getPointeeType()),
4125 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4126 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4127 HadError = true;
4128 }
4129
4130 ImplicitExceptionSpecification Spec(
4131 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4132
4133 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4134 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4135 *ExceptionType = Context.getFunctionType(
4136 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4137
4138 QualType ArgType = OperType->getArgType(0);
4139 if (!ArgType->isRValueReferenceType()) {
4140 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4141 HadError = true;
4142 } else {
4143 if (ArgType->getPointeeType().isVolatileQualified()) {
4144 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4145 HadError = true;
4146 }
4147 if (ArgType->getPointeeType().isConstQualified()) {
4148 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4149 HadError = true;
4150 }
4151 }
4152
4153 if (OperType->getTypeQuals()) {
4154 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4155 HadError = true;
4156 }
4157
4158 if (OperType->hasExceptionSpec()) {
4159 if (CheckEquivalentExceptionSpec(
4160 PDiag(diag::err_incorrect_defaulted_exception_spec)
4161 << CXXMoveAssignment,
4162 PDiag(),
4163 ExceptionType, SourceLocation(),
4164 OperType, MD->getLocation())) {
4165 HadError = true;
4166 }
Richard Smith61802452011-12-22 02:22:31 +00004167 }
4168 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004169 // We set the declaration to have the computed exception spec here.
4170 // We duplicate the one parameter type.
4171 EPI.RefQualifier = OperType->getRefQualifier();
4172 EPI.ExtInfo = OperType->getExtInfo();
4173 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4174 }
4175
4176 if (HadError) {
4177 MD->setInvalidDecl();
4178 return;
4179 }
4180
4181 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4182 if (First) {
4183 MD->setDeletedAsWritten();
4184 } else {
4185 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4186 << CXXMoveAssignment;
4187 MD->setInvalidDecl();
4188 }
4189 }
4190}
4191
Sean Huntcb45a0f2011-05-12 22:46:25 +00004192void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4193 assert(DD->isExplicitlyDefaulted());
4194
4195 // Whether this was the first-declared instance of the destructor.
4196 bool First = DD == DD->getCanonicalDecl();
4197
4198 ImplicitExceptionSpecification Spec
4199 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4200 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4201 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4202 *ExceptionType = Context.getFunctionType(
4203 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4204
4205 if (DtorType->hasExceptionSpec()) {
4206 if (CheckEquivalentExceptionSpec(
4207 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004208 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004209 PDiag(),
4210 ExceptionType, SourceLocation(),
4211 DtorType, DD->getLocation())) {
4212 DD->setInvalidDecl();
4213 return;
4214 }
Richard Smith61802452011-12-22 02:22:31 +00004215 }
4216 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004217 // We set the declaration to have the computed exception spec here.
4218 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004219 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004220 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4221 }
4222
4223 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004224 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004225 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004226 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004227 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004228 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004229 DD->setInvalidDecl();
4230 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004231 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004232}
4233
Sean Hunte16da072011-10-10 06:18:57 +00004234/// This function implements the following C++0x paragraphs:
4235/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004236/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004237bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4238 assert(!MD->isInvalidDecl());
4239 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004240 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004241 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004242 return false;
4243
Sean Hunte16da072011-10-10 06:18:57 +00004244 bool IsUnion = RD->isUnion();
4245 bool IsConstructor = false;
4246 bool IsAssignment = false;
4247 bool IsMove = false;
4248
4249 bool ConstArg = false;
4250
4251 switch (CSM) {
4252 case CXXDefaultConstructor:
4253 IsConstructor = true;
4254 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004255 case CXXCopyConstructor:
4256 IsConstructor = true;
4257 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4258 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004259 case CXXMoveConstructor:
4260 IsConstructor = true;
4261 IsMove = true;
4262 break;
Sean Hunte16da072011-10-10 06:18:57 +00004263 default:
4264 llvm_unreachable("function only currently implemented for default ctors");
4265 }
4266
4267 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004268
Sean Huntc32d6842011-10-11 04:55:36 +00004269 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004270 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004271
Sean Huntcdee3fe2011-05-11 22:34:38 +00004272 bool AllConst = true;
4273
Sean Huntcdee3fe2011-05-11 22:34:38 +00004274 // We do this because we should never actually use an anonymous
4275 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004276 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004277 return false;
4278
4279 // FIXME: We should put some diagnostic logic right into this function.
4280
Sean Huntcdee3fe2011-05-11 22:34:38 +00004281 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4282 BE = RD->bases_end();
4283 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004284 // We'll handle this one later
4285 if (BI->isVirtual())
4286 continue;
4287
Sean Huntcdee3fe2011-05-11 22:34:38 +00004288 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4289 assert(BaseDecl && "base isn't a CXXRecordDecl");
4290
Sean Hunte16da072011-10-10 06:18:57 +00004291 // Unless we have an assignment operator, the base's destructor must
4292 // be accessible and not deleted.
4293 if (!IsAssignment) {
4294 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4295 if (BaseDtor->isDeleted())
4296 return true;
4297 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4298 AR_accessible)
4299 return true;
4300 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004301
Sean Hunte16da072011-10-10 06:18:57 +00004302 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004303 // unique, accessible, non-deleted function. If we are doing
4304 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004305 if (CSM != CXXDestructor) {
4306 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004307 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004308 false);
4309 if (!SMOR->hasSuccess())
4310 return true;
4311 CXXMethodDecl *BaseMember = SMOR->getMethod();
4312 if (IsConstructor) {
4313 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4314 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4315 PDiag()) != AR_accessible)
4316 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004317
4318 // For a move operation, the corresponding operation must actually
4319 // be a move operation (and not a copy selected by overload
4320 // resolution) unless we are working on a trivially copyable class.
4321 if (IsMove && !BaseCtor->isMoveConstructor() &&
4322 !BaseDecl->isTriviallyCopyable())
4323 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004324 }
4325 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004326 }
4327
4328 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4329 BE = RD->vbases_end();
4330 BI != BE; ++BI) {
4331 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4332 assert(BaseDecl && "base isn't a CXXRecordDecl");
4333
Sean Hunte16da072011-10-10 06:18:57 +00004334 // Unless we have an assignment operator, the base's destructor must
4335 // be accessible and not deleted.
4336 if (!IsAssignment) {
4337 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4338 if (BaseDtor->isDeleted())
4339 return true;
4340 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4341 AR_accessible)
4342 return true;
4343 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004344
Sean Hunte16da072011-10-10 06:18:57 +00004345 // Finding the corresponding member in the base should lead to a
4346 // unique, accessible, non-deleted function.
4347 if (CSM != CXXDestructor) {
4348 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004349 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004350 false);
4351 if (!SMOR->hasSuccess())
4352 return true;
4353 CXXMethodDecl *BaseMember = SMOR->getMethod();
4354 if (IsConstructor) {
4355 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4356 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4357 PDiag()) != AR_accessible)
4358 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004359
4360 // For a move operation, the corresponding operation must actually
4361 // be a move operation (and not a copy selected by overload
4362 // resolution) unless we are working on a trivially copyable class.
4363 if (IsMove && !BaseCtor->isMoveConstructor() &&
4364 !BaseDecl->isTriviallyCopyable())
4365 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004366 }
4367 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004368 }
4369
4370 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4371 FE = RD->field_end();
4372 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004373 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004374 continue;
4375
Sean Huntcdee3fe2011-05-11 22:34:38 +00004376 QualType FieldType = Context.getBaseElementType(FI->getType());
4377 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004378
Sean Hunte16da072011-10-10 06:18:57 +00004379 // For a default constructor, all references must be initialized in-class
4380 // and, if a union, it must have a non-const member.
4381 if (CSM == CXXDefaultConstructor) {
4382 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4383 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004384
Sean Hunte16da072011-10-10 06:18:57 +00004385 if (IsUnion && !FieldType.isConstQualified())
4386 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004387 // For a copy constructor, data members must not be of rvalue reference
4388 // type.
4389 } else if (CSM == CXXCopyConstructor) {
4390 if (FieldType->isRValueReferenceType())
4391 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004392 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004393
4394 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004395 // For a default constructor, a const member must have a user-provided
4396 // default constructor or else be explicitly initialized.
4397 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004398 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004399 !FieldRecord->hasUserProvidedDefaultConstructor())
4400 return true;
4401
Sean Huntc32d6842011-10-11 04:55:36 +00004402 // Some additional restrictions exist on the variant members.
4403 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004404 FieldRecord->isAnonymousStructOrUnion()) {
4405 // We're okay to reuse AllConst here since we only care about the
4406 // value otherwise if we're in a union.
4407 AllConst = true;
4408
4409 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4410 UE = FieldRecord->field_end();
4411 UI != UE; ++UI) {
4412 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4413 CXXRecordDecl *UnionFieldRecord =
4414 UnionFieldType->getAsCXXRecordDecl();
4415
4416 if (!UnionFieldType.isConstQualified())
4417 AllConst = false;
4418
Sean Huntc32d6842011-10-11 04:55:36 +00004419 if (UnionFieldRecord) {
4420 // FIXME: Checking for accessibility and validity of this
4421 // destructor is technically going beyond the
4422 // standard, but this is believed to be a defect.
4423 if (!IsAssignment) {
4424 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4425 if (FieldDtor->isDeleted())
4426 return true;
4427 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4428 AR_accessible)
4429 return true;
4430 if (!FieldDtor->isTrivial())
4431 return true;
4432 }
4433
4434 if (CSM != CXXDestructor) {
4435 SpecialMemberOverloadResult *SMOR =
4436 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004437 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004438 // FIXME: Checking for accessibility and validity of this
4439 // corresponding member is technically going beyond the
4440 // standard, but this is believed to be a defect.
4441 if (!SMOR->hasSuccess())
4442 return true;
4443
4444 CXXMethodDecl *FieldMember = SMOR->getMethod();
4445 // A member of a union must have a trivial corresponding
4446 // constructor.
4447 if (!FieldMember->isTrivial())
4448 return true;
4449
4450 if (IsConstructor) {
4451 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4452 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4453 PDiag()) != AR_accessible)
4454 return true;
4455 }
4456 }
4457 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004458 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004459
Sean Huntc32d6842011-10-11 04:55:36 +00004460 // At least one member in each anonymous union must be non-const
4461 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004462 return true;
4463
4464 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004465 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004466 continue;
4467 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004468
Sean Huntc32d6842011-10-11 04:55:36 +00004469 // Unless we're doing assignment, the field's destructor must be
4470 // accessible and not deleted.
4471 if (!IsAssignment) {
4472 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4473 if (FieldDtor->isDeleted())
4474 return true;
4475 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4476 AR_accessible)
4477 return true;
4478 }
4479
Sean Hunte16da072011-10-10 06:18:57 +00004480 // Check that the corresponding member of the field is accessible,
4481 // unique, and non-deleted. We don't do this if it has an explicit
4482 // initialization when default-constructing.
4483 if (CSM != CXXDestructor &&
4484 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4485 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004486 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004487 false);
4488 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004489 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004490
4491 CXXMethodDecl *FieldMember = SMOR->getMethod();
4492 if (IsConstructor) {
4493 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4494 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4495 PDiag()) != AR_accessible)
4496 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004497
4498 // For a move operation, the corresponding operation must actually
4499 // be a move operation (and not a copy selected by overload
4500 // resolution) unless we are working on a trivially copyable class.
4501 if (IsMove && !FieldCtor->isMoveConstructor() &&
4502 !FieldRecord->isTriviallyCopyable())
4503 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004504 }
4505
4506 // We need the corresponding member of a union to be trivial so that
4507 // we can safely copy them all simultaneously.
4508 // FIXME: Note that performing the check here (where we rely on the lack
4509 // of an in-class initializer) is technically ill-formed. However, this
4510 // seems most obviously to be a bug in the standard.
4511 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004512 return true;
4513 }
Sean Hunte16da072011-10-10 06:18:57 +00004514 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4515 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4516 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004517 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004518 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004519 }
4520
Sean Hunte16da072011-10-10 06:18:57 +00004521 // We can't have all const members in a union when default-constructing,
4522 // or else they're all nonsensical garbage values that can't be changed.
4523 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004524 return true;
4525
4526 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004527}
4528
Sean Hunt7f410192011-05-14 05:23:24 +00004529bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4530 CXXRecordDecl *RD = MD->getParent();
4531 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004532 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004533 return false;
4534
Sean Hunt71a682f2011-05-18 03:41:58 +00004535 SourceLocation Loc = MD->getLocation();
4536
Sean Hunt7f410192011-05-14 05:23:24 +00004537 // Do access control from the constructor
4538 ContextRAII MethodContext(*this, MD);
4539
4540 bool Union = RD->isUnion();
4541
Sean Hunt661c67a2011-06-21 23:42:56 +00004542 unsigned ArgQuals =
4543 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4544 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004545
4546 // We do this because we should never actually use an anonymous
4547 // union's constructor.
4548 if (Union && RD->isAnonymousStructOrUnion())
4549 return false;
4550
Sean Hunt7f410192011-05-14 05:23:24 +00004551 // FIXME: We should put some diagnostic logic right into this function.
4552
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004553 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004554 // A defaulted [copy] assignment operator for class X is defined as deleted
4555 // if X has:
4556
4557 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4558 BE = RD->bases_end();
4559 BI != BE; ++BI) {
4560 // We'll handle this one later
4561 if (BI->isVirtual())
4562 continue;
4563
4564 QualType BaseType = BI->getType();
4565 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4566 assert(BaseDecl && "base isn't a CXXRecordDecl");
4567
4568 // -- a [direct base class] B that cannot be [copied] because overload
4569 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004570 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004571 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004572 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4573 0);
4574 if (!CopyOper || CopyOper->isDeleted())
4575 return true;
4576 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004577 return true;
4578 }
4579
4580 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4581 BE = RD->vbases_end();
4582 BI != BE; ++BI) {
4583 QualType BaseType = BI->getType();
4584 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4585 assert(BaseDecl && "base isn't a CXXRecordDecl");
4586
Sean Hunt7f410192011-05-14 05:23:24 +00004587 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004588 // resolution, as applied to B's [copy] assignment operator, results in
4589 // an ambiguity or a function that is deleted or inaccessible from the
4590 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004591 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4592 0);
4593 if (!CopyOper || CopyOper->isDeleted())
4594 return true;
4595 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004596 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004597 }
4598
4599 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4600 FE = RD->field_end();
4601 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004602 if (FI->isUnnamedBitfield())
4603 continue;
4604
Sean Hunt7f410192011-05-14 05:23:24 +00004605 QualType FieldType = Context.getBaseElementType(FI->getType());
4606
4607 // -- a non-static data member of reference type
4608 if (FieldType->isReferenceType())
4609 return true;
4610
4611 // -- a non-static data member of const non-class type (or array thereof)
4612 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4613 return true;
4614
4615 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4616
4617 if (FieldRecord) {
4618 // This is an anonymous union
4619 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4620 // Anonymous unions inside unions do not variant members create
4621 if (!Union) {
4622 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4623 UE = FieldRecord->field_end();
4624 UI != UE; ++UI) {
4625 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4626 CXXRecordDecl *UnionFieldRecord =
4627 UnionFieldType->getAsCXXRecordDecl();
4628
4629 // -- a variant member with a non-trivial [copy] assignment operator
4630 // and X is a union-like class
4631 if (UnionFieldRecord &&
4632 !UnionFieldRecord->hasTrivialCopyAssignment())
4633 return true;
4634 }
4635 }
4636
4637 // Don't try to initalize an anonymous union
4638 continue;
4639 // -- a variant member with a non-trivial [copy] assignment operator
4640 // and X is a union-like class
4641 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4642 return true;
4643 }
Sean Hunt7f410192011-05-14 05:23:24 +00004644
Sean Hunt661c67a2011-06-21 23:42:56 +00004645 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4646 false, 0);
4647 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004648 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004649 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004650 return true;
4651 }
4652 }
4653
4654 return false;
4655}
4656
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004657bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4658 CXXRecordDecl *RD = MD->getParent();
4659 assert(!RD->isDependentType() && "do deletion after instantiation");
4660 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4661 return false;
4662
4663 SourceLocation Loc = MD->getLocation();
4664
4665 // Do access control from the constructor
4666 ContextRAII MethodContext(*this, MD);
4667
4668 bool Union = RD->isUnion();
4669
4670 // We do this because we should never actually use an anonymous
4671 // union's constructor.
4672 if (Union && RD->isAnonymousStructOrUnion())
4673 return false;
4674
4675 // C++0x [class.copy]/20
4676 // A defaulted [move] assignment operator for class X is defined as deleted
4677 // if X has:
4678
4679 // -- for the move constructor, [...] any direct or indirect virtual base
4680 // class.
4681 if (RD->getNumVBases() != 0)
4682 return true;
4683
4684 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4685 BE = RD->bases_end();
4686 BI != BE; ++BI) {
4687
4688 QualType BaseType = BI->getType();
4689 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4690 assert(BaseDecl && "base isn't a CXXRecordDecl");
4691
4692 // -- a [direct base class] B that cannot be [moved] because overload
4693 // resolution, as applied to B's [move] assignment operator, results in
4694 // an ambiguity or a function that is deleted or inaccessible from the
4695 // assignment operator
4696 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4697 if (!MoveOper || MoveOper->isDeleted())
4698 return true;
4699 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4700 return true;
4701
4702 // -- for the move assignment operator, a [direct base class] with a type
4703 // that does not have a move assignment operator and is not trivially
4704 // copyable.
4705 if (!MoveOper->isMoveAssignmentOperator() &&
4706 !BaseDecl->isTriviallyCopyable())
4707 return true;
4708 }
4709
4710 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4711 FE = RD->field_end();
4712 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004713 if (FI->isUnnamedBitfield())
4714 continue;
4715
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004716 QualType FieldType = Context.getBaseElementType(FI->getType());
4717
4718 // -- a non-static data member of reference type
4719 if (FieldType->isReferenceType())
4720 return true;
4721
4722 // -- a non-static data member of const non-class type (or array thereof)
4723 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4724 return true;
4725
4726 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4727
4728 if (FieldRecord) {
4729 // This is an anonymous union
4730 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4731 // Anonymous unions inside unions do not variant members create
4732 if (!Union) {
4733 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4734 UE = FieldRecord->field_end();
4735 UI != UE; ++UI) {
4736 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4737 CXXRecordDecl *UnionFieldRecord =
4738 UnionFieldType->getAsCXXRecordDecl();
4739
4740 // -- a variant member with a non-trivial [move] assignment operator
4741 // and X is a union-like class
4742 if (UnionFieldRecord &&
4743 !UnionFieldRecord->hasTrivialMoveAssignment())
4744 return true;
4745 }
4746 }
4747
4748 // Don't try to initalize an anonymous union
4749 continue;
4750 // -- a variant member with a non-trivial [move] assignment operator
4751 // and X is a union-like class
4752 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4753 return true;
4754 }
4755
4756 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4757 if (!MoveOper || MoveOper->isDeleted())
4758 return true;
4759 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4760 return true;
4761
4762 // -- for the move assignment operator, a [non-static data member] with a
4763 // type that does not have a move assignment operator and is not
4764 // trivially copyable.
4765 if (!MoveOper->isMoveAssignmentOperator() &&
4766 !FieldRecord->isTriviallyCopyable())
4767 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004768 }
Sean Hunt7f410192011-05-14 05:23:24 +00004769 }
4770
4771 return false;
4772}
4773
Sean Huntcb45a0f2011-05-12 22:46:25 +00004774bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4775 CXXRecordDecl *RD = DD->getParent();
4776 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004777 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004778 return false;
4779
Sean Hunt71a682f2011-05-18 03:41:58 +00004780 SourceLocation Loc = DD->getLocation();
4781
Sean Huntcb45a0f2011-05-12 22:46:25 +00004782 // Do access control from the destructor
4783 ContextRAII CtorContext(*this, DD);
4784
4785 bool Union = RD->isUnion();
4786
Sean Hunt49634cf2011-05-13 06:10:58 +00004787 // We do this because we should never actually use an anonymous
4788 // union's destructor.
4789 if (Union && RD->isAnonymousStructOrUnion())
4790 return false;
4791
Sean Huntcb45a0f2011-05-12 22:46:25 +00004792 // C++0x [class.dtor]p5
4793 // A defaulted destructor for a class X is defined as deleted if:
4794 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4795 BE = RD->bases_end();
4796 BI != BE; ++BI) {
4797 // We'll handle this one later
4798 if (BI->isVirtual())
4799 continue;
4800
4801 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4802 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4803 assert(BaseDtor && "base has no destructor");
4804
4805 // -- any direct or virtual base class has a deleted destructor or
4806 // a destructor that is inaccessible from the defaulted destructor
4807 if (BaseDtor->isDeleted())
4808 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004809 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004810 AR_accessible)
4811 return true;
4812 }
4813
4814 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4815 BE = RD->vbases_end();
4816 BI != BE; ++BI) {
4817 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4818 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4819 assert(BaseDtor && "base has no destructor");
4820
4821 // -- any direct or virtual base class has a deleted destructor or
4822 // a destructor that is inaccessible from the defaulted destructor
4823 if (BaseDtor->isDeleted())
4824 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004825 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004826 AR_accessible)
4827 return true;
4828 }
4829
4830 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4831 FE = RD->field_end();
4832 FI != FE; ++FI) {
4833 QualType FieldType = Context.getBaseElementType(FI->getType());
4834 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4835 if (FieldRecord) {
4836 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4837 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4838 UE = FieldRecord->field_end();
4839 UI != UE; ++UI) {
4840 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4841 CXXRecordDecl *UnionFieldRecord =
4842 UnionFieldType->getAsCXXRecordDecl();
4843
4844 // -- X is a union-like class that has a variant member with a non-
4845 // trivial destructor.
4846 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4847 return true;
4848 }
4849 // Technically we are supposed to do this next check unconditionally.
4850 // But that makes absolutely no sense.
4851 } else {
4852 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4853
4854 // -- any of the non-static data members has class type M (or array
4855 // thereof) and M has a deleted destructor or a destructor that is
4856 // inaccessible from the defaulted destructor
4857 if (FieldDtor->isDeleted())
4858 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004859 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004860 AR_accessible)
4861 return true;
4862
4863 // -- X is a union-like class that has a variant member with a non-
4864 // trivial destructor.
4865 if (Union && !FieldDtor->isTrivial())
4866 return true;
4867 }
4868 }
4869 }
4870
4871 if (DD->isVirtual()) {
4872 FunctionDecl *OperatorDelete = 0;
4873 DeclarationName Name =
4874 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004875 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004876 false))
4877 return true;
4878 }
4879
4880
4881 return false;
4882}
4883
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004884/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004885namespace {
4886 struct FindHiddenVirtualMethodData {
4887 Sema *S;
4888 CXXMethodDecl *Method;
4889 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004890 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004891 };
4892}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004893
4894/// \brief Member lookup function that determines whether a given C++
4895/// method overloads virtual methods in a base class without overriding any,
4896/// to be used with CXXRecordDecl::lookupInBases().
4897static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4898 CXXBasePath &Path,
4899 void *UserData) {
4900 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4901
4902 FindHiddenVirtualMethodData &Data
4903 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4904
4905 DeclarationName Name = Data.Method->getDeclName();
4906 assert(Name.getNameKind() == DeclarationName::Identifier);
4907
4908 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004909 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004910 for (Path.Decls = BaseRecord->lookup(Name);
4911 Path.Decls.first != Path.Decls.second;
4912 ++Path.Decls.first) {
4913 NamedDecl *D = *Path.Decls.first;
4914 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004915 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004916 foundSameNameMethod = true;
4917 // Interested only in hidden virtual methods.
4918 if (!MD->isVirtual())
4919 continue;
4920 // If the method we are checking overrides a method from its base
4921 // don't warn about the other overloaded methods.
4922 if (!Data.S->IsOverload(Data.Method, MD, false))
4923 return true;
4924 // Collect the overload only if its hidden.
4925 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4926 overloadedMethods.push_back(MD);
4927 }
4928 }
4929
4930 if (foundSameNameMethod)
4931 Data.OverloadedMethods.append(overloadedMethods.begin(),
4932 overloadedMethods.end());
4933 return foundSameNameMethod;
4934}
4935
4936/// \brief See if a method overloads virtual methods in a base class without
4937/// overriding any.
4938void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4939 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004940 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004941 return;
4942 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4943 return;
4944
4945 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4946 /*bool RecordPaths=*/false,
4947 /*bool DetectVirtual=*/false);
4948 FindHiddenVirtualMethodData Data;
4949 Data.Method = MD;
4950 Data.S = this;
4951
4952 // Keep the base methods that were overriden or introduced in the subclass
4953 // by 'using' in a set. A base method not in this set is hidden.
4954 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4955 res.first != res.second; ++res.first) {
4956 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4957 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4958 E = MD->end_overridden_methods();
4959 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004960 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004961 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4962 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004963 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004964 }
4965
4966 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4967 !Data.OverloadedMethods.empty()) {
4968 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4969 << MD << (Data.OverloadedMethods.size() > 1);
4970
4971 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4972 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4973 Diag(overloadedMD->getLocation(),
4974 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4975 }
4976 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004977}
4978
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004979void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004980 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004981 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004982 SourceLocation RBrac,
4983 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004984 if (!TagDecl)
4985 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004986
Douglas Gregor42af25f2009-05-11 19:58:34 +00004987 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004988
David Blaikie77b6de02011-09-22 02:58:26 +00004989 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004990 // strict aliasing violation!
4991 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004992 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004993
Douglas Gregor23c94db2010-07-02 17:43:08 +00004994 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004995 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004996}
4997
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004998/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4999/// special functions, such as the default constructor, copy
5000/// constructor, or destructor, to the given C++ class (C++
5001/// [special]p1). This routine can only be executed just before the
5002/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005003void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005004 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005005 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005006
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005007 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005008 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005009
Richard Smithb701d3d2011-12-24 21:56:24 +00005010 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5011 ++ASTContext::NumImplicitMoveConstructors;
5012
Douglas Gregora376d102010-07-02 21:50:04 +00005013 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5014 ++ASTContext::NumImplicitCopyAssignmentOperators;
5015
5016 // If we have a dynamic class, then the copy assignment operator may be
5017 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5018 // it shows up in the right place in the vtable and that we diagnose
5019 // problems with the implicit exception specification.
5020 if (ClassDecl->isDynamicClass())
5021 DeclareImplicitCopyAssignment(ClassDecl);
5022 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005023
Richard Smithb701d3d2011-12-24 21:56:24 +00005024 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5025 ++ASTContext::NumImplicitMoveAssignmentOperators;
5026
5027 // Likewise for the move assignment operator.
5028 if (ClassDecl->isDynamicClass())
5029 DeclareImplicitMoveAssignment(ClassDecl);
5030 }
5031
Douglas Gregor4923aa22010-07-02 20:37:36 +00005032 if (!ClassDecl->hasUserDeclaredDestructor()) {
5033 ++ASTContext::NumImplicitDestructors;
5034
5035 // If we have a dynamic class, then the destructor may be virtual, so we
5036 // have to declare the destructor immediately. This ensures that, e.g., it
5037 // shows up in the right place in the vtable and that we diagnose problems
5038 // with the implicit exception specification.
5039 if (ClassDecl->isDynamicClass())
5040 DeclareImplicitDestructor(ClassDecl);
5041 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005042}
5043
Francois Pichet8387e2a2011-04-22 22:18:13 +00005044void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5045 if (!D)
5046 return;
5047
5048 int NumParamList = D->getNumTemplateParameterLists();
5049 for (int i = 0; i < NumParamList; i++) {
5050 TemplateParameterList* Params = D->getTemplateParameterList(i);
5051 for (TemplateParameterList::iterator Param = Params->begin(),
5052 ParamEnd = Params->end();
5053 Param != ParamEnd; ++Param) {
5054 NamedDecl *Named = cast<NamedDecl>(*Param);
5055 if (Named->getDeclName()) {
5056 S->AddDecl(Named);
5057 IdResolver.AddDecl(Named);
5058 }
5059 }
5060 }
5061}
5062
John McCalld226f652010-08-21 09:40:31 +00005063void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005064 if (!D)
5065 return;
5066
5067 TemplateParameterList *Params = 0;
5068 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5069 Params = Template->getTemplateParameters();
5070 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5071 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5072 Params = PartialSpec->getTemplateParameters();
5073 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005074 return;
5075
Douglas Gregor6569d682009-05-27 23:11:45 +00005076 for (TemplateParameterList::iterator Param = Params->begin(),
5077 ParamEnd = Params->end();
5078 Param != ParamEnd; ++Param) {
5079 NamedDecl *Named = cast<NamedDecl>(*Param);
5080 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005081 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005082 IdResolver.AddDecl(Named);
5083 }
5084 }
5085}
5086
John McCalld226f652010-08-21 09:40:31 +00005087void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005088 if (!RecordD) return;
5089 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005090 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005091 PushDeclContext(S, Record);
5092}
5093
John McCalld226f652010-08-21 09:40:31 +00005094void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005095 if (!RecordD) return;
5096 PopDeclContext();
5097}
5098
Douglas Gregor72b505b2008-12-16 21:30:33 +00005099/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5100/// parsing a top-level (non-nested) C++ class, and we are now
5101/// parsing those parts of the given Method declaration that could
5102/// not be parsed earlier (C++ [class.mem]p2), such as default
5103/// arguments. This action should enter the scope of the given
5104/// Method declaration as if we had just parsed the qualified method
5105/// name. However, it should not bring the parameters into scope;
5106/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005107void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005108}
5109
5110/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5111/// C++ method declaration. We're (re-)introducing the given
5112/// function parameter into scope for use in parsing later parts of
5113/// the method declaration. For example, we could see an
5114/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005115void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005116 if (!ParamD)
5117 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005118
John McCalld226f652010-08-21 09:40:31 +00005119 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005120
5121 // If this parameter has an unparsed default argument, clear it out
5122 // to make way for the parsed default argument.
5123 if (Param->hasUnparsedDefaultArg())
5124 Param->setDefaultArg(0);
5125
John McCalld226f652010-08-21 09:40:31 +00005126 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005127 if (Param->getDeclName())
5128 IdResolver.AddDecl(Param);
5129}
5130
5131/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5132/// processing the delayed method declaration for Method. The method
5133/// declaration is now considered finished. There may be a separate
5134/// ActOnStartOfFunctionDef action later (not necessarily
5135/// immediately!) for this method, if it was also defined inside the
5136/// class body.
John McCalld226f652010-08-21 09:40:31 +00005137void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005138 if (!MethodD)
5139 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005140
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005141 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005142
John McCalld226f652010-08-21 09:40:31 +00005143 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005144
5145 // Now that we have our default arguments, check the constructor
5146 // again. It could produce additional diagnostics or affect whether
5147 // the class has implicitly-declared destructors, among other
5148 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005149 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5150 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005151
5152 // Check the default arguments, which we may have added.
5153 if (!Method->isInvalidDecl())
5154 CheckCXXDefaultArguments(Method);
5155}
5156
Douglas Gregor42a552f2008-11-05 20:51:48 +00005157/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005158/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005159/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005160/// emit diagnostics and set the invalid bit to true. In any case, the type
5161/// will be updated to reflect a well-formed type for the constructor and
5162/// returned.
5163QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005164 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005165 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005166
5167 // C++ [class.ctor]p3:
5168 // A constructor shall not be virtual (10.3) or static (9.4). A
5169 // constructor can be invoked for a const, volatile or const
5170 // volatile object. A constructor shall not be declared const,
5171 // volatile, or const volatile (9.3.2).
5172 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005173 if (!D.isInvalidType())
5174 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5175 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5176 << SourceRange(D.getIdentifierLoc());
5177 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005178 }
John McCalld931b082010-08-26 03:08:43 +00005179 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005180 if (!D.isInvalidType())
5181 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5182 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5183 << SourceRange(D.getIdentifierLoc());
5184 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005185 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005186 }
Mike Stump1eb44332009-09-09 15:08:12 +00005187
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005188 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005189 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005190 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005191 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5192 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005193 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005194 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5195 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005196 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005197 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5198 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005199 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005200 }
Mike Stump1eb44332009-09-09 15:08:12 +00005201
Douglas Gregorc938c162011-01-26 05:01:58 +00005202 // C++0x [class.ctor]p4:
5203 // A constructor shall not be declared with a ref-qualifier.
5204 if (FTI.hasRefQualifier()) {
5205 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5206 << FTI.RefQualifierIsLValueRef
5207 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5208 D.setInvalidType();
5209 }
5210
Douglas Gregor42a552f2008-11-05 20:51:48 +00005211 // Rebuild the function type "R" without any type qualifiers (in
5212 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005213 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005214 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005215 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5216 return R;
5217
5218 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5219 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005220 EPI.RefQualifier = RQ_None;
5221
Chris Lattner65401802009-04-25 08:28:21 +00005222 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005223 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005224}
5225
Douglas Gregor72b505b2008-12-16 21:30:33 +00005226/// CheckConstructor - Checks a fully-formed constructor for
5227/// well-formedness, issuing any diagnostics required. Returns true if
5228/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005229void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005230 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005231 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5232 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005233 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005234
5235 // C++ [class.copy]p3:
5236 // A declaration of a constructor for a class X is ill-formed if
5237 // its first parameter is of type (optionally cv-qualified) X and
5238 // either there are no other parameters or else all other
5239 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005240 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005241 ((Constructor->getNumParams() == 1) ||
5242 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005243 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5244 Constructor->getTemplateSpecializationKind()
5245 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005246 QualType ParamType = Constructor->getParamDecl(0)->getType();
5247 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5248 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005249 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005250 const char *ConstRef
5251 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5252 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005253 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005254 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005255
5256 // FIXME: Rather that making the constructor invalid, we should endeavor
5257 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005258 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005259 }
5260 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005261}
5262
John McCall15442822010-08-04 01:04:25 +00005263/// CheckDestructor - Checks a fully-formed destructor definition for
5264/// well-formedness, issuing any diagnostics required. Returns true
5265/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005266bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005267 CXXRecordDecl *RD = Destructor->getParent();
5268
5269 if (Destructor->isVirtual()) {
5270 SourceLocation Loc;
5271
5272 if (!Destructor->isImplicit())
5273 Loc = Destructor->getLocation();
5274 else
5275 Loc = RD->getLocation();
5276
5277 // If we have a virtual destructor, look up the deallocation function
5278 FunctionDecl *OperatorDelete = 0;
5279 DeclarationName Name =
5280 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005281 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005282 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005283
5284 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005285
5286 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005287 }
Anders Carlsson37909802009-11-30 21:24:50 +00005288
5289 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005290}
5291
Mike Stump1eb44332009-09-09 15:08:12 +00005292static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005293FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5294 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5295 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005296 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005297}
5298
Douglas Gregor42a552f2008-11-05 20:51:48 +00005299/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5300/// the well-formednes of the destructor declarator @p D with type @p
5301/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005302/// emit diagnostics and set the declarator to invalid. Even if this happens,
5303/// will be updated to reflect a well-formed type for the destructor and
5304/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005305QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005306 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005307 // C++ [class.dtor]p1:
5308 // [...] A typedef-name that names a class is a class-name
5309 // (7.1.3); however, a typedef-name that names a class shall not
5310 // be used as the identifier in the declarator for a destructor
5311 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005312 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005313 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005314 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005315 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005316 else if (const TemplateSpecializationType *TST =
5317 DeclaratorType->getAs<TemplateSpecializationType>())
5318 if (TST->isTypeAlias())
5319 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5320 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005321
5322 // C++ [class.dtor]p2:
5323 // A destructor is used to destroy objects of its class type. A
5324 // destructor takes no parameters, and no return type can be
5325 // specified for it (not even void). The address of a destructor
5326 // shall not be taken. A destructor shall not be static. A
5327 // destructor can be invoked for a const, volatile or const
5328 // volatile object. A destructor shall not be declared const,
5329 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005330 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005331 if (!D.isInvalidType())
5332 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5333 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005334 << SourceRange(D.getIdentifierLoc())
5335 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5336
John McCalld931b082010-08-26 03:08:43 +00005337 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005338 }
Chris Lattner65401802009-04-25 08:28:21 +00005339 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005340 // Destructors don't have return types, but the parser will
5341 // happily parse something like:
5342 //
5343 // class X {
5344 // float ~X();
5345 // };
5346 //
5347 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005348 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5349 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5350 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005351 }
Mike Stump1eb44332009-09-09 15:08:12 +00005352
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005353 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005354 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005355 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005356 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5357 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005358 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005359 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5360 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005361 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005362 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5363 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005364 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005365 }
5366
Douglas Gregorc938c162011-01-26 05:01:58 +00005367 // C++0x [class.dtor]p2:
5368 // A destructor shall not be declared with a ref-qualifier.
5369 if (FTI.hasRefQualifier()) {
5370 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5371 << FTI.RefQualifierIsLValueRef
5372 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5373 D.setInvalidType();
5374 }
5375
Douglas Gregor42a552f2008-11-05 20:51:48 +00005376 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005377 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005378 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5379
5380 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005381 FTI.freeArgs();
5382 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005383 }
5384
Mike Stump1eb44332009-09-09 15:08:12 +00005385 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005386 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005387 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005388 D.setInvalidType();
5389 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005390
5391 // Rebuild the function type "R" without any type qualifiers or
5392 // parameters (in case any of the errors above fired) and with
5393 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005394 // types.
John McCalle23cf432010-12-14 08:05:40 +00005395 if (!D.isInvalidType())
5396 return R;
5397
Douglas Gregord92ec472010-07-01 05:10:53 +00005398 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005399 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5400 EPI.Variadic = false;
5401 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005402 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005403 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005404}
5405
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005406/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5407/// well-formednes of the conversion function declarator @p D with
5408/// type @p R. If there are any errors in the declarator, this routine
5409/// will emit diagnostics and return true. Otherwise, it will return
5410/// false. Either way, the type @p R will be updated to reflect a
5411/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005412void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005413 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005414 // C++ [class.conv.fct]p1:
5415 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005416 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005417 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005418 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005419 if (!D.isInvalidType())
5420 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5421 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5422 << SourceRange(D.getIdentifierLoc());
5423 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005424 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005425 }
John McCalla3f81372010-04-13 00:04:31 +00005426
5427 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5428
Chris Lattner6e475012009-04-25 08:35:12 +00005429 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005430 // Conversion functions don't have return types, but the parser will
5431 // happily parse something like:
5432 //
5433 // class X {
5434 // float operator bool();
5435 // };
5436 //
5437 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005438 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5439 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5440 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005441 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005442 }
5443
John McCalla3f81372010-04-13 00:04:31 +00005444 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5445
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005446 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005447 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005448 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5449
5450 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005451 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005452 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005453 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005454 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005455 D.setInvalidType();
5456 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005457
John McCalla3f81372010-04-13 00:04:31 +00005458 // Diagnose "&operator bool()" and other such nonsense. This
5459 // is actually a gcc extension which we don't support.
5460 if (Proto->getResultType() != ConvType) {
5461 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5462 << Proto->getResultType();
5463 D.setInvalidType();
5464 ConvType = Proto->getResultType();
5465 }
5466
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005467 // C++ [class.conv.fct]p4:
5468 // The conversion-type-id shall not represent a function type nor
5469 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005470 if (ConvType->isArrayType()) {
5471 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5472 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005473 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005474 } else if (ConvType->isFunctionType()) {
5475 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5476 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005477 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005478 }
5479
5480 // Rebuild the function type "R" without any parameters (in case any
5481 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005482 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005483 if (D.isInvalidType())
5484 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005485
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005486 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005487 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005488 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005489 getLangOptions().CPlusPlus0x ?
5490 diag::warn_cxx98_compat_explicit_conversion_functions :
5491 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005492 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005493}
5494
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005495/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5496/// the declaration of the given C++ conversion function. This routine
5497/// is responsible for recording the conversion function in the C++
5498/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005499Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005500 assert(Conversion && "Expected to receive a conversion function declaration");
5501
Douglas Gregor9d350972008-12-12 08:25:50 +00005502 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005503
5504 // Make sure we aren't redeclaring the conversion function.
5505 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005506
5507 // C++ [class.conv.fct]p1:
5508 // [...] A conversion function is never used to convert a
5509 // (possibly cv-qualified) object to the (possibly cv-qualified)
5510 // same object type (or a reference to it), to a (possibly
5511 // cv-qualified) base class of that type (or a reference to it),
5512 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005513 // FIXME: Suppress this warning if the conversion function ends up being a
5514 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005515 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005516 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005517 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005518 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005519 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5520 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005521 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005522 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005523 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5524 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005525 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005526 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005527 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005528 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005529 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005530 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005531 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005532 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005533 }
5534
Douglas Gregore80622f2010-09-29 04:25:11 +00005535 if (FunctionTemplateDecl *ConversionTemplate
5536 = Conversion->getDescribedFunctionTemplate())
5537 return ConversionTemplate;
5538
John McCalld226f652010-08-21 09:40:31 +00005539 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005540}
5541
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005542//===----------------------------------------------------------------------===//
5543// Namespace Handling
5544//===----------------------------------------------------------------------===//
5545
John McCallea318642010-08-26 09:15:37 +00005546
5547
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005548/// ActOnStartNamespaceDef - This is called at the start of a namespace
5549/// definition.
John McCalld226f652010-08-21 09:40:31 +00005550Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005551 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005552 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005553 SourceLocation IdentLoc,
5554 IdentifierInfo *II,
5555 SourceLocation LBrace,
5556 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005557 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5558 // For anonymous namespace, take the location of the left brace.
5559 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005560 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005561 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005562 bool IsStd = false;
5563 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005564 Scope *DeclRegionScope = NamespcScope->getParent();
5565
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005566 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005567 if (II) {
5568 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005569 // The identifier in an original-namespace-definition shall not
5570 // have been previously defined in the declarative region in
5571 // which the original-namespace-definition appears. The
5572 // identifier in an original-namespace-definition is the name of
5573 // the namespace. Subsequently in that declarative region, it is
5574 // treated as an original-namespace-name.
5575 //
5576 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005577 // look through using directives, just look for any ordinary names.
5578
5579 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005580 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5581 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005582 NamedDecl *PrevDecl = 0;
5583 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005584 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005585 R.first != R.second; ++R.first) {
5586 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5587 PrevDecl = *R.first;
5588 break;
5589 }
5590 }
5591
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005592 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5593
5594 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005595 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005596 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005597 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005598 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005599 // The user probably just forgot the 'inline', so suggest that it
5600 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005601 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005602 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5603 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005604 Diag(Loc, diag::err_inline_namespace_mismatch)
5605 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005606 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005607 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5608
5609 IsInline = PrevNS->isInline();
5610 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005611 } else if (PrevDecl) {
5612 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005613 Diag(Loc, diag::err_redefinition_different_kind)
5614 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005615 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005616 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005617 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005618 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005619 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005620 // This is the first "real" definition of the namespace "std", so update
5621 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005622 PrevNS = getStdNamespace();
5623 IsStd = true;
5624 AddToKnown = !IsInline;
5625 } else {
5626 // We've seen this namespace for the first time.
5627 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005628 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005629 } else {
John McCall9aeed322009-10-01 00:25:31 +00005630 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005631
5632 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005633 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005634 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005635 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005636 } else {
5637 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005638 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005639 }
5640
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005641 if (PrevNS && IsInline != PrevNS->isInline()) {
5642 // inline-ness must match
5643 Diag(Loc, diag::err_inline_namespace_mismatch)
5644 << IsInline;
5645 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005646
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005647 // Recover by ignoring the new namespace's inline status.
5648 IsInline = PrevNS->isInline();
5649 }
5650 }
5651
5652 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5653 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005654 if (IsInvalid)
5655 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005656
5657 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005658
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005659 // FIXME: Should we be merging attributes?
5660 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5661 PushNamespaceVisibilityAttr(Attr);
5662
5663 if (IsStd)
5664 StdNamespace = Namespc;
5665 if (AddToKnown)
5666 KnownNamespaces[Namespc] = false;
5667
5668 if (II) {
5669 PushOnScopeChains(Namespc, DeclRegionScope);
5670 } else {
5671 // Link the anonymous namespace into its parent.
5672 DeclContext *Parent = CurContext->getRedeclContext();
5673 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5674 TU->setAnonymousNamespace(Namespc);
5675 } else {
5676 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005677 }
John McCall9aeed322009-10-01 00:25:31 +00005678
Douglas Gregora4181472010-03-24 00:46:35 +00005679 CurContext->addDecl(Namespc);
5680
John McCall9aeed322009-10-01 00:25:31 +00005681 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5682 // behaves as if it were replaced by
5683 // namespace unique { /* empty body */ }
5684 // using namespace unique;
5685 // namespace unique { namespace-body }
5686 // where all occurrences of 'unique' in a translation unit are
5687 // replaced by the same identifier and this identifier differs
5688 // from all other identifiers in the entire program.
5689
5690 // We just create the namespace with an empty name and then add an
5691 // implicit using declaration, just like the standard suggests.
5692 //
5693 // CodeGen enforces the "universally unique" aspect by giving all
5694 // declarations semantically contained within an anonymous
5695 // namespace internal linkage.
5696
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005697 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005698 UsingDirectiveDecl* UD
5699 = UsingDirectiveDecl::Create(Context, CurContext,
5700 /* 'using' */ LBrace,
5701 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005702 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005703 /* identifier */ SourceLocation(),
5704 Namespc,
5705 /* Ancestor */ CurContext);
5706 UD->setImplicit();
5707 CurContext->addDecl(UD);
5708 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005709 }
5710
5711 // Although we could have an invalid decl (i.e. the namespace name is a
5712 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005713 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5714 // for the namespace has the declarations that showed up in that particular
5715 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005716 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005717 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005718}
5719
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005720/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5721/// is a namespace alias, returns the namespace it points to.
5722static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5723 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5724 return AD->getNamespace();
5725 return dyn_cast_or_null<NamespaceDecl>(D);
5726}
5727
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005728/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5729/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005730void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005731 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5732 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005733 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005734 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005735 if (Namespc->hasAttr<VisibilityAttr>())
5736 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005737}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005738
John McCall384aff82010-08-25 07:42:41 +00005739CXXRecordDecl *Sema::getStdBadAlloc() const {
5740 return cast_or_null<CXXRecordDecl>(
5741 StdBadAlloc.get(Context.getExternalSource()));
5742}
5743
5744NamespaceDecl *Sema::getStdNamespace() const {
5745 return cast_or_null<NamespaceDecl>(
5746 StdNamespace.get(Context.getExternalSource()));
5747}
5748
Douglas Gregor66992202010-06-29 17:53:46 +00005749/// \brief Retrieve the special "std" namespace, which may require us to
5750/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005751NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005752 if (!StdNamespace) {
5753 // The "std" namespace has not yet been defined, so build one implicitly.
5754 StdNamespace = NamespaceDecl::Create(Context,
5755 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005756 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005757 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005758 &PP.getIdentifierTable().get("std"),
5759 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005760 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005761 }
5762
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005763 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005764}
5765
Douglas Gregor9172aa62011-03-26 22:25:30 +00005766/// \brief Determine whether a using statement is in a context where it will be
5767/// apply in all contexts.
5768static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5769 switch (CurContext->getDeclKind()) {
5770 case Decl::TranslationUnit:
5771 return true;
5772 case Decl::LinkageSpec:
5773 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5774 default:
5775 return false;
5776 }
5777}
5778
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005779namespace {
5780
5781// Callback to only accept typo corrections that are namespaces.
5782class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5783 public:
5784 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5785 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5786 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5787 }
5788 return false;
5789 }
5790};
5791
5792}
5793
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005794static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5795 CXXScopeSpec &SS,
5796 SourceLocation IdentLoc,
5797 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005798 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005799 R.clear();
5800 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005801 R.getLookupKind(), Sc, &SS,
5802 &Validator)) {
5803 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5804 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5805 if (DeclContext *DC = S.computeDeclContext(SS, false))
5806 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5807 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5808 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5809 else
5810 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5811 << Ident << CorrectedQuotedStr
5812 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005813
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005814 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5815 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005816
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005817 Ident = Corrected.getCorrectionAsIdentifierInfo();
5818 R.addDecl(Corrected.getCorrectionDecl());
5819 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005820 }
5821 return false;
5822}
5823
John McCalld226f652010-08-21 09:40:31 +00005824Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005825 SourceLocation UsingLoc,
5826 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005827 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005828 SourceLocation IdentLoc,
5829 IdentifierInfo *NamespcName,
5830 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005831 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5832 assert(NamespcName && "Invalid NamespcName.");
5833 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005834
5835 // This can only happen along a recovery path.
5836 while (S->getFlags() & Scope::TemplateParamScope)
5837 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005838 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005839
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005840 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005841 NestedNameSpecifier *Qualifier = 0;
5842 if (SS.isSet())
5843 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5844
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005845 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005846 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5847 LookupParsedName(R, S, &SS);
5848 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005849 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005850
Douglas Gregor66992202010-06-29 17:53:46 +00005851 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005852 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005853 // Allow "using namespace std;" or "using namespace ::std;" even if
5854 // "std" hasn't been defined yet, for GCC compatibility.
5855 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5856 NamespcName->isStr("std")) {
5857 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005858 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005859 R.resolveKind();
5860 }
5861 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005862 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005863 }
5864
John McCallf36e02d2009-10-09 21:13:30 +00005865 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005866 NamedDecl *Named = R.getFoundDecl();
5867 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5868 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005869 // C++ [namespace.udir]p1:
5870 // A using-directive specifies that the names in the nominated
5871 // namespace can be used in the scope in which the
5872 // using-directive appears after the using-directive. During
5873 // unqualified name lookup (3.4.1), the names appear as if they
5874 // were declared in the nearest enclosing namespace which
5875 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005876 // namespace. [Note: in this context, "contains" means "contains
5877 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005878
5879 // Find enclosing context containing both using-directive and
5880 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005881 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005882 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5883 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5884 CommonAncestor = CommonAncestor->getParent();
5885
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005886 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005887 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005888 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005889
Douglas Gregor9172aa62011-03-26 22:25:30 +00005890 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005891 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005892 Diag(IdentLoc, diag::warn_using_directive_in_header);
5893 }
5894
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005895 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005896 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005897 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005898 }
5899
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005900 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005901 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005902}
5903
5904void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5905 // If scope has associated entity, then using directive is at namespace
5906 // or translation unit scope. We add UsingDirectiveDecls, into
5907 // it's lookup structure.
5908 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005909 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005910 else
5911 // Otherwise it is block-sope. using-directives will affect lookup
5912 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005913 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005914}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005915
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005916
John McCalld226f652010-08-21 09:40:31 +00005917Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005918 AccessSpecifier AS,
5919 bool HasUsingKeyword,
5920 SourceLocation UsingLoc,
5921 CXXScopeSpec &SS,
5922 UnqualifiedId &Name,
5923 AttributeList *AttrList,
5924 bool IsTypeName,
5925 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005926 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005927
Douglas Gregor12c118a2009-11-04 16:30:06 +00005928 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005929 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005930 case UnqualifiedId::IK_Identifier:
5931 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005932 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005933 case UnqualifiedId::IK_ConversionFunctionId:
5934 break;
5935
5936 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005937 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005938 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00005939 Diag(Name.getSourceRange().getBegin(),
5940 getLangOptions().CPlusPlus0x ?
5941 diag::warn_cxx98_compat_using_decl_constructor :
5942 diag::err_using_decl_constructor)
5943 << SS.getRange();
5944
John McCall604e7f12009-12-08 07:46:18 +00005945 if (getLangOptions().CPlusPlus0x) break;
5946
John McCalld226f652010-08-21 09:40:31 +00005947 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005948
5949 case UnqualifiedId::IK_DestructorName:
5950 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5951 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005952 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005953
5954 case UnqualifiedId::IK_TemplateId:
5955 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5956 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005957 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005958 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005959
5960 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5961 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005962 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005963 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005964
John McCall60fa3cf2009-12-11 02:10:03 +00005965 // Warn about using declarations.
5966 // TODO: store that the declaration was written without 'using' and
5967 // talk about access decls instead of using decls in the
5968 // diagnostics.
5969 if (!HasUsingKeyword) {
5970 UsingLoc = Name.getSourceRange().getBegin();
5971
5972 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005973 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005974 }
5975
Douglas Gregor56c04582010-12-16 00:46:58 +00005976 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5977 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5978 return 0;
5979
John McCall9488ea12009-11-17 05:59:44 +00005980 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005981 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005982 /* IsInstantiation */ false,
5983 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005984 if (UD)
5985 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005986
John McCalld226f652010-08-21 09:40:31 +00005987 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005988}
5989
Douglas Gregor09acc982010-07-07 23:08:52 +00005990/// \brief Determine whether a using declaration considers the given
5991/// declarations as "equivalent", e.g., if they are redeclarations of
5992/// the same entity or are both typedefs of the same type.
5993static bool
5994IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5995 bool &SuppressRedeclaration) {
5996 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5997 SuppressRedeclaration = false;
5998 return true;
5999 }
6000
Richard Smith162e1c12011-04-15 14:24:37 +00006001 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6002 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006003 SuppressRedeclaration = true;
6004 return Context.hasSameType(TD1->getUnderlyingType(),
6005 TD2->getUnderlyingType());
6006 }
6007
6008 return false;
6009}
6010
6011
John McCall9f54ad42009-12-10 09:41:52 +00006012/// Determines whether to create a using shadow decl for a particular
6013/// decl, given the set of decls existing prior to this using lookup.
6014bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6015 const LookupResult &Previous) {
6016 // Diagnose finding a decl which is not from a base class of the
6017 // current class. We do this now because there are cases where this
6018 // function will silently decide not to build a shadow decl, which
6019 // will pre-empt further diagnostics.
6020 //
6021 // We don't need to do this in C++0x because we do the check once on
6022 // the qualifier.
6023 //
6024 // FIXME: diagnose the following if we care enough:
6025 // struct A { int foo; };
6026 // struct B : A { using A::foo; };
6027 // template <class T> struct C : A {};
6028 // template <class T> struct D : C<T> { using B::foo; } // <---
6029 // This is invalid (during instantiation) in C++03 because B::foo
6030 // resolves to the using decl in B, which is not a base class of D<T>.
6031 // We can't diagnose it immediately because C<T> is an unknown
6032 // specialization. The UsingShadowDecl in D<T> then points directly
6033 // to A::foo, which will look well-formed when we instantiate.
6034 // The right solution is to not collapse the shadow-decl chain.
6035 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6036 DeclContext *OrigDC = Orig->getDeclContext();
6037
6038 // Handle enums and anonymous structs.
6039 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6040 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6041 while (OrigRec->isAnonymousStructOrUnion())
6042 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6043
6044 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6045 if (OrigDC == CurContext) {
6046 Diag(Using->getLocation(),
6047 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006048 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006049 Diag(Orig->getLocation(), diag::note_using_decl_target);
6050 return true;
6051 }
6052
Douglas Gregordc355712011-02-25 00:36:19 +00006053 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006054 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006055 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006056 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006057 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006058 Diag(Orig->getLocation(), diag::note_using_decl_target);
6059 return true;
6060 }
6061 }
6062
6063 if (Previous.empty()) return false;
6064
6065 NamedDecl *Target = Orig;
6066 if (isa<UsingShadowDecl>(Target))
6067 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6068
John McCalld7533ec2009-12-11 02:33:26 +00006069 // If the target happens to be one of the previous declarations, we
6070 // don't have a conflict.
6071 //
6072 // FIXME: but we might be increasing its access, in which case we
6073 // should redeclare it.
6074 NamedDecl *NonTag = 0, *Tag = 0;
6075 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6076 I != E; ++I) {
6077 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006078 bool Result;
6079 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6080 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006081
6082 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6083 }
6084
John McCall9f54ad42009-12-10 09:41:52 +00006085 if (Target->isFunctionOrFunctionTemplate()) {
6086 FunctionDecl *FD;
6087 if (isa<FunctionTemplateDecl>(Target))
6088 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6089 else
6090 FD = cast<FunctionDecl>(Target);
6091
6092 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006093 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006094 case Ovl_Overload:
6095 return false;
6096
6097 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006098 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006099 break;
6100
6101 // We found a decl with the exact signature.
6102 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006103 // If we're in a record, we want to hide the target, so we
6104 // return true (without a diagnostic) to tell the caller not to
6105 // build a shadow decl.
6106 if (CurContext->isRecord())
6107 return true;
6108
6109 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006110 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006111 break;
6112 }
6113
6114 Diag(Target->getLocation(), diag::note_using_decl_target);
6115 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6116 return true;
6117 }
6118
6119 // Target is not a function.
6120
John McCall9f54ad42009-12-10 09:41:52 +00006121 if (isa<TagDecl>(Target)) {
6122 // No conflict between a tag and a non-tag.
6123 if (!Tag) return false;
6124
John McCall41ce66f2009-12-10 19:51:03 +00006125 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006126 Diag(Target->getLocation(), diag::note_using_decl_target);
6127 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6128 return true;
6129 }
6130
6131 // No conflict between a tag and a non-tag.
6132 if (!NonTag) return false;
6133
John McCall41ce66f2009-12-10 19:51:03 +00006134 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006135 Diag(Target->getLocation(), diag::note_using_decl_target);
6136 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6137 return true;
6138}
6139
John McCall9488ea12009-11-17 05:59:44 +00006140/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006141UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006142 UsingDecl *UD,
6143 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006144
6145 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006146 NamedDecl *Target = Orig;
6147 if (isa<UsingShadowDecl>(Target)) {
6148 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6149 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006150 }
6151
6152 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006153 = UsingShadowDecl::Create(Context, CurContext,
6154 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006155 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006156
6157 Shadow->setAccess(UD->getAccess());
6158 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6159 Shadow->setInvalidDecl();
6160
John McCall9488ea12009-11-17 05:59:44 +00006161 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006162 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006163 else
John McCall604e7f12009-12-08 07:46:18 +00006164 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006165
John McCall604e7f12009-12-08 07:46:18 +00006166
John McCall9f54ad42009-12-10 09:41:52 +00006167 return Shadow;
6168}
John McCall604e7f12009-12-08 07:46:18 +00006169
John McCall9f54ad42009-12-10 09:41:52 +00006170/// Hides a using shadow declaration. This is required by the current
6171/// using-decl implementation when a resolvable using declaration in a
6172/// class is followed by a declaration which would hide or override
6173/// one or more of the using decl's targets; for example:
6174///
6175/// struct Base { void foo(int); };
6176/// struct Derived : Base {
6177/// using Base::foo;
6178/// void foo(int);
6179/// };
6180///
6181/// The governing language is C++03 [namespace.udecl]p12:
6182///
6183/// When a using-declaration brings names from a base class into a
6184/// derived class scope, member functions in the derived class
6185/// override and/or hide member functions with the same name and
6186/// parameter types in a base class (rather than conflicting).
6187///
6188/// There are two ways to implement this:
6189/// (1) optimistically create shadow decls when they're not hidden
6190/// by existing declarations, or
6191/// (2) don't create any shadow decls (or at least don't make them
6192/// visible) until we've fully parsed/instantiated the class.
6193/// The problem with (1) is that we might have to retroactively remove
6194/// a shadow decl, which requires several O(n) operations because the
6195/// decl structures are (very reasonably) not designed for removal.
6196/// (2) avoids this but is very fiddly and phase-dependent.
6197void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006198 if (Shadow->getDeclName().getNameKind() ==
6199 DeclarationName::CXXConversionFunctionName)
6200 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6201
John McCall9f54ad42009-12-10 09:41:52 +00006202 // Remove it from the DeclContext...
6203 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006204
John McCall9f54ad42009-12-10 09:41:52 +00006205 // ...and the scope, if applicable...
6206 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006207 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006208 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006209 }
6210
John McCall9f54ad42009-12-10 09:41:52 +00006211 // ...and the using decl.
6212 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6213
6214 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006215 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006216}
6217
John McCall7ba107a2009-11-18 02:36:19 +00006218/// Builds a using declaration.
6219///
6220/// \param IsInstantiation - Whether this call arises from an
6221/// instantiation of an unresolved using declaration. We treat
6222/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006223NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6224 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006225 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006226 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006227 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006228 bool IsInstantiation,
6229 bool IsTypeName,
6230 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006231 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006232 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006233 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006234
Anders Carlsson550b14b2009-08-28 05:49:21 +00006235 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006236
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006237 if (SS.isEmpty()) {
6238 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006239 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006240 }
Mike Stump1eb44332009-09-09 15:08:12 +00006241
John McCall9f54ad42009-12-10 09:41:52 +00006242 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006243 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006244 ForRedeclaration);
6245 Previous.setHideTags(false);
6246 if (S) {
6247 LookupName(Previous, S);
6248
6249 // It is really dumb that we have to do this.
6250 LookupResult::Filter F = Previous.makeFilter();
6251 while (F.hasNext()) {
6252 NamedDecl *D = F.next();
6253 if (!isDeclInScope(D, CurContext, S))
6254 F.erase();
6255 }
6256 F.done();
6257 } else {
6258 assert(IsInstantiation && "no scope in non-instantiation");
6259 assert(CurContext->isRecord() && "scope not record in instantiation");
6260 LookupQualifiedName(Previous, CurContext);
6261 }
6262
John McCall9f54ad42009-12-10 09:41:52 +00006263 // Check for invalid redeclarations.
6264 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6265 return 0;
6266
6267 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006268 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6269 return 0;
6270
John McCallaf8e6ed2009-11-12 03:15:40 +00006271 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006272 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006273 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006274 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006275 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006276 // FIXME: not all declaration name kinds are legal here
6277 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6278 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006279 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006280 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006281 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006282 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6283 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006284 }
John McCalled976492009-12-04 22:46:56 +00006285 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006286 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6287 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006288 }
John McCalled976492009-12-04 22:46:56 +00006289 D->setAccess(AS);
6290 CurContext->addDecl(D);
6291
6292 if (!LookupContext) return D;
6293 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006294
John McCall77bb1aa2010-05-01 00:40:08 +00006295 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006296 UD->setInvalidDecl();
6297 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006298 }
6299
Sebastian Redlf677ea32011-02-05 19:23:19 +00006300 // Constructor inheriting using decls get special treatment.
6301 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006302 if (CheckInheritedConstructorUsingDecl(UD))
6303 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006304 return UD;
6305 }
6306
6307 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006308
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006309 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006310
John McCall604e7f12009-12-08 07:46:18 +00006311 // Unlike most lookups, we don't always want to hide tag
6312 // declarations: tag names are visible through the using declaration
6313 // even if hidden by ordinary names, *except* in a dependent context
6314 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006315 if (!IsInstantiation)
6316 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006317
John McCalla24dc2e2009-11-17 02:14:36 +00006318 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006319
John McCallf36e02d2009-10-09 21:13:30 +00006320 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006321 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006322 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006323 UD->setInvalidDecl();
6324 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006325 }
6326
John McCalled976492009-12-04 22:46:56 +00006327 if (R.isAmbiguous()) {
6328 UD->setInvalidDecl();
6329 return UD;
6330 }
Mike Stump1eb44332009-09-09 15:08:12 +00006331
John McCall7ba107a2009-11-18 02:36:19 +00006332 if (IsTypeName) {
6333 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006334 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006335 Diag(IdentLoc, diag::err_using_typename_non_type);
6336 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6337 Diag((*I)->getUnderlyingDecl()->getLocation(),
6338 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006339 UD->setInvalidDecl();
6340 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006341 }
6342 } else {
6343 // If we asked for a non-typename and we got a type, error out,
6344 // but only if this is an instantiation of an unresolved using
6345 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006346 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006347 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6348 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006349 UD->setInvalidDecl();
6350 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006351 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006352 }
6353
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006354 // C++0x N2914 [namespace.udecl]p6:
6355 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006356 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006357 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6358 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006359 UD->setInvalidDecl();
6360 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006361 }
Mike Stump1eb44332009-09-09 15:08:12 +00006362
John McCall9f54ad42009-12-10 09:41:52 +00006363 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6364 if (!CheckUsingShadowDecl(UD, *I, Previous))
6365 BuildUsingShadowDecl(S, UD, *I);
6366 }
John McCall9488ea12009-11-17 05:59:44 +00006367
6368 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006369}
6370
Sebastian Redlf677ea32011-02-05 19:23:19 +00006371/// Additional checks for a using declaration referring to a constructor name.
6372bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6373 if (UD->isTypeName()) {
6374 // FIXME: Cannot specify typename when specifying constructor
6375 return true;
6376 }
6377
Douglas Gregordc355712011-02-25 00:36:19 +00006378 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006379 assert(SourceType &&
6380 "Using decl naming constructor doesn't have type in scope spec.");
6381 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6382
6383 // Check whether the named type is a direct base class.
6384 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6385 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6386 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6387 BaseIt != BaseE; ++BaseIt) {
6388 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6389 if (CanonicalSourceType == BaseType)
6390 break;
6391 }
6392
6393 if (BaseIt == BaseE) {
6394 // Did not find SourceType in the bases.
6395 Diag(UD->getUsingLocation(),
6396 diag::err_using_decl_constructor_not_in_direct_base)
6397 << UD->getNameInfo().getSourceRange()
6398 << QualType(SourceType, 0) << TargetClass;
6399 return true;
6400 }
6401
6402 BaseIt->setInheritConstructors();
6403
6404 return false;
6405}
6406
John McCall9f54ad42009-12-10 09:41:52 +00006407/// Checks that the given using declaration is not an invalid
6408/// redeclaration. Note that this is checking only for the using decl
6409/// itself, not for any ill-formedness among the UsingShadowDecls.
6410bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6411 bool isTypeName,
6412 const CXXScopeSpec &SS,
6413 SourceLocation NameLoc,
6414 const LookupResult &Prev) {
6415 // C++03 [namespace.udecl]p8:
6416 // C++0x [namespace.udecl]p10:
6417 // A using-declaration is a declaration and can therefore be used
6418 // repeatedly where (and only where) multiple declarations are
6419 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006420 //
John McCall8a726212010-11-29 18:01:58 +00006421 // That's in non-member contexts.
6422 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006423 return false;
6424
6425 NestedNameSpecifier *Qual
6426 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6427
6428 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6429 NamedDecl *D = *I;
6430
6431 bool DTypename;
6432 NestedNameSpecifier *DQual;
6433 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6434 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006435 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006436 } else if (UnresolvedUsingValueDecl *UD
6437 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6438 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006439 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006440 } else if (UnresolvedUsingTypenameDecl *UD
6441 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6442 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006443 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006444 } else continue;
6445
6446 // using decls differ if one says 'typename' and the other doesn't.
6447 // FIXME: non-dependent using decls?
6448 if (isTypeName != DTypename) continue;
6449
6450 // using decls differ if they name different scopes (but note that
6451 // template instantiation can cause this check to trigger when it
6452 // didn't before instantiation).
6453 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6454 Context.getCanonicalNestedNameSpecifier(DQual))
6455 continue;
6456
6457 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006458 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006459 return true;
6460 }
6461
6462 return false;
6463}
6464
John McCall604e7f12009-12-08 07:46:18 +00006465
John McCalled976492009-12-04 22:46:56 +00006466/// Checks that the given nested-name qualifier used in a using decl
6467/// in the current context is appropriately related to the current
6468/// scope. If an error is found, diagnoses it and returns true.
6469bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6470 const CXXScopeSpec &SS,
6471 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006472 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006473
John McCall604e7f12009-12-08 07:46:18 +00006474 if (!CurContext->isRecord()) {
6475 // C++03 [namespace.udecl]p3:
6476 // C++0x [namespace.udecl]p8:
6477 // A using-declaration for a class member shall be a member-declaration.
6478
6479 // If we weren't able to compute a valid scope, it must be a
6480 // dependent class scope.
6481 if (!NamedContext || NamedContext->isRecord()) {
6482 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6483 << SS.getRange();
6484 return true;
6485 }
6486
6487 // Otherwise, everything is known to be fine.
6488 return false;
6489 }
6490
6491 // The current scope is a record.
6492
6493 // If the named context is dependent, we can't decide much.
6494 if (!NamedContext) {
6495 // FIXME: in C++0x, we can diagnose if we can prove that the
6496 // nested-name-specifier does not refer to a base class, which is
6497 // still possible in some cases.
6498
6499 // Otherwise we have to conservatively report that things might be
6500 // okay.
6501 return false;
6502 }
6503
6504 if (!NamedContext->isRecord()) {
6505 // Ideally this would point at the last name in the specifier,
6506 // but we don't have that level of source info.
6507 Diag(SS.getRange().getBegin(),
6508 diag::err_using_decl_nested_name_specifier_is_not_class)
6509 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6510 return true;
6511 }
6512
Douglas Gregor6fb07292010-12-21 07:41:49 +00006513 if (!NamedContext->isDependentContext() &&
6514 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6515 return true;
6516
John McCall604e7f12009-12-08 07:46:18 +00006517 if (getLangOptions().CPlusPlus0x) {
6518 // C++0x [namespace.udecl]p3:
6519 // In a using-declaration used as a member-declaration, the
6520 // nested-name-specifier shall name a base class of the class
6521 // being defined.
6522
6523 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6524 cast<CXXRecordDecl>(NamedContext))) {
6525 if (CurContext == NamedContext) {
6526 Diag(NameLoc,
6527 diag::err_using_decl_nested_name_specifier_is_current_class)
6528 << SS.getRange();
6529 return true;
6530 }
6531
6532 Diag(SS.getRange().getBegin(),
6533 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6534 << (NestedNameSpecifier*) SS.getScopeRep()
6535 << cast<CXXRecordDecl>(CurContext)
6536 << SS.getRange();
6537 return true;
6538 }
6539
6540 return false;
6541 }
6542
6543 // C++03 [namespace.udecl]p4:
6544 // A using-declaration used as a member-declaration shall refer
6545 // to a member of a base class of the class being defined [etc.].
6546
6547 // Salient point: SS doesn't have to name a base class as long as
6548 // lookup only finds members from base classes. Therefore we can
6549 // diagnose here only if we can prove that that can't happen,
6550 // i.e. if the class hierarchies provably don't intersect.
6551
6552 // TODO: it would be nice if "definitely valid" results were cached
6553 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6554 // need to be repeated.
6555
6556 struct UserData {
6557 llvm::DenseSet<const CXXRecordDecl*> Bases;
6558
6559 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6560 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6561 Data->Bases.insert(Base);
6562 return true;
6563 }
6564
6565 bool hasDependentBases(const CXXRecordDecl *Class) {
6566 return !Class->forallBases(collect, this);
6567 }
6568
6569 /// Returns true if the base is dependent or is one of the
6570 /// accumulated base classes.
6571 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6572 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6573 return !Data->Bases.count(Base);
6574 }
6575
6576 bool mightShareBases(const CXXRecordDecl *Class) {
6577 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6578 }
6579 };
6580
6581 UserData Data;
6582
6583 // Returns false if we find a dependent base.
6584 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6585 return false;
6586
6587 // Returns false if the class has a dependent base or if it or one
6588 // of its bases is present in the base set of the current context.
6589 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6590 return false;
6591
6592 Diag(SS.getRange().getBegin(),
6593 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6594 << (NestedNameSpecifier*) SS.getScopeRep()
6595 << cast<CXXRecordDecl>(CurContext)
6596 << SS.getRange();
6597
6598 return true;
John McCalled976492009-12-04 22:46:56 +00006599}
6600
Richard Smith162e1c12011-04-15 14:24:37 +00006601Decl *Sema::ActOnAliasDeclaration(Scope *S,
6602 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006603 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006604 SourceLocation UsingLoc,
6605 UnqualifiedId &Name,
6606 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006607 // Skip up to the relevant declaration scope.
6608 while (S->getFlags() & Scope::TemplateParamScope)
6609 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006610 assert((S->getFlags() & Scope::DeclScope) &&
6611 "got alias-declaration outside of declaration scope");
6612
6613 if (Type.isInvalid())
6614 return 0;
6615
6616 bool Invalid = false;
6617 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6618 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006619 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006620
6621 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6622 return 0;
6623
6624 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006625 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006626 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006627 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6628 TInfo->getTypeLoc().getBeginLoc());
6629 }
Richard Smith162e1c12011-04-15 14:24:37 +00006630
6631 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6632 LookupName(Previous, S);
6633
6634 // Warn about shadowing the name of a template parameter.
6635 if (Previous.isSingleResult() &&
6636 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006637 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006638 Previous.clear();
6639 }
6640
6641 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6642 "name in alias declaration must be an identifier");
6643 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6644 Name.StartLocation,
6645 Name.Identifier, TInfo);
6646
6647 NewTD->setAccess(AS);
6648
6649 if (Invalid)
6650 NewTD->setInvalidDecl();
6651
Richard Smith3e4c6c42011-05-05 21:57:07 +00006652 CheckTypedefForVariablyModifiedType(S, NewTD);
6653 Invalid |= NewTD->isInvalidDecl();
6654
Richard Smith162e1c12011-04-15 14:24:37 +00006655 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006656
6657 NamedDecl *NewND;
6658 if (TemplateParamLists.size()) {
6659 TypeAliasTemplateDecl *OldDecl = 0;
6660 TemplateParameterList *OldTemplateParams = 0;
6661
6662 if (TemplateParamLists.size() != 1) {
6663 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6664 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6665 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6666 }
6667 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6668
6669 // Only consider previous declarations in the same scope.
6670 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6671 /*ExplicitInstantiationOrSpecialization*/false);
6672 if (!Previous.empty()) {
6673 Redeclaration = true;
6674
6675 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6676 if (!OldDecl && !Invalid) {
6677 Diag(UsingLoc, diag::err_redefinition_different_kind)
6678 << Name.Identifier;
6679
6680 NamedDecl *OldD = Previous.getRepresentativeDecl();
6681 if (OldD->getLocation().isValid())
6682 Diag(OldD->getLocation(), diag::note_previous_definition);
6683
6684 Invalid = true;
6685 }
6686
6687 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6688 if (TemplateParameterListsAreEqual(TemplateParams,
6689 OldDecl->getTemplateParameters(),
6690 /*Complain=*/true,
6691 TPL_TemplateMatch))
6692 OldTemplateParams = OldDecl->getTemplateParameters();
6693 else
6694 Invalid = true;
6695
6696 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6697 if (!Invalid &&
6698 !Context.hasSameType(OldTD->getUnderlyingType(),
6699 NewTD->getUnderlyingType())) {
6700 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6701 // but we can't reasonably accept it.
6702 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6703 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6704 if (OldTD->getLocation().isValid())
6705 Diag(OldTD->getLocation(), diag::note_previous_definition);
6706 Invalid = true;
6707 }
6708 }
6709 }
6710
6711 // Merge any previous default template arguments into our parameters,
6712 // and check the parameter list.
6713 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6714 TPC_TypeAliasTemplate))
6715 return 0;
6716
6717 TypeAliasTemplateDecl *NewDecl =
6718 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6719 Name.Identifier, TemplateParams,
6720 NewTD);
6721
6722 NewDecl->setAccess(AS);
6723
6724 if (Invalid)
6725 NewDecl->setInvalidDecl();
6726 else if (OldDecl)
6727 NewDecl->setPreviousDeclaration(OldDecl);
6728
6729 NewND = NewDecl;
6730 } else {
6731 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6732 NewND = NewTD;
6733 }
Richard Smith162e1c12011-04-15 14:24:37 +00006734
6735 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006736 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006737
Richard Smith3e4c6c42011-05-05 21:57:07 +00006738 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006739}
6740
John McCalld226f652010-08-21 09:40:31 +00006741Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006742 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006743 SourceLocation AliasLoc,
6744 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006745 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006746 SourceLocation IdentLoc,
6747 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006748
Anders Carlsson81c85c42009-03-28 23:53:49 +00006749 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006750 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6751 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006752
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006753 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006754 NamedDecl *PrevDecl
6755 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6756 ForRedeclaration);
6757 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6758 PrevDecl = 0;
6759
6760 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006761 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006762 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006763 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006764 // FIXME: At some point, we'll want to create the (redundant)
6765 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006766 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006767 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006768 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006769 }
Mike Stump1eb44332009-09-09 15:08:12 +00006770
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006771 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6772 diag::err_redefinition_different_kind;
6773 Diag(AliasLoc, DiagID) << Alias;
6774 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006775 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006776 }
6777
John McCalla24dc2e2009-11-17 02:14:36 +00006778 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006779 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006780
John McCallf36e02d2009-10-09 21:13:30 +00006781 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006782 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006783 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006784 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006785 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006786 }
Mike Stump1eb44332009-09-09 15:08:12 +00006787
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006788 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006789 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006790 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006791 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006792
John McCall3dbd3d52010-02-16 06:53:13 +00006793 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006794 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006795}
6796
Douglas Gregor39957dc2010-05-01 15:04:51 +00006797namespace {
6798 /// \brief Scoped object used to handle the state changes required in Sema
6799 /// to implicitly define the body of a C++ member function;
6800 class ImplicitlyDefinedFunctionScope {
6801 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006802 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006803
6804 public:
6805 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006806 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006807 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006808 S.PushFunctionScope();
6809 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6810 }
6811
6812 ~ImplicitlyDefinedFunctionScope() {
6813 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006814 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006815 }
6816 };
6817}
6818
Sean Hunt001cad92011-05-10 00:49:42 +00006819Sema::ImplicitExceptionSpecification
6820Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006821 // C++ [except.spec]p14:
6822 // An implicitly declared special member function (Clause 12) shall have an
6823 // exception-specification. [...]
6824 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006825 if (ClassDecl->isInvalidDecl())
6826 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006827
Sebastian Redl60618fa2011-03-12 11:50:43 +00006828 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006829 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6830 BEnd = ClassDecl->bases_end();
6831 B != BEnd; ++B) {
6832 if (B->isVirtual()) // Handled below.
6833 continue;
6834
Douglas Gregor18274032010-07-03 00:47:00 +00006835 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6836 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006837 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6838 // If this is a deleted function, add it anyway. This might be conformant
6839 // with the standard. This might not. I'm not sure. It might not matter.
6840 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006841 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006842 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006843 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006844
6845 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006846 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6847 BEnd = ClassDecl->vbases_end();
6848 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006849 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6850 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006851 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6852 // If this is a deleted function, add it anyway. This might be conformant
6853 // with the standard. This might not. I'm not sure. It might not matter.
6854 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006855 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006856 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006857 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006858
6859 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006860 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6861 FEnd = ClassDecl->field_end();
6862 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006863 if (F->hasInClassInitializer()) {
6864 if (Expr *E = F->getInClassInitializer())
6865 ExceptSpec.CalledExpr(E);
6866 else if (!F->isInvalidDecl())
6867 ExceptSpec.SetDelayed();
6868 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006869 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006870 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6871 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6872 // If this is a deleted function, add it anyway. This might be conformant
6873 // with the standard. This might not. I'm not sure. It might not matter.
6874 // In particular, the problem is that this function never gets called. It
6875 // might just be ill-formed because this function attempts to refer to
6876 // a deleted function here.
6877 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006878 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006879 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006880 }
John McCalle23cf432010-12-14 08:05:40 +00006881
Sean Hunt001cad92011-05-10 00:49:42 +00006882 return ExceptSpec;
6883}
6884
6885CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6886 CXXRecordDecl *ClassDecl) {
6887 // C++ [class.ctor]p5:
6888 // A default constructor for a class X is a constructor of class X
6889 // that can be called without an argument. If there is no
6890 // user-declared constructor for class X, a default constructor is
6891 // implicitly declared. An implicitly-declared default constructor
6892 // is an inline public member of its class.
6893 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6894 "Should not build implicit default constructor!");
6895
6896 ImplicitExceptionSpecification Spec =
6897 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6898 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006899
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006900 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006901 CanQualType ClassType
6902 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006903 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006904 DeclarationName Name
6905 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006906 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006907 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6908 Context, ClassDecl, ClassLoc, NameInfo,
6909 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6910 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6911 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
6912 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006913 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006914 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006915 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006916 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006917
6918 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006919 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6920
Douglas Gregor23c94db2010-07-02 17:43:08 +00006921 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006922 PushOnScopeChains(DefaultCon, S, false);
6923 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006924
Sean Hunte16da072011-10-10 06:18:57 +00006925 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006926 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006927
Douglas Gregor32df23e2010-07-01 22:02:46 +00006928 return DefaultCon;
6929}
6930
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006931void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6932 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006933 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006934 !Constructor->doesThisDeclarationHaveABody() &&
6935 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006936 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006937
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006938 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006939 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006940
Douglas Gregor39957dc2010-05-01 15:04:51 +00006941 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006942 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006943 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006944 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006945 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006946 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006947 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006948 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006949 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006950
6951 SourceLocation Loc = Constructor->getLocation();
6952 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6953
6954 Constructor->setUsed();
6955 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006956
6957 if (ASTMutationListener *L = getASTMutationListener()) {
6958 L->CompletedImplicitDefinition(Constructor);
6959 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006960}
6961
Richard Smith7a614d82011-06-11 17:19:42 +00006962/// Get any existing defaulted default constructor for the given class. Do not
6963/// implicitly define one if it does not exist.
6964static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6965 CXXRecordDecl *D) {
6966 ASTContext &Context = Self.Context;
6967 QualType ClassType = Context.getTypeDeclType(D);
6968 DeclarationName ConstructorName
6969 = Context.DeclarationNames.getCXXConstructorName(
6970 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6971
6972 DeclContext::lookup_const_iterator Con, ConEnd;
6973 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6974 Con != ConEnd; ++Con) {
6975 // A function template cannot be defaulted.
6976 if (isa<FunctionTemplateDecl>(*Con))
6977 continue;
6978
6979 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6980 if (Constructor->isDefaultConstructor())
6981 return Constructor->isDefaulted() ? Constructor : 0;
6982 }
6983 return 0;
6984}
6985
6986void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6987 if (!D) return;
6988 AdjustDeclIfTemplate(D);
6989
6990 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6991 CXXConstructorDecl *CtorDecl
6992 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6993
6994 if (!CtorDecl) return;
6995
6996 // Compute the exception specification for the default constructor.
6997 const FunctionProtoType *CtorTy =
6998 CtorDecl->getType()->castAs<FunctionProtoType>();
6999 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7000 ImplicitExceptionSpecification Spec =
7001 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7002 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7003 assert(EPI.ExceptionSpecType != EST_Delayed);
7004
7005 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7006 }
7007
7008 // If the default constructor is explicitly defaulted, checking the exception
7009 // specification is deferred until now.
7010 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7011 !ClassDecl->isDependentType())
7012 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7013}
7014
Sebastian Redlf677ea32011-02-05 19:23:19 +00007015void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7016 // We start with an initial pass over the base classes to collect those that
7017 // inherit constructors from. If there are none, we can forgo all further
7018 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007019 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007020 BasesVector BasesToInheritFrom;
7021 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7022 BaseE = ClassDecl->bases_end();
7023 BaseIt != BaseE; ++BaseIt) {
7024 if (BaseIt->getInheritConstructors()) {
7025 QualType Base = BaseIt->getType();
7026 if (Base->isDependentType()) {
7027 // If we inherit constructors from anything that is dependent, just
7028 // abort processing altogether. We'll get another chance for the
7029 // instantiations.
7030 return;
7031 }
7032 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7033 }
7034 }
7035 if (BasesToInheritFrom.empty())
7036 return;
7037
7038 // Now collect the constructors that we already have in the current class.
7039 // Those take precedence over inherited constructors.
7040 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7041 // unless there is a user-declared constructor with the same signature in
7042 // the class where the using-declaration appears.
7043 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7044 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7045 CtorE = ClassDecl->ctor_end();
7046 CtorIt != CtorE; ++CtorIt) {
7047 ExistingConstructors.insert(
7048 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7049 }
7050
7051 Scope *S = getScopeForContext(ClassDecl);
7052 DeclarationName CreatedCtorName =
7053 Context.DeclarationNames.getCXXConstructorName(
7054 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7055
7056 // Now comes the true work.
7057 // First, we keep a map from constructor types to the base that introduced
7058 // them. Needed for finding conflicting constructors. We also keep the
7059 // actually inserted declarations in there, for pretty diagnostics.
7060 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7061 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7062 ConstructorToSourceMap InheritedConstructors;
7063 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7064 BaseE = BasesToInheritFrom.end();
7065 BaseIt != BaseE; ++BaseIt) {
7066 const RecordType *Base = *BaseIt;
7067 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7068 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7069 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7070 CtorE = BaseDecl->ctor_end();
7071 CtorIt != CtorE; ++CtorIt) {
7072 // Find the using declaration for inheriting this base's constructors.
7073 DeclarationName Name =
7074 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7075 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7076 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7077 SourceLocation UsingLoc = UD ? UD->getLocation() :
7078 ClassDecl->getLocation();
7079
7080 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7081 // from the class X named in the using-declaration consists of actual
7082 // constructors and notional constructors that result from the
7083 // transformation of defaulted parameters as follows:
7084 // - all non-template default constructors of X, and
7085 // - for each non-template constructor of X that has at least one
7086 // parameter with a default argument, the set of constructors that
7087 // results from omitting any ellipsis parameter specification and
7088 // successively omitting parameters with a default argument from the
7089 // end of the parameter-type-list.
7090 CXXConstructorDecl *BaseCtor = *CtorIt;
7091 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7092 const FunctionProtoType *BaseCtorType =
7093 BaseCtor->getType()->getAs<FunctionProtoType>();
7094
7095 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7096 maxParams = BaseCtor->getNumParams();
7097 params <= maxParams; ++params) {
7098 // Skip default constructors. They're never inherited.
7099 if (params == 0)
7100 continue;
7101 // Skip copy and move constructors for the same reason.
7102 if (CanBeCopyOrMove && params == 1)
7103 continue;
7104
7105 // Build up a function type for this particular constructor.
7106 // FIXME: The working paper does not consider that the exception spec
7107 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007108 // source. This code doesn't yet, either. When it does, this code will
7109 // need to be delayed until after exception specifications and in-class
7110 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007111 const Type *NewCtorType;
7112 if (params == maxParams)
7113 NewCtorType = BaseCtorType;
7114 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007115 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007116 for (unsigned i = 0; i < params; ++i) {
7117 Args.push_back(BaseCtorType->getArgType(i));
7118 }
7119 FunctionProtoType::ExtProtoInfo ExtInfo =
7120 BaseCtorType->getExtProtoInfo();
7121 ExtInfo.Variadic = false;
7122 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7123 Args.data(), params, ExtInfo)
7124 .getTypePtr();
7125 }
7126 const Type *CanonicalNewCtorType =
7127 Context.getCanonicalType(NewCtorType);
7128
7129 // Now that we have the type, first check if the class already has a
7130 // constructor with this signature.
7131 if (ExistingConstructors.count(CanonicalNewCtorType))
7132 continue;
7133
7134 // Then we check if we have already declared an inherited constructor
7135 // with this signature.
7136 std::pair<ConstructorToSourceMap::iterator, bool> result =
7137 InheritedConstructors.insert(std::make_pair(
7138 CanonicalNewCtorType,
7139 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7140 if (!result.second) {
7141 // Already in the map. If it came from a different class, that's an
7142 // error. Not if it's from the same.
7143 CanQualType PreviousBase = result.first->second.first;
7144 if (CanonicalBase != PreviousBase) {
7145 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7146 const CXXConstructorDecl *PrevBaseCtor =
7147 PrevCtor->getInheritedConstructor();
7148 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7149
7150 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7151 Diag(BaseCtor->getLocation(),
7152 diag::note_using_decl_constructor_conflict_current_ctor);
7153 Diag(PrevBaseCtor->getLocation(),
7154 diag::note_using_decl_constructor_conflict_previous_ctor);
7155 Diag(PrevCtor->getLocation(),
7156 diag::note_using_decl_constructor_conflict_previous_using);
7157 }
7158 continue;
7159 }
7160
7161 // OK, we're there, now add the constructor.
7162 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007163 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007164 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7165 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007166 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7167 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007168 /*ImplicitlyDeclared=*/true,
7169 // FIXME: Due to a defect in the standard, we treat inherited
7170 // constructors as constexpr even if that makes them ill-formed.
7171 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007172 NewCtor->setAccess(BaseCtor->getAccess());
7173
7174 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007175 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007176 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007177 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7178 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007179 /*IdentifierInfo=*/0,
7180 BaseCtorType->getArgType(i),
7181 /*TInfo=*/0, SC_None,
7182 SC_None, /*DefaultArg=*/0));
7183 }
David Blaikie4278c652011-09-21 18:16:56 +00007184 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007185 NewCtor->setInheritedConstructor(BaseCtor);
7186
7187 PushOnScopeChains(NewCtor, S, false);
7188 ClassDecl->addDecl(NewCtor);
7189 result.first->second.second = NewCtor;
7190 }
7191 }
7192 }
7193}
7194
Sean Huntcb45a0f2011-05-12 22:46:25 +00007195Sema::ImplicitExceptionSpecification
7196Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007197 // C++ [except.spec]p14:
7198 // An implicitly declared special member function (Clause 12) shall have
7199 // an exception-specification.
7200 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007201 if (ClassDecl->isInvalidDecl())
7202 return ExceptSpec;
7203
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007204 // Direct base-class destructors.
7205 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7206 BEnd = ClassDecl->bases_end();
7207 B != BEnd; ++B) {
7208 if (B->isVirtual()) // Handled below.
7209 continue;
7210
7211 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7212 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007213 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007214 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007215
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007216 // Virtual base-class destructors.
7217 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7218 BEnd = ClassDecl->vbases_end();
7219 B != BEnd; ++B) {
7220 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7221 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007222 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007223 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007224
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007225 // Field destructors.
7226 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7227 FEnd = ClassDecl->field_end();
7228 F != FEnd; ++F) {
7229 if (const RecordType *RecordTy
7230 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7231 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007232 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007233 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007234
Sean Huntcb45a0f2011-05-12 22:46:25 +00007235 return ExceptSpec;
7236}
7237
7238CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7239 // C++ [class.dtor]p2:
7240 // If a class has no user-declared destructor, a destructor is
7241 // declared implicitly. An implicitly-declared destructor is an
7242 // inline public member of its class.
7243
7244 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007245 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007246 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7247
Douglas Gregor4923aa22010-07-02 20:37:36 +00007248 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007249 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007250
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007251 CanQualType ClassType
7252 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007253 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007254 DeclarationName Name
7255 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007256 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007257 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007258 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7259 /*isInline=*/true,
7260 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007261 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007262 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007263 Destructor->setImplicit();
7264 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007265
7266 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007267 ++ASTContext::NumImplicitDestructorsDeclared;
7268
7269 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007270 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007271 PushOnScopeChains(Destructor, S, false);
7272 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007273
7274 // This could be uniqued if it ever proves significant.
7275 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007276
7277 if (ShouldDeleteDestructor(Destructor))
7278 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007279
7280 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007281
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007282 return Destructor;
7283}
7284
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007285void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007286 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007287 assert((Destructor->isDefaulted() &&
7288 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007289 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007290 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007291 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007292
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007293 if (Destructor->isInvalidDecl())
7294 return;
7295
Douglas Gregor39957dc2010-05-01 15:04:51 +00007296 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007297
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007298 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007299 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7300 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007301
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007302 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007303 Diag(CurrentLocation, diag::note_member_synthesized_at)
7304 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7305
7306 Destructor->setInvalidDecl();
7307 return;
7308 }
7309
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007310 SourceLocation Loc = Destructor->getLocation();
7311 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007312 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007313 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007314 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007315
7316 if (ASTMutationListener *L = getASTMutationListener()) {
7317 L->CompletedImplicitDefinition(Destructor);
7318 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007319}
7320
Sebastian Redl0ee33912011-05-19 05:13:44 +00007321void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7322 CXXDestructorDecl *destructor) {
7323 // C++11 [class.dtor]p3:
7324 // A declaration of a destructor that does not have an exception-
7325 // specification is implicitly considered to have the same exception-
7326 // specification as an implicit declaration.
7327 const FunctionProtoType *dtorType = destructor->getType()->
7328 getAs<FunctionProtoType>();
7329 if (dtorType->hasExceptionSpec())
7330 return;
7331
7332 ImplicitExceptionSpecification exceptSpec =
7333 ComputeDefaultedDtorExceptionSpec(classDecl);
7334
Chandler Carruth3f224b22011-09-20 04:55:26 +00007335 // Replace the destructor's type, building off the existing one. Fortunately,
7336 // the only thing of interest in the destructor type is its extended info.
7337 // The return and arguments are fixed.
7338 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007339 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7340 epi.NumExceptions = exceptSpec.size();
7341 epi.Exceptions = exceptSpec.data();
7342 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7343
7344 destructor->setType(ty);
7345
7346 // FIXME: If the destructor has a body that could throw, and the newly created
7347 // spec doesn't allow exceptions, we should emit a warning, because this
7348 // change in behavior can break conforming C++03 programs at runtime.
7349 // However, we don't have a body yet, so it needs to be done somewhere else.
7350}
7351
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007352/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007353/// \c To.
7354///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007355/// This routine is used to copy/move the members of a class with an
7356/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007357/// copied are arrays, this routine builds for loops to copy them.
7358///
7359/// \param S The Sema object used for type-checking.
7360///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007361/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007362///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007363/// \param T The type of the expressions being copied/moved. Both expressions
7364/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007365///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007366/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007367///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007368/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007369///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007370/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007371/// Otherwise, it's a non-static member subobject.
7372///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007373/// \param Copying Whether we're copying or moving.
7374///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007375/// \param Depth Internal parameter recording the depth of the recursion.
7376///
7377/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007378static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007379BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007380 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007381 bool CopyingBaseSubobject, bool Copying,
7382 unsigned Depth = 0) {
7383 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007384 // Each subobject is assigned in the manner appropriate to its type:
7385 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007386 // - if the subobject is of class type, as if by a call to operator= with
7387 // the subobject as the object expression and the corresponding
7388 // subobject of x as a single function argument (as if by explicit
7389 // qualification; that is, ignoring any possible virtual overriding
7390 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007391 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7392 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7393
7394 // Look for operator=.
7395 DeclarationName Name
7396 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7397 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7398 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7399
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007400 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007401 LookupResult::Filter F = OpLookup.makeFilter();
7402 while (F.hasNext()) {
7403 NamedDecl *D = F.next();
7404 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007405 if (Copying ? Method->isCopyAssignmentOperator() :
7406 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007407 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007408
Douglas Gregor06a9f362010-05-01 20:49:11 +00007409 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007410 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007411 F.done();
7412
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007413 // Suppress the protected check (C++ [class.protected]) for each of the
7414 // assignment operators we found. This strange dance is required when
7415 // we're assigning via a base classes's copy-assignment operator. To
7416 // ensure that we're getting the right base class subobject (without
7417 // ambiguities), we need to cast "this" to that subobject type; to
7418 // ensure that we don't go through the virtual call mechanism, we need
7419 // to qualify the operator= name with the base class (see below). However,
7420 // this means that if the base class has a protected copy assignment
7421 // operator, the protected member access check will fail. So, we
7422 // rewrite "protected" access to "public" access in this case, since we
7423 // know by construction that we're calling from a derived class.
7424 if (CopyingBaseSubobject) {
7425 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7426 L != LEnd; ++L) {
7427 if (L.getAccess() == AS_protected)
7428 L.setAccess(AS_public);
7429 }
7430 }
7431
Douglas Gregor06a9f362010-05-01 20:49:11 +00007432 // Create the nested-name-specifier that will be used to qualify the
7433 // reference to operator=; this is required to suppress the virtual
7434 // call mechanism.
7435 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007436 SS.MakeTrivial(S.Context,
7437 NestedNameSpecifier::Create(S.Context, 0, false,
7438 T.getTypePtr()),
7439 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007440
7441 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007442 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007443 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007444 /*FirstQualifierInScope=*/0, OpLookup,
7445 /*TemplateArgs=*/0,
7446 /*SuppressQualifierCheck=*/true);
7447 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007448 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007449
7450 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007451
John McCall60d7b3a2010-08-24 06:29:42 +00007452 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007453 OpEqualRef.takeAs<Expr>(),
7454 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007455 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007456 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007457
7458 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007459 }
John McCallb0207482010-03-16 06:11:48 +00007460
Douglas Gregor06a9f362010-05-01 20:49:11 +00007461 // - if the subobject is of scalar type, the built-in assignment
7462 // operator is used.
7463 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7464 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007465 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007466 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007467 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007468
7469 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007470 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007471
7472 // - if the subobject is an array, each element is assigned, in the
7473 // manner appropriate to the element type;
7474
7475 // Construct a loop over the array bounds, e.g.,
7476 //
7477 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7478 //
7479 // that will copy each of the array elements.
7480 QualType SizeType = S.Context.getSizeType();
7481
7482 // Create the iteration variable.
7483 IdentifierInfo *IterationVarName = 0;
7484 {
7485 llvm::SmallString<8> Str;
7486 llvm::raw_svector_ostream OS(Str);
7487 OS << "__i" << Depth;
7488 IterationVarName = &S.Context.Idents.get(OS.str());
7489 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007490 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007491 IterationVarName, SizeType,
7492 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007493 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007494
7495 // Initialize the iteration variable to zero.
7496 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007497 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007498
7499 // Create a reference to the iteration variable; we'll use this several
7500 // times throughout.
7501 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00007502 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007503 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7504
7505 // Create the DeclStmt that holds the iteration variable.
7506 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7507
7508 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007509 llvm::APInt Upper
7510 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007511 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00007512 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00007513 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7514 BO_NE, S.Context.BoolTy,
7515 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007516
7517 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007518 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007519 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7520 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007521
7522 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007523 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7524 IterationVarRef, Loc));
7525 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7526 IterationVarRef, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007527 if (!Copying) // Cast to rvalue
7528 From = CastForMoving(S, From);
7529
7530 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007531 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7532 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007533 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007534 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007535 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007536
7537 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007538 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007539 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007540 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007541 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007542}
7543
Sean Hunt30de05c2011-05-14 05:23:20 +00007544std::pair<Sema::ImplicitExceptionSpecification, bool>
7545Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7546 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007547 if (ClassDecl->isInvalidDecl())
7548 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7549
Douglas Gregord3c35902010-07-01 16:36:15 +00007550 // C++ [class.copy]p10:
7551 // If the class definition does not explicitly declare a copy
7552 // assignment operator, one is declared implicitly.
7553 // The implicitly-defined copy assignment operator for a class X
7554 // will have the form
7555 //
7556 // X& X::operator=(const X&)
7557 //
7558 // if
7559 bool HasConstCopyAssignment = true;
7560
7561 // -- each direct base class B of X has a copy assignment operator
7562 // whose parameter is of type const B&, const volatile B& or B,
7563 // and
7564 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7565 BaseEnd = ClassDecl->bases_end();
7566 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007567 // We'll handle this below
7568 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7569 continue;
7570
Douglas Gregord3c35902010-07-01 16:36:15 +00007571 assert(!Base->getType()->isDependentType() &&
7572 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007573 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7574 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7575 &HasConstCopyAssignment);
7576 }
7577
Richard Smithebaf0e62011-10-18 20:49:44 +00007578 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007579 if (LangOpts.CPlusPlus0x) {
7580 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7581 BaseEnd = ClassDecl->vbases_end();
7582 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7583 assert(!Base->getType()->isDependentType() &&
7584 "Cannot generate implicit members for class with dependent bases.");
7585 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7586 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7587 &HasConstCopyAssignment);
7588 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007589 }
7590
7591 // -- for all the nonstatic data members of X that are of a class
7592 // type M (or array thereof), each such class type has a copy
7593 // assignment operator whose parameter is of type const M&,
7594 // const volatile M& or M.
7595 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7596 FieldEnd = ClassDecl->field_end();
7597 HasConstCopyAssignment && Field != FieldEnd;
7598 ++Field) {
7599 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007600 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7601 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7602 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007603 }
7604 }
7605
7606 // Otherwise, the implicitly declared copy assignment operator will
7607 // have the form
7608 //
7609 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007610
Douglas Gregorb87786f2010-07-01 17:48:08 +00007611 // C++ [except.spec]p14:
7612 // An implicitly declared special member function (Clause 12) shall have an
7613 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007614
7615 // It is unspecified whether or not an implicit copy assignment operator
7616 // attempts to deduplicate calls to assignment operators of virtual bases are
7617 // made. As such, this exception specification is effectively unspecified.
7618 // Based on a similar decision made for constness in C++0x, we're erring on
7619 // the side of assuming such calls to be made regardless of whether they
7620 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007621 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007622 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007623 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7624 BaseEnd = ClassDecl->bases_end();
7625 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007626 if (Base->isVirtual())
7627 continue;
7628
Douglas Gregora376d102010-07-02 21:50:04 +00007629 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007630 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007631 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7632 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007633 ExceptSpec.CalledDecl(CopyAssign);
7634 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007635
7636 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7637 BaseEnd = ClassDecl->vbases_end();
7638 Base != BaseEnd; ++Base) {
7639 CXXRecordDecl *BaseClassDecl
7640 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7641 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7642 ArgQuals, false, 0))
7643 ExceptSpec.CalledDecl(CopyAssign);
7644 }
7645
Douglas Gregorb87786f2010-07-01 17:48:08 +00007646 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7647 FieldEnd = ClassDecl->field_end();
7648 Field != FieldEnd;
7649 ++Field) {
7650 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007651 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7652 if (CXXMethodDecl *CopyAssign =
7653 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7654 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007655 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007656 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007657
Sean Hunt30de05c2011-05-14 05:23:20 +00007658 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7659}
7660
7661CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7662 // Note: The following rules are largely analoguous to the copy
7663 // constructor rules. Note that virtual bases are not taken into account
7664 // for determining the argument type of the operator. Note also that
7665 // operators taking an object instead of a reference are allowed.
7666
7667 ImplicitExceptionSpecification Spec(Context);
7668 bool Const;
7669 llvm::tie(Spec, Const) =
7670 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7671
7672 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7673 QualType RetType = Context.getLValueReferenceType(ArgType);
7674 if (Const)
7675 ArgType = ArgType.withConst();
7676 ArgType = Context.getLValueReferenceType(ArgType);
7677
Douglas Gregord3c35902010-07-01 16:36:15 +00007678 // An implicitly-declared copy assignment operator is an inline public
7679 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007680 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007681 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007682 SourceLocation ClassLoc = ClassDecl->getLocation();
7683 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007684 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007685 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007686 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007687 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007688 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007689 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007690 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007691 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007692 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007693 CopyAssignment->setImplicit();
7694 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007695
7696 // Add the parameter to the operator.
7697 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007698 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007699 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007700 SC_None,
7701 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007702 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007703
Douglas Gregora376d102010-07-02 21:50:04 +00007704 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007705 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007706
Douglas Gregor23c94db2010-07-02 17:43:08 +00007707 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007708 PushOnScopeChains(CopyAssignment, S, false);
7709 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007710
Sean Hunt1ccbc542011-06-22 01:05:13 +00007711 // C++0x [class.copy]p18:
7712 // ... If the class definition declares a move constructor or move
7713 // assignment operator, the implicitly declared copy assignment operator is
7714 // defined as deleted; ...
7715 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7716 ClassDecl->hasUserDeclaredMoveAssignment() ||
7717 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007718 CopyAssignment->setDeletedAsWritten();
7719
Douglas Gregord3c35902010-07-01 16:36:15 +00007720 AddOverriddenMethods(ClassDecl, CopyAssignment);
7721 return CopyAssignment;
7722}
7723
Douglas Gregor06a9f362010-05-01 20:49:11 +00007724void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7725 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007726 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007727 CopyAssignOperator->isOverloadedOperator() &&
7728 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007729 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007730 "DefineImplicitCopyAssignment called for wrong function");
7731
7732 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7733
7734 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7735 CopyAssignOperator->setInvalidDecl();
7736 return;
7737 }
7738
7739 CopyAssignOperator->setUsed();
7740
7741 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007742 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007743
7744 // C++0x [class.copy]p30:
7745 // The implicitly-defined or explicitly-defaulted copy assignment operator
7746 // for a non-union class X performs memberwise copy assignment of its
7747 // subobjects. The direct base classes of X are assigned first, in the
7748 // order of their declaration in the base-specifier-list, and then the
7749 // immediate non-static data members of X are assigned, in the order in
7750 // which they were declared in the class definition.
7751
7752 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007753 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007754
7755 // The parameter for the "other" object, which we are copying from.
7756 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7757 Qualifiers OtherQuals = Other->getType().getQualifiers();
7758 QualType OtherRefType = Other->getType();
7759 if (const LValueReferenceType *OtherRef
7760 = OtherRefType->getAs<LValueReferenceType>()) {
7761 OtherRefType = OtherRef->getPointeeType();
7762 OtherQuals = OtherRefType.getQualifiers();
7763 }
7764
7765 // Our location for everything implicitly-generated.
7766 SourceLocation Loc = CopyAssignOperator->getLocation();
7767
7768 // Construct a reference to the "other" object. We'll be using this
7769 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007770 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007771 assert(OtherRef && "Reference to parameter cannot fail!");
7772
7773 // Construct the "this" pointer. We'll be using this throughout the generated
7774 // ASTs.
7775 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7776 assert(This && "Reference to this cannot fail!");
7777
7778 // Assign base classes.
7779 bool Invalid = false;
7780 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7781 E = ClassDecl->bases_end(); Base != E; ++Base) {
7782 // Form the assignment:
7783 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7784 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007785 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007786 Invalid = true;
7787 continue;
7788 }
7789
John McCallf871d0c2010-08-07 06:22:56 +00007790 CXXCastPath BasePath;
7791 BasePath.push_back(Base);
7792
Douglas Gregor06a9f362010-05-01 20:49:11 +00007793 // Construct the "from" expression, which is an implicit cast to the
7794 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007795 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007796 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7797 CK_UncheckedDerivedToBase,
7798 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007799
7800 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007801 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007802
7803 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007804 To = ImpCastExprToType(To.take(),
7805 Context.getCVRQualifiedType(BaseType,
7806 CopyAssignOperator->getTypeQualifiers()),
7807 CK_UncheckedDerivedToBase,
7808 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007809
7810 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007811 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007812 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007813 /*CopyingBaseSubobject=*/true,
7814 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007815 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007816 Diag(CurrentLocation, diag::note_member_synthesized_at)
7817 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7818 CopyAssignOperator->setInvalidDecl();
7819 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007820 }
7821
7822 // Success! Record the copy.
7823 Statements.push_back(Copy.takeAs<Expr>());
7824 }
7825
7826 // \brief Reference to the __builtin_memcpy function.
7827 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007828 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007829 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007830
7831 // Assign non-static members.
7832 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7833 FieldEnd = ClassDecl->field_end();
7834 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007835 if (Field->isUnnamedBitfield())
7836 continue;
7837
Douglas Gregor06a9f362010-05-01 20:49:11 +00007838 // Check for members of reference type; we can't copy those.
7839 if (Field->getType()->isReferenceType()) {
7840 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7841 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7842 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007843 Diag(CurrentLocation, diag::note_member_synthesized_at)
7844 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007845 Invalid = true;
7846 continue;
7847 }
7848
7849 // Check for members of const-qualified, non-class type.
7850 QualType BaseType = Context.getBaseElementType(Field->getType());
7851 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7852 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7853 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7854 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007855 Diag(CurrentLocation, diag::note_member_synthesized_at)
7856 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007857 Invalid = true;
7858 continue;
7859 }
John McCallb77115d2011-06-17 00:18:42 +00007860
7861 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007862 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7863 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007864
7865 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007866 if (FieldType->isIncompleteArrayType()) {
7867 assert(ClassDecl->hasFlexibleArrayMember() &&
7868 "Incomplete array type is not valid");
7869 continue;
7870 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007871
7872 // Build references to the field in the object we're copying from and to.
7873 CXXScopeSpec SS; // Intentionally empty
7874 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7875 LookupMemberName);
7876 MemberLookup.addDecl(*Field);
7877 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007878 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007879 Loc, /*IsArrow=*/false,
7880 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007881 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007882 Loc, /*IsArrow=*/true,
7883 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007884 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7885 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7886
7887 // If the field should be copied with __builtin_memcpy rather than via
7888 // explicit assignments, do so. This optimization only applies for arrays
7889 // of scalars and arrays of class type with trivial copy-assignment
7890 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007891 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007892 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007893 // Compute the size of the memory buffer to be copied.
7894 QualType SizeType = Context.getSizeType();
7895 llvm::APInt Size(Context.getTypeSize(SizeType),
7896 Context.getTypeSizeInChars(BaseType).getQuantity());
7897 for (const ConstantArrayType *Array
7898 = Context.getAsConstantArrayType(FieldType);
7899 Array;
7900 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007901 llvm::APInt ArraySize
7902 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007903 Size *= ArraySize;
7904 }
7905
7906 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007907 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7908 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007909
7910 bool NeedsCollectableMemCpy =
7911 (BaseType->isRecordType() &&
7912 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7913
7914 if (NeedsCollectableMemCpy) {
7915 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007916 // Create a reference to the __builtin_objc_memmove_collectable function.
7917 LookupResult R(*this,
7918 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007919 Loc, LookupOrdinaryName);
7920 LookupName(R, TUScope, true);
7921
7922 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7923 if (!CollectableMemCpy) {
7924 // Something went horribly wrong earlier, and we will have
7925 // complained about it.
7926 Invalid = true;
7927 continue;
7928 }
7929
7930 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7931 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007932 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007933 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7934 }
7935 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007936 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007937 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007938 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7939 LookupOrdinaryName);
7940 LookupName(R, TUScope, true);
7941
7942 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7943 if (!BuiltinMemCpy) {
7944 // Something went horribly wrong earlier, and we will have complained
7945 // about it.
7946 Invalid = true;
7947 continue;
7948 }
7949
7950 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7951 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007952 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007953 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7954 }
7955
John McCallca0408f2010-08-23 06:44:23 +00007956 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007957 CallArgs.push_back(To.takeAs<Expr>());
7958 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007959 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007960 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007961 if (NeedsCollectableMemCpy)
7962 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007963 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007964 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007965 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007966 else
7967 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007968 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007969 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007970 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007971
Douglas Gregor06a9f362010-05-01 20:49:11 +00007972 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7973 Statements.push_back(Call.takeAs<Expr>());
7974 continue;
7975 }
7976
7977 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007978 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007979 To.get(), From.get(),
7980 /*CopyingBaseSubobject=*/false,
7981 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007982 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007983 Diag(CurrentLocation, diag::note_member_synthesized_at)
7984 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7985 CopyAssignOperator->setInvalidDecl();
7986 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007987 }
7988
7989 // Success! Record the copy.
7990 Statements.push_back(Copy.takeAs<Stmt>());
7991 }
7992
7993 if (!Invalid) {
7994 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007995 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007996
John McCall60d7b3a2010-08-24 06:29:42 +00007997 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007998 if (Return.isInvalid())
7999 Invalid = true;
8000 else {
8001 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008002
8003 if (Trap.hasErrorOccurred()) {
8004 Diag(CurrentLocation, diag::note_member_synthesized_at)
8005 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8006 Invalid = true;
8007 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008008 }
8009 }
8010
8011 if (Invalid) {
8012 CopyAssignOperator->setInvalidDecl();
8013 return;
8014 }
8015
John McCall60d7b3a2010-08-24 06:29:42 +00008016 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008017 /*isStmtExpr=*/false);
8018 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8019 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008020
8021 if (ASTMutationListener *L = getASTMutationListener()) {
8022 L->CompletedImplicitDefinition(CopyAssignOperator);
8023 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008024}
8025
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008026Sema::ImplicitExceptionSpecification
8027Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8028 ImplicitExceptionSpecification ExceptSpec(Context);
8029
8030 if (ClassDecl->isInvalidDecl())
8031 return ExceptSpec;
8032
8033 // C++0x [except.spec]p14:
8034 // An implicitly declared special member function (Clause 12) shall have an
8035 // exception-specification. [...]
8036
8037 // It is unspecified whether or not an implicit move assignment operator
8038 // attempts to deduplicate calls to assignment operators of virtual bases are
8039 // made. As such, this exception specification is effectively unspecified.
8040 // Based on a similar decision made for constness in C++0x, we're erring on
8041 // the side of assuming such calls to be made regardless of whether they
8042 // actually happen.
8043 // Note that a move constructor is not implicitly declared when there are
8044 // virtual bases, but it can still be user-declared and explicitly defaulted.
8045 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8046 BaseEnd = ClassDecl->bases_end();
8047 Base != BaseEnd; ++Base) {
8048 if (Base->isVirtual())
8049 continue;
8050
8051 CXXRecordDecl *BaseClassDecl
8052 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8053 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8054 false, 0))
8055 ExceptSpec.CalledDecl(MoveAssign);
8056 }
8057
8058 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8059 BaseEnd = ClassDecl->vbases_end();
8060 Base != BaseEnd; ++Base) {
8061 CXXRecordDecl *BaseClassDecl
8062 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8063 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8064 false, 0))
8065 ExceptSpec.CalledDecl(MoveAssign);
8066 }
8067
8068 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8069 FieldEnd = ClassDecl->field_end();
8070 Field != FieldEnd;
8071 ++Field) {
8072 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8073 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8074 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8075 false, 0))
8076 ExceptSpec.CalledDecl(MoveAssign);
8077 }
8078 }
8079
8080 return ExceptSpec;
8081}
8082
8083CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8084 // Note: The following rules are largely analoguous to the move
8085 // constructor rules.
8086
8087 ImplicitExceptionSpecification Spec(
8088 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8089
8090 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8091 QualType RetType = Context.getLValueReferenceType(ArgType);
8092 ArgType = Context.getRValueReferenceType(ArgType);
8093
8094 // An implicitly-declared move assignment operator is an inline public
8095 // member of its class.
8096 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8097 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8098 SourceLocation ClassLoc = ClassDecl->getLocation();
8099 DeclarationNameInfo NameInfo(Name, ClassLoc);
8100 CXXMethodDecl *MoveAssignment
8101 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8102 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8103 /*TInfo=*/0, /*isStatic=*/false,
8104 /*StorageClassAsWritten=*/SC_None,
8105 /*isInline=*/true,
8106 /*isConstexpr=*/false,
8107 SourceLocation());
8108 MoveAssignment->setAccess(AS_public);
8109 MoveAssignment->setDefaulted();
8110 MoveAssignment->setImplicit();
8111 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8112
8113 // Add the parameter to the operator.
8114 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8115 ClassLoc, ClassLoc, /*Id=*/0,
8116 ArgType, /*TInfo=*/0,
8117 SC_None,
8118 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008119 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008120
8121 // Note that we have added this copy-assignment operator.
8122 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8123
8124 // C++0x [class.copy]p9:
8125 // If the definition of a class X does not explicitly declare a move
8126 // assignment operator, one will be implicitly declared as defaulted if and
8127 // only if:
8128 // [...]
8129 // - the move assignment operator would not be implicitly defined as
8130 // deleted.
8131 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8132 // Cache this result so that we don't try to generate this over and over
8133 // on every lookup, leaking memory and wasting time.
8134 ClassDecl->setFailedImplicitMoveAssignment();
8135 return 0;
8136 }
8137
8138 if (Scope *S = getScopeForContext(ClassDecl))
8139 PushOnScopeChains(MoveAssignment, S, false);
8140 ClassDecl->addDecl(MoveAssignment);
8141
8142 AddOverriddenMethods(ClassDecl, MoveAssignment);
8143 return MoveAssignment;
8144}
8145
8146void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8147 CXXMethodDecl *MoveAssignOperator) {
8148 assert((MoveAssignOperator->isDefaulted() &&
8149 MoveAssignOperator->isOverloadedOperator() &&
8150 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8151 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8152 "DefineImplicitMoveAssignment called for wrong function");
8153
8154 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8155
8156 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8157 MoveAssignOperator->setInvalidDecl();
8158 return;
8159 }
8160
8161 MoveAssignOperator->setUsed();
8162
8163 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8164 DiagnosticErrorTrap Trap(Diags);
8165
8166 // C++0x [class.copy]p28:
8167 // The implicitly-defined or move assignment operator for a non-union class
8168 // X performs memberwise move assignment of its subobjects. The direct base
8169 // classes of X are assigned first, in the order of their declaration in the
8170 // base-specifier-list, and then the immediate non-static data members of X
8171 // are assigned, in the order in which they were declared in the class
8172 // definition.
8173
8174 // The statements that form the synthesized function body.
8175 ASTOwningVector<Stmt*> Statements(*this);
8176
8177 // The parameter for the "other" object, which we are move from.
8178 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8179 QualType OtherRefType = Other->getType()->
8180 getAs<RValueReferenceType>()->getPointeeType();
8181 assert(OtherRefType.getQualifiers() == 0 &&
8182 "Bad argument type of defaulted move assignment");
8183
8184 // Our location for everything implicitly-generated.
8185 SourceLocation Loc = MoveAssignOperator->getLocation();
8186
8187 // Construct a reference to the "other" object. We'll be using this
8188 // throughout the generated ASTs.
8189 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8190 assert(OtherRef && "Reference to parameter cannot fail!");
8191 // Cast to rvalue.
8192 OtherRef = CastForMoving(*this, OtherRef);
8193
8194 // Construct the "this" pointer. We'll be using this throughout the generated
8195 // ASTs.
8196 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8197 assert(This && "Reference to this cannot fail!");
8198
8199 // Assign base classes.
8200 bool Invalid = false;
8201 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8202 E = ClassDecl->bases_end(); Base != E; ++Base) {
8203 // Form the assignment:
8204 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8205 QualType BaseType = Base->getType().getUnqualifiedType();
8206 if (!BaseType->isRecordType()) {
8207 Invalid = true;
8208 continue;
8209 }
8210
8211 CXXCastPath BasePath;
8212 BasePath.push_back(Base);
8213
8214 // Construct the "from" expression, which is an implicit cast to the
8215 // appropriately-qualified base type.
8216 Expr *From = OtherRef;
8217 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008218 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008219
8220 // Dereference "this".
8221 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8222
8223 // Implicitly cast "this" to the appropriately-qualified base type.
8224 To = ImpCastExprToType(To.take(),
8225 Context.getCVRQualifiedType(BaseType,
8226 MoveAssignOperator->getTypeQualifiers()),
8227 CK_UncheckedDerivedToBase,
8228 VK_LValue, &BasePath);
8229
8230 // Build the move.
8231 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8232 To.get(), From,
8233 /*CopyingBaseSubobject=*/true,
8234 /*Copying=*/false);
8235 if (Move.isInvalid()) {
8236 Diag(CurrentLocation, diag::note_member_synthesized_at)
8237 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8238 MoveAssignOperator->setInvalidDecl();
8239 return;
8240 }
8241
8242 // Success! Record the move.
8243 Statements.push_back(Move.takeAs<Expr>());
8244 }
8245
8246 // \brief Reference to the __builtin_memcpy function.
8247 Expr *BuiltinMemCpyRef = 0;
8248 // \brief Reference to the __builtin_objc_memmove_collectable function.
8249 Expr *CollectableMemCpyRef = 0;
8250
8251 // Assign non-static members.
8252 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8253 FieldEnd = ClassDecl->field_end();
8254 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008255 if (Field->isUnnamedBitfield())
8256 continue;
8257
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008258 // Check for members of reference type; we can't move those.
8259 if (Field->getType()->isReferenceType()) {
8260 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8261 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8262 Diag(Field->getLocation(), diag::note_declared_at);
8263 Diag(CurrentLocation, diag::note_member_synthesized_at)
8264 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8265 Invalid = true;
8266 continue;
8267 }
8268
8269 // Check for members of const-qualified, non-class type.
8270 QualType BaseType = Context.getBaseElementType(Field->getType());
8271 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8272 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8273 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8274 Diag(Field->getLocation(), diag::note_declared_at);
8275 Diag(CurrentLocation, diag::note_member_synthesized_at)
8276 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8277 Invalid = true;
8278 continue;
8279 }
8280
8281 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008282 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8283 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008284
8285 QualType FieldType = Field->getType().getNonReferenceType();
8286 if (FieldType->isIncompleteArrayType()) {
8287 assert(ClassDecl->hasFlexibleArrayMember() &&
8288 "Incomplete array type is not valid");
8289 continue;
8290 }
8291
8292 // Build references to the field in the object we're copying from and to.
8293 CXXScopeSpec SS; // Intentionally empty
8294 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8295 LookupMemberName);
8296 MemberLookup.addDecl(*Field);
8297 MemberLookup.resolveKind();
8298 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8299 Loc, /*IsArrow=*/false,
8300 SS, 0, MemberLookup, 0);
8301 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8302 Loc, /*IsArrow=*/true,
8303 SS, 0, MemberLookup, 0);
8304 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8305 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8306
8307 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8308 "Member reference with rvalue base must be rvalue except for reference "
8309 "members, which aren't allowed for move assignment.");
8310
8311 // If the field should be copied with __builtin_memcpy rather than via
8312 // explicit assignments, do so. This optimization only applies for arrays
8313 // of scalars and arrays of class type with trivial move-assignment
8314 // operators.
8315 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8316 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8317 // Compute the size of the memory buffer to be copied.
8318 QualType SizeType = Context.getSizeType();
8319 llvm::APInt Size(Context.getTypeSize(SizeType),
8320 Context.getTypeSizeInChars(BaseType).getQuantity());
8321 for (const ConstantArrayType *Array
8322 = Context.getAsConstantArrayType(FieldType);
8323 Array;
8324 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8325 llvm::APInt ArraySize
8326 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8327 Size *= ArraySize;
8328 }
8329
Douglas Gregor45d3d712011-09-01 02:09:07 +00008330 // Take the address of the field references for "from" and "to". We
8331 // directly construct UnaryOperators here because semantic analysis
8332 // does not permit us to take the address of an xvalue.
8333 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8334 Context.getPointerType(From.get()->getType()),
8335 VK_RValue, OK_Ordinary, Loc);
8336 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8337 Context.getPointerType(To.get()->getType()),
8338 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008339
8340 bool NeedsCollectableMemCpy =
8341 (BaseType->isRecordType() &&
8342 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8343
8344 if (NeedsCollectableMemCpy) {
8345 if (!CollectableMemCpyRef) {
8346 // Create a reference to the __builtin_objc_memmove_collectable function.
8347 LookupResult R(*this,
8348 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8349 Loc, LookupOrdinaryName);
8350 LookupName(R, TUScope, true);
8351
8352 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8353 if (!CollectableMemCpy) {
8354 // Something went horribly wrong earlier, and we will have
8355 // complained about it.
8356 Invalid = true;
8357 continue;
8358 }
8359
8360 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8361 CollectableMemCpy->getType(),
8362 VK_LValue, Loc, 0).take();
8363 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8364 }
8365 }
8366 // Create a reference to the __builtin_memcpy builtin function.
8367 else if (!BuiltinMemCpyRef) {
8368 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8369 LookupOrdinaryName);
8370 LookupName(R, TUScope, true);
8371
8372 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8373 if (!BuiltinMemCpy) {
8374 // Something went horribly wrong earlier, and we will have complained
8375 // about it.
8376 Invalid = true;
8377 continue;
8378 }
8379
8380 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8381 BuiltinMemCpy->getType(),
8382 VK_LValue, Loc, 0).take();
8383 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8384 }
8385
8386 ASTOwningVector<Expr*> CallArgs(*this);
8387 CallArgs.push_back(To.takeAs<Expr>());
8388 CallArgs.push_back(From.takeAs<Expr>());
8389 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8390 ExprResult Call = ExprError();
8391 if (NeedsCollectableMemCpy)
8392 Call = ActOnCallExpr(/*Scope=*/0,
8393 CollectableMemCpyRef,
8394 Loc, move_arg(CallArgs),
8395 Loc);
8396 else
8397 Call = ActOnCallExpr(/*Scope=*/0,
8398 BuiltinMemCpyRef,
8399 Loc, move_arg(CallArgs),
8400 Loc);
8401
8402 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8403 Statements.push_back(Call.takeAs<Expr>());
8404 continue;
8405 }
8406
8407 // Build the move of this field.
8408 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8409 To.get(), From.get(),
8410 /*CopyingBaseSubobject=*/false,
8411 /*Copying=*/false);
8412 if (Move.isInvalid()) {
8413 Diag(CurrentLocation, diag::note_member_synthesized_at)
8414 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8415 MoveAssignOperator->setInvalidDecl();
8416 return;
8417 }
8418
8419 // Success! Record the copy.
8420 Statements.push_back(Move.takeAs<Stmt>());
8421 }
8422
8423 if (!Invalid) {
8424 // Add a "return *this;"
8425 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8426
8427 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8428 if (Return.isInvalid())
8429 Invalid = true;
8430 else {
8431 Statements.push_back(Return.takeAs<Stmt>());
8432
8433 if (Trap.hasErrorOccurred()) {
8434 Diag(CurrentLocation, diag::note_member_synthesized_at)
8435 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8436 Invalid = true;
8437 }
8438 }
8439 }
8440
8441 if (Invalid) {
8442 MoveAssignOperator->setInvalidDecl();
8443 return;
8444 }
8445
8446 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8447 /*isStmtExpr=*/false);
8448 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8449 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8450
8451 if (ASTMutationListener *L = getASTMutationListener()) {
8452 L->CompletedImplicitDefinition(MoveAssignOperator);
8453 }
8454}
8455
Sean Hunt49634cf2011-05-13 06:10:58 +00008456std::pair<Sema::ImplicitExceptionSpecification, bool>
8457Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008458 if (ClassDecl->isInvalidDecl())
8459 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8460
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008461 // C++ [class.copy]p5:
8462 // The implicitly-declared copy constructor for a class X will
8463 // have the form
8464 //
8465 // X::X(const X&)
8466 //
8467 // if
Sean Huntc530d172011-06-10 04:44:37 +00008468 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008469 bool HasConstCopyConstructor = true;
8470
8471 // -- each direct or virtual base class B of X has a copy
8472 // constructor whose first parameter is of type const B& or
8473 // const volatile B&, and
8474 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8475 BaseEnd = ClassDecl->bases_end();
8476 HasConstCopyConstructor && Base != BaseEnd;
8477 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008478 // Virtual bases are handled below.
8479 if (Base->isVirtual())
8480 continue;
8481
Douglas Gregor22584312010-07-02 23:41:54 +00008482 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008483 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008484 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8485 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008486 }
8487
8488 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8489 BaseEnd = ClassDecl->vbases_end();
8490 HasConstCopyConstructor && Base != BaseEnd;
8491 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008492 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008493 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008494 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8495 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008496 }
8497
8498 // -- for all the nonstatic data members of X that are of a
8499 // class type M (or array thereof), each such class type
8500 // has a copy constructor whose first parameter is of type
8501 // const M& or const volatile M&.
8502 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8503 FieldEnd = ClassDecl->field_end();
8504 HasConstCopyConstructor && Field != FieldEnd;
8505 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008506 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008507 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008508 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8509 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008510 }
8511 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008512 // Otherwise, the implicitly declared copy constructor will have
8513 // the form
8514 //
8515 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008516
Douglas Gregor0d405db2010-07-01 20:59:04 +00008517 // C++ [except.spec]p14:
8518 // An implicitly declared special member function (Clause 12) shall have an
8519 // exception-specification. [...]
8520 ImplicitExceptionSpecification ExceptSpec(Context);
8521 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8522 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8523 BaseEnd = ClassDecl->bases_end();
8524 Base != BaseEnd;
8525 ++Base) {
8526 // Virtual bases are handled below.
8527 if (Base->isVirtual())
8528 continue;
8529
Douglas Gregor22584312010-07-02 23:41:54 +00008530 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008531 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008532 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008533 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008534 ExceptSpec.CalledDecl(CopyConstructor);
8535 }
8536 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8537 BaseEnd = ClassDecl->vbases_end();
8538 Base != BaseEnd;
8539 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008540 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008541 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008542 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008543 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008544 ExceptSpec.CalledDecl(CopyConstructor);
8545 }
8546 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8547 FieldEnd = ClassDecl->field_end();
8548 Field != FieldEnd;
8549 ++Field) {
8550 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008551 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8552 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008553 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008554 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008555 }
8556 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008557
Sean Hunt49634cf2011-05-13 06:10:58 +00008558 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8559}
8560
8561CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8562 CXXRecordDecl *ClassDecl) {
8563 // C++ [class.copy]p4:
8564 // If the class definition does not explicitly declare a copy
8565 // constructor, one is declared implicitly.
8566
8567 ImplicitExceptionSpecification Spec(Context);
8568 bool Const;
8569 llvm::tie(Spec, Const) =
8570 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8571
8572 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8573 QualType ArgType = ClassType;
8574 if (Const)
8575 ArgType = ArgType.withConst();
8576 ArgType = Context.getLValueReferenceType(ArgType);
8577
8578 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8579
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008580 DeclarationName Name
8581 = Context.DeclarationNames.getCXXConstructorName(
8582 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008583 SourceLocation ClassLoc = ClassDecl->getLocation();
8584 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008585
8586 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008587 // member of its class.
8588 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8589 Context, ClassDecl, ClassLoc, NameInfo,
8590 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8591 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8592 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8593 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008594 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008595 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008596 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008597
Douglas Gregor22584312010-07-02 23:41:54 +00008598 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008599 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8600
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008601 // Add the parameter to the constructor.
8602 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008603 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008604 /*IdentifierInfo=*/0,
8605 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008606 SC_None,
8607 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008608 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008609
Douglas Gregor23c94db2010-07-02 17:43:08 +00008610 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008611 PushOnScopeChains(CopyConstructor, S, false);
8612 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008613
Sean Hunt1ccbc542011-06-22 01:05:13 +00008614 // C++0x [class.copy]p7:
8615 // ... If the class definition declares a move constructor or move
8616 // assignment operator, the implicitly declared constructor is defined as
8617 // deleted; ...
8618 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8619 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Huntc32d6842011-10-11 04:55:36 +00008620 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008621 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008622
8623 return CopyConstructor;
8624}
8625
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008626void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008627 CXXConstructorDecl *CopyConstructor) {
8628 assert((CopyConstructor->isDefaulted() &&
8629 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008630 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008631 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008632
Anders Carlsson63010a72010-04-23 16:24:12 +00008633 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008634 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008635
Douglas Gregor39957dc2010-05-01 15:04:51 +00008636 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008637 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008638
Sean Huntcbb67482011-01-08 20:30:50 +00008639 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008640 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008641 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008642 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008643 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008644 } else {
8645 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8646 CopyConstructor->getLocation(),
8647 MultiStmtArg(*this, 0, 0),
8648 /*isStmtExpr=*/false)
8649 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008650 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008651 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008652
8653 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008654 if (ASTMutationListener *L = getASTMutationListener()) {
8655 L->CompletedImplicitDefinition(CopyConstructor);
8656 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008657}
8658
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008659Sema::ImplicitExceptionSpecification
8660Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8661 // C++ [except.spec]p14:
8662 // An implicitly declared special member function (Clause 12) shall have an
8663 // exception-specification. [...]
8664 ImplicitExceptionSpecification ExceptSpec(Context);
8665 if (ClassDecl->isInvalidDecl())
8666 return ExceptSpec;
8667
8668 // Direct base-class constructors.
8669 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8670 BEnd = ClassDecl->bases_end();
8671 B != BEnd; ++B) {
8672 if (B->isVirtual()) // Handled below.
8673 continue;
8674
8675 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8676 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8677 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8678 // If this is a deleted function, add it anyway. This might be conformant
8679 // with the standard. This might not. I'm not sure. It might not matter.
8680 if (Constructor)
8681 ExceptSpec.CalledDecl(Constructor);
8682 }
8683 }
8684
8685 // Virtual base-class constructors.
8686 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8687 BEnd = ClassDecl->vbases_end();
8688 B != BEnd; ++B) {
8689 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8690 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8691 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8692 // If this is a deleted function, add it anyway. This might be conformant
8693 // with the standard. This might not. I'm not sure. It might not matter.
8694 if (Constructor)
8695 ExceptSpec.CalledDecl(Constructor);
8696 }
8697 }
8698
8699 // Field constructors.
8700 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8701 FEnd = ClassDecl->field_end();
8702 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008703 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008704 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8705 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8706 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8707 // If this is a deleted function, add it anyway. This might be conformant
8708 // with the standard. This might not. I'm not sure. It might not matter.
8709 // In particular, the problem is that this function never gets called. It
8710 // might just be ill-formed because this function attempts to refer to
8711 // a deleted function here.
8712 if (Constructor)
8713 ExceptSpec.CalledDecl(Constructor);
8714 }
8715 }
8716
8717 return ExceptSpec;
8718}
8719
8720CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8721 CXXRecordDecl *ClassDecl) {
8722 ImplicitExceptionSpecification Spec(
8723 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8724
8725 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8726 QualType ArgType = Context.getRValueReferenceType(ClassType);
8727
8728 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8729
8730 DeclarationName Name
8731 = Context.DeclarationNames.getCXXConstructorName(
8732 Context.getCanonicalType(ClassType));
8733 SourceLocation ClassLoc = ClassDecl->getLocation();
8734 DeclarationNameInfo NameInfo(Name, ClassLoc);
8735
8736 // C++0x [class.copy]p11:
8737 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008738 // member of its class.
8739 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8740 Context, ClassDecl, ClassLoc, NameInfo,
8741 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8742 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8743 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8744 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008745 MoveConstructor->setAccess(AS_public);
8746 MoveConstructor->setDefaulted();
8747 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008748
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008749 // Add the parameter to the constructor.
8750 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8751 ClassLoc, ClassLoc,
8752 /*IdentifierInfo=*/0,
8753 ArgType, /*TInfo=*/0,
8754 SC_None,
8755 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008756 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008757
8758 // C++0x [class.copy]p9:
8759 // If the definition of a class X does not explicitly declare a move
8760 // constructor, one will be implicitly declared as defaulted if and only if:
8761 // [...]
8762 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008763 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008764 // Cache this result so that we don't try to generate this over and over
8765 // on every lookup, leaking memory and wasting time.
8766 ClassDecl->setFailedImplicitMoveConstructor();
8767 return 0;
8768 }
8769
8770 // Note that we have declared this constructor.
8771 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8772
8773 if (Scope *S = getScopeForContext(ClassDecl))
8774 PushOnScopeChains(MoveConstructor, S, false);
8775 ClassDecl->addDecl(MoveConstructor);
8776
8777 return MoveConstructor;
8778}
8779
8780void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8781 CXXConstructorDecl *MoveConstructor) {
8782 assert((MoveConstructor->isDefaulted() &&
8783 MoveConstructor->isMoveConstructor() &&
8784 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8785 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8786
8787 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8788 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8789
8790 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8791 DiagnosticErrorTrap Trap(Diags);
8792
8793 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8794 Trap.hasErrorOccurred()) {
8795 Diag(CurrentLocation, diag::note_member_synthesized_at)
8796 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8797 MoveConstructor->setInvalidDecl();
8798 } else {
8799 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8800 MoveConstructor->getLocation(),
8801 MultiStmtArg(*this, 0, 0),
8802 /*isStmtExpr=*/false)
8803 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008804 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008805 }
8806
8807 MoveConstructor->setUsed();
8808
8809 if (ASTMutationListener *L = getASTMutationListener()) {
8810 L->CompletedImplicitDefinition(MoveConstructor);
8811 }
8812}
8813
John McCall60d7b3a2010-08-24 06:29:42 +00008814ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008815Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008816 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008817 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008818 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008819 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008820 unsigned ConstructKind,
8821 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008822 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008823
Douglas Gregor2f599792010-04-02 18:24:57 +00008824 // C++0x [class.copy]p34:
8825 // When certain criteria are met, an implementation is allowed to
8826 // omit the copy/move construction of a class object, even if the
8827 // copy/move constructor and/or destructor for the object have
8828 // side effects. [...]
8829 // - when a temporary class object that has not been bound to a
8830 // reference (12.2) would be copied/moved to a class object
8831 // with the same cv-unqualified type, the copy/move operation
8832 // can be omitted by constructing the temporary object
8833 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008834 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008835 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008836 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008837 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008838 }
Mike Stump1eb44332009-09-09 15:08:12 +00008839
8840 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008841 Elidable, move(ExprArgs), HadMultipleCandidates,
8842 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008843}
8844
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008845/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8846/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008847ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008848Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8849 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008850 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008851 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008852 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008853 unsigned ConstructKind,
8854 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008855 unsigned NumExprs = ExprArgs.size();
8856 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008857
Nick Lewycky909a70d2011-03-25 01:44:32 +00008858 for (specific_attr_iterator<NonNullAttr>
8859 i = Constructor->specific_attr_begin<NonNullAttr>(),
8860 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8861 const NonNullAttr *NonNull = *i;
8862 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8863 }
8864
Douglas Gregor7edfb692009-11-23 12:27:39 +00008865 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008866 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008867 Constructor, Elidable, Exprs, NumExprs,
8868 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008869 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8870 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008871}
8872
Mike Stump1eb44332009-09-09 15:08:12 +00008873bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008874 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008875 MultiExprArg Exprs,
8876 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008877 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008878 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008879 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008880 move(Exprs), HadMultipleCandidates, false,
8881 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008882 if (TempResult.isInvalid())
8883 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008884
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008885 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008886 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008887 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008888 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008889 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008890
Anders Carlssonfe2de492009-08-25 05:18:00 +00008891 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00008892}
8893
John McCall68c6c9a2010-02-02 09:10:11 +00008894void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008895 if (VD->isInvalidDecl()) return;
8896
John McCall68c6c9a2010-02-02 09:10:11 +00008897 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008898 if (ClassDecl->isInvalidDecl()) return;
8899 if (ClassDecl->hasTrivialDestructor()) return;
8900 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00008901
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008902 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8903 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8904 CheckDestructorAccess(VD->getLocation(), Destructor,
8905 PDiag(diag::err_access_dtor_var)
8906 << VD->getDeclName()
8907 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00008908
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00008909 if (!VD->hasGlobalStorage()) return;
8910
8911 // Emit warning for non-trivial dtor in global scope (a real global,
8912 // class-static, function-static).
8913 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8914
8915 // TODO: this should be re-enabled for static locals by !CXAAtExit
8916 if (!VD->isStaticLocal())
8917 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008918}
8919
Mike Stump1eb44332009-09-09 15:08:12 +00008920/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008921/// ActOnDeclarator, when a C++ direct initializer is present.
8922/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00008923void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00008924 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008925 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00008926 SourceLocation RParenLoc,
8927 bool TypeMayContainAuto) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008928 // If there is no declaration, there was an error parsing it. Just ignore
8929 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00008930 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008931 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008932
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008933 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8934 if (!VDecl) {
8935 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8936 RealDecl->setInvalidDecl();
8937 return;
8938 }
8939
Eli Friedman6aeaa602012-01-05 22:34:08 +00008940 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00008941 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedman6aeaa602012-01-05 22:34:08 +00008942 if (Exprs.size() == 0) {
8943 // It isn't possible to write this directly, but it is possible to
8944 // end up in this situation with "auto x(some_pack...);"
8945 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
8946 << VDecl->getDeclName() << VDecl->getType()
8947 << VDecl->getSourceRange();
8948 RealDecl->setInvalidDecl();
8949 return;
8950 }
8951
Richard Smith34b41d92011-02-20 03:19:35 +00008952 if (Exprs.size() > 1) {
8953 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8954 diag::err_auto_var_init_multiple_expressions)
8955 << VDecl->getDeclName() << VDecl->getType()
8956 << VDecl->getSourceRange();
8957 RealDecl->setInvalidDecl();
8958 return;
8959 }
8960
8961 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00008962 TypeSourceInfo *DeducedType = 0;
8963 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00008964 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8965 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8966 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00008967 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00008968 RealDecl->setInvalidDecl();
8969 return;
8970 }
Richard Smitha085da82011-03-17 16:11:59 +00008971 VDecl->setTypeSourceInfo(DeducedType);
8972 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00008973
John McCallf85e1932011-06-15 23:02:42 +00008974 // In ARC, infer lifetime.
8975 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8976 VDecl->setInvalidDecl();
8977
Richard Smith34b41d92011-02-20 03:19:35 +00008978 // If this is a redeclaration, check that the type we just deduced matches
8979 // the previously declared type.
Douglas Gregoref96ee02012-01-14 16:38:05 +00008980 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith34b41d92011-02-20 03:19:35 +00008981 MergeVarDeclTypes(VDecl, Old);
8982 }
8983
Douglas Gregor83ddad32009-08-26 21:14:46 +00008984 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00008985 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008986 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8987 //
8988 // Clients that want to distinguish between the two forms, can check for
8989 // direct initializer using VarDecl::hasCXXDirectInitializer().
8990 // A major benefit is that clients that don't particularly care about which
8991 // exactly form was it (like the CodeGen) can handle both cases without
8992 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008993
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00008994 // C++ 8.5p11:
8995 // The form of initialization (using parentheses or '=') is generally
8996 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00008997 // class type.
8998
Douglas Gregor4dffad62010-02-11 22:55:30 +00008999 if (!VDecl->getType()->isDependentType() &&
Douglas Gregord24c3062011-10-10 16:05:18 +00009000 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor4dffad62010-02-11 22:55:30 +00009001 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00009002 diag::err_typecheck_decl_incomplete_type)) {
9003 VDecl->setInvalidDecl();
9004 return;
9005 }
9006
Douglas Gregor90f93822009-12-22 22:17:25 +00009007 // The variable can not have an abstract class type.
9008 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9009 diag::err_abstract_type_in_decl,
9010 AbstractVariableType))
9011 VDecl->setInvalidDecl();
9012
Sebastian Redl31310a22010-02-01 20:16:42 +00009013 const VarDecl *Def;
9014 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009015 Diag(VDecl->getLocation(), diag::err_redefinition)
9016 << VDecl->getDeclName();
9017 Diag(Def->getLocation(), diag::note_previous_definition);
9018 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009019 return;
9020 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009021
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009022 // C++ [class.static.data]p4
9023 // If a static data member is of const integral or const
9024 // enumeration type, its declaration in the class definition can
9025 // specify a constant-initializer which shall be an integral
9026 // constant expression (5.19). In that case, the member can appear
9027 // in integral constant expressions. The member shall still be
9028 // defined in a namespace scope if it is used in the program and the
9029 // namespace scope definition shall not contain an initializer.
9030 //
9031 // We already performed a redefinition check above, but for static
9032 // data members we also need to check whether there was an in-class
9033 // declaration with an initializer.
9034 const VarDecl* PrevInit = 0;
9035 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9036 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9037 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9038 return;
9039 }
9040
Douglas Gregora31040f2010-12-16 01:31:22 +00009041 bool IsDependent = false;
9042 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9043 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9044 VDecl->setInvalidDecl();
9045 return;
9046 }
9047
9048 if (Exprs.get()[I]->isTypeDependent())
9049 IsDependent = true;
9050 }
9051
Douglas Gregor4dffad62010-02-11 22:55:30 +00009052 // If either the declaration has a dependent type or if any of the
9053 // expressions is type-dependent, we represent the initialization
9054 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009055 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009056 // Let clients know that initialization was done with a direct initializer.
9057 VDecl->setCXXDirectInitializer(true);
9058
9059 // Store the initialization expressions as a ParenListExpr.
9060 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009061 VDecl->setInit(new (Context) ParenListExpr(
9062 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9063 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009064 return;
9065 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009066
9067 // Capture the variable that is being initialized and the style of
9068 // initialization.
9069 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9070
9071 // FIXME: Poor source location information.
9072 InitializationKind Kind
9073 = InitializationKind::CreateDirect(VDecl->getLocation(),
9074 LParenLoc, RParenLoc);
9075
Douglas Gregord24c3062011-10-10 16:05:18 +00009076 QualType T = VDecl->getType();
Douglas Gregor90f93822009-12-22 22:17:25 +00009077 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009078 Exprs.get(), Exprs.size());
Douglas Gregord24c3062011-10-10 16:05:18 +00009079 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregor90f93822009-12-22 22:17:25 +00009080 if (Result.isInvalid()) {
9081 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009082 return;
Douglas Gregord24c3062011-10-10 16:05:18 +00009083 } else if (T != VDecl->getType()) {
9084 VDecl->setType(T);
9085 Result.get()->setType(T);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009086 }
John McCallb4eb64d2010-10-08 02:01:28 +00009087
Douglas Gregord24c3062011-10-10 16:05:18 +00009088
Richard Smithc6d990a2011-09-29 19:11:37 +00009089 Expr *Init = Result.get();
9090 CheckImplicitConversions(Init, LParenLoc);
Richard Smithc6d990a2011-09-29 19:11:37 +00009091
9092 Init = MaybeCreateExprWithCleanups(Init);
9093 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009094 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009095
John McCall2998d6b2011-01-19 11:48:09 +00009096 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009097}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009098
Douglas Gregor39da0b82009-09-09 23:08:42 +00009099/// \brief Given a constructor and the set of arguments provided for the
9100/// constructor, convert the arguments and add any required default arguments
9101/// to form a proper call to this constructor.
9102///
9103/// \returns true if an error occurred, false otherwise.
9104bool
9105Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9106 MultiExprArg ArgsPtr,
9107 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009108 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009109 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9110 unsigned NumArgs = ArgsPtr.size();
9111 Expr **Args = (Expr **)ArgsPtr.get();
9112
9113 const FunctionProtoType *Proto
9114 = Constructor->getType()->getAs<FunctionProtoType>();
9115 assert(Proto && "Constructor without a prototype?");
9116 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009117
9118 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009119 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009120 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009121 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009122 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009123
9124 VariadicCallType CallType =
9125 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009126 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009127 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9128 Proto, 0, Args, NumArgs, AllArgs,
9129 CallType);
9130 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9131 ConvertedArgs.push_back(AllArgs[i]);
9132 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009133}
9134
Anders Carlsson20d45d22009-12-12 00:32:00 +00009135static inline bool
9136CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9137 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009138 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009139 if (isa<NamespaceDecl>(DC)) {
9140 return SemaRef.Diag(FnDecl->getLocation(),
9141 diag::err_operator_new_delete_declared_in_namespace)
9142 << FnDecl->getDeclName();
9143 }
9144
9145 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009146 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009147 return SemaRef.Diag(FnDecl->getLocation(),
9148 diag::err_operator_new_delete_declared_static)
9149 << FnDecl->getDeclName();
9150 }
9151
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009152 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009153}
9154
Anders Carlsson156c78e2009-12-13 17:53:43 +00009155static inline bool
9156CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9157 CanQualType ExpectedResultType,
9158 CanQualType ExpectedFirstParamType,
9159 unsigned DependentParamTypeDiag,
9160 unsigned InvalidParamTypeDiag) {
9161 QualType ResultType =
9162 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9163
9164 // Check that the result type is not dependent.
9165 if (ResultType->isDependentType())
9166 return SemaRef.Diag(FnDecl->getLocation(),
9167 diag::err_operator_new_delete_dependent_result_type)
9168 << FnDecl->getDeclName() << ExpectedResultType;
9169
9170 // Check that the result type is what we expect.
9171 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9172 return SemaRef.Diag(FnDecl->getLocation(),
9173 diag::err_operator_new_delete_invalid_result_type)
9174 << FnDecl->getDeclName() << ExpectedResultType;
9175
9176 // A function template must have at least 2 parameters.
9177 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9178 return SemaRef.Diag(FnDecl->getLocation(),
9179 diag::err_operator_new_delete_template_too_few_parameters)
9180 << FnDecl->getDeclName();
9181
9182 // The function decl must have at least 1 parameter.
9183 if (FnDecl->getNumParams() == 0)
9184 return SemaRef.Diag(FnDecl->getLocation(),
9185 diag::err_operator_new_delete_too_few_parameters)
9186 << FnDecl->getDeclName();
9187
9188 // Check the the first parameter type is not dependent.
9189 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9190 if (FirstParamType->isDependentType())
9191 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9192 << FnDecl->getDeclName() << ExpectedFirstParamType;
9193
9194 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009195 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009196 ExpectedFirstParamType)
9197 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9198 << FnDecl->getDeclName() << ExpectedFirstParamType;
9199
9200 return false;
9201}
9202
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009203static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009204CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009205 // C++ [basic.stc.dynamic.allocation]p1:
9206 // A program is ill-formed if an allocation function is declared in a
9207 // namespace scope other than global scope or declared static in global
9208 // scope.
9209 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9210 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009211
9212 CanQualType SizeTy =
9213 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9214
9215 // C++ [basic.stc.dynamic.allocation]p1:
9216 // The return type shall be void*. The first parameter shall have type
9217 // std::size_t.
9218 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9219 SizeTy,
9220 diag::err_operator_new_dependent_param_type,
9221 diag::err_operator_new_param_type))
9222 return true;
9223
9224 // C++ [basic.stc.dynamic.allocation]p1:
9225 // The first parameter shall not have an associated default argument.
9226 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009227 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009228 diag::err_operator_new_default_arg)
9229 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9230
9231 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009232}
9233
9234static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009235CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9236 // C++ [basic.stc.dynamic.deallocation]p1:
9237 // A program is ill-formed if deallocation functions are declared in a
9238 // namespace scope other than global scope or declared static in global
9239 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009240 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9241 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009242
9243 // C++ [basic.stc.dynamic.deallocation]p2:
9244 // Each deallocation function shall return void and its first parameter
9245 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009246 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9247 SemaRef.Context.VoidPtrTy,
9248 diag::err_operator_delete_dependent_param_type,
9249 diag::err_operator_delete_param_type))
9250 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009251
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009252 return false;
9253}
9254
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009255/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9256/// of this overloaded operator is well-formed. If so, returns false;
9257/// otherwise, emits appropriate diagnostics and returns true.
9258bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009259 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009260 "Expected an overloaded operator declaration");
9261
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009262 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9263
Mike Stump1eb44332009-09-09 15:08:12 +00009264 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009265 // The allocation and deallocation functions, operator new,
9266 // operator new[], operator delete and operator delete[], are
9267 // described completely in 3.7.3. The attributes and restrictions
9268 // found in the rest of this subclause do not apply to them unless
9269 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009270 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009271 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009272
Anders Carlssona3ccda52009-12-12 00:26:23 +00009273 if (Op == OO_New || Op == OO_Array_New)
9274 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009275
9276 // C++ [over.oper]p6:
9277 // An operator function shall either be a non-static member
9278 // function or be a non-member function and have at least one
9279 // parameter whose type is a class, a reference to a class, an
9280 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009281 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9282 if (MethodDecl->isStatic())
9283 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009284 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009285 } else {
9286 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009287 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9288 ParamEnd = FnDecl->param_end();
9289 Param != ParamEnd; ++Param) {
9290 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009291 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9292 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009293 ClassOrEnumParam = true;
9294 break;
9295 }
9296 }
9297
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009298 if (!ClassOrEnumParam)
9299 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009300 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009301 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009302 }
9303
9304 // C++ [over.oper]p8:
9305 // An operator function cannot have default arguments (8.3.6),
9306 // except where explicitly stated below.
9307 //
Mike Stump1eb44332009-09-09 15:08:12 +00009308 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009309 // (C++ [over.call]p1).
9310 if (Op != OO_Call) {
9311 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9312 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009313 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009314 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009315 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009316 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009317 }
9318 }
9319
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009320 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9321 { false, false, false }
9322#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9323 , { Unary, Binary, MemberOnly }
9324#include "clang/Basic/OperatorKinds.def"
9325 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009326
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009327 bool CanBeUnaryOperator = OperatorUses[Op][0];
9328 bool CanBeBinaryOperator = OperatorUses[Op][1];
9329 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009330
9331 // C++ [over.oper]p8:
9332 // [...] Operator functions cannot have more or fewer parameters
9333 // than the number required for the corresponding operator, as
9334 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009335 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009336 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009337 if (Op != OO_Call &&
9338 ((NumParams == 1 && !CanBeUnaryOperator) ||
9339 (NumParams == 2 && !CanBeBinaryOperator) ||
9340 (NumParams < 1) || (NumParams > 2))) {
9341 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009342 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009343 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009344 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009345 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009346 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009347 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009348 assert(CanBeBinaryOperator &&
9349 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009350 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009351 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009352
Chris Lattner416e46f2008-11-21 07:57:12 +00009353 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009354 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009355 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009356
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009357 // Overloaded operators other than operator() cannot be variadic.
9358 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009359 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009360 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009361 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009362 }
9363
9364 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009365 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9366 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009367 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009368 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009369 }
9370
9371 // C++ [over.inc]p1:
9372 // The user-defined function called operator++ implements the
9373 // prefix and postfix ++ operator. If this function is a member
9374 // function with no parameters, or a non-member function with one
9375 // parameter of class or enumeration type, it defines the prefix
9376 // increment operator ++ for objects of that type. If the function
9377 // is a member function with one parameter (which shall be of type
9378 // int) or a non-member function with two parameters (the second
9379 // of which shall be of type int), it defines the postfix
9380 // increment operator ++ for objects of that type.
9381 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9382 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9383 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009384 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009385 ParamIsInt = BT->getKind() == BuiltinType::Int;
9386
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009387 if (!ParamIsInt)
9388 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009389 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009390 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009391 }
9392
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009393 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009394}
Chris Lattner5a003a42008-12-17 07:09:26 +00009395
Sean Hunta6c058d2010-01-13 09:01:02 +00009396/// CheckLiteralOperatorDeclaration - Check whether the declaration
9397/// of this literal operator function is well-formed. If so, returns
9398/// false; otherwise, emits appropriate diagnostics and returns true.
9399bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9400 DeclContext *DC = FnDecl->getDeclContext();
9401 Decl::Kind Kind = DC->getDeclKind();
9402 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9403 Kind != Decl::LinkageSpec) {
9404 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9405 << FnDecl->getDeclName();
9406 return true;
9407 }
9408
9409 bool Valid = false;
9410
Sean Hunt216c2782010-04-07 23:11:06 +00009411 // template <char...> type operator "" name() is the only valid template
9412 // signature, and the only valid signature with no parameters.
9413 if (FnDecl->param_size() == 0) {
9414 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9415 // Must have only one template parameter
9416 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9417 if (Params->size() == 1) {
9418 NonTypeTemplateParmDecl *PmDecl =
9419 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009420
Sean Hunt216c2782010-04-07 23:11:06 +00009421 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009422 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9423 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9424 Valid = true;
9425 }
9426 }
9427 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009428 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009429 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9430
Sean Hunta6c058d2010-01-13 09:01:02 +00009431 QualType T = (*Param)->getType();
9432
Sean Hunt30019c02010-04-07 22:57:35 +00009433 // unsigned long long int, long double, and any character type are allowed
9434 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009435 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9436 Context.hasSameType(T, Context.LongDoubleTy) ||
9437 Context.hasSameType(T, Context.CharTy) ||
9438 Context.hasSameType(T, Context.WCharTy) ||
9439 Context.hasSameType(T, Context.Char16Ty) ||
9440 Context.hasSameType(T, Context.Char32Ty)) {
9441 if (++Param == FnDecl->param_end())
9442 Valid = true;
9443 goto FinishedParams;
9444 }
9445
Sean Hunt30019c02010-04-07 22:57:35 +00009446 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009447 const PointerType *PT = T->getAs<PointerType>();
9448 if (!PT)
9449 goto FinishedParams;
9450 T = PT->getPointeeType();
9451 if (!T.isConstQualified())
9452 goto FinishedParams;
9453 T = T.getUnqualifiedType();
9454
9455 // Move on to the second parameter;
9456 ++Param;
9457
9458 // If there is no second parameter, the first must be a const char *
9459 if (Param == FnDecl->param_end()) {
9460 if (Context.hasSameType(T, Context.CharTy))
9461 Valid = true;
9462 goto FinishedParams;
9463 }
9464
9465 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9466 // are allowed as the first parameter to a two-parameter function
9467 if (!(Context.hasSameType(T, Context.CharTy) ||
9468 Context.hasSameType(T, Context.WCharTy) ||
9469 Context.hasSameType(T, Context.Char16Ty) ||
9470 Context.hasSameType(T, Context.Char32Ty)))
9471 goto FinishedParams;
9472
9473 // The second and final parameter must be an std::size_t
9474 T = (*Param)->getType().getUnqualifiedType();
9475 if (Context.hasSameType(T, Context.getSizeType()) &&
9476 ++Param == FnDecl->param_end())
9477 Valid = true;
9478 }
9479
9480 // FIXME: This diagnostic is absolutely terrible.
9481FinishedParams:
9482 if (!Valid) {
9483 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9484 << FnDecl->getDeclName();
9485 return true;
9486 }
9487
Douglas Gregor1155c422011-08-30 22:40:35 +00009488 StringRef LiteralName
9489 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9490 if (LiteralName[0] != '_') {
9491 // C++0x [usrlit.suffix]p1:
9492 // Literal suffix identifiers that do not start with an underscore are
9493 // reserved for future standardization.
9494 bool IsHexFloat = true;
9495 if (LiteralName.size() > 1 &&
9496 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9497 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9498 if (!isdigit(LiteralName[I])) {
9499 IsHexFloat = false;
9500 break;
9501 }
9502 }
9503 }
9504
9505 if (IsHexFloat)
9506 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9507 << LiteralName;
9508 else
9509 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9510 }
9511
Sean Hunta6c058d2010-01-13 09:01:02 +00009512 return false;
9513}
9514
Douglas Gregor074149e2009-01-05 19:45:36 +00009515/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9516/// linkage specification, including the language and (if present)
9517/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9518/// the location of the language string literal, which is provided
9519/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9520/// the '{' brace. Otherwise, this linkage specification does not
9521/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009522Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9523 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009524 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009525 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009526 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009527 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009528 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009529 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009530 Language = LinkageSpecDecl::lang_cxx;
9531 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009532 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009533 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009534 }
Mike Stump1eb44332009-09-09 15:08:12 +00009535
Chris Lattnercc98eac2008-12-17 07:13:27 +00009536 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009537
Douglas Gregor074149e2009-01-05 19:45:36 +00009538 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009539 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009540 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009541 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009542 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009543}
9544
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009545/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009546/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9547/// valid, it's the position of the closing '}' brace in a linkage
9548/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009549Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009550 Decl *LinkageSpec,
9551 SourceLocation RBraceLoc) {
9552 if (LinkageSpec) {
9553 if (RBraceLoc.isValid()) {
9554 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9555 LSDecl->setRBraceLoc(RBraceLoc);
9556 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009557 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009558 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009559 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009560}
9561
Douglas Gregord308e622009-05-18 20:51:54 +00009562/// \brief Perform semantic analysis for the variable declaration that
9563/// occurs within a C++ catch clause, returning the newly-created
9564/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009565VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009566 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009567 SourceLocation StartLoc,
9568 SourceLocation Loc,
9569 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009570 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009571 QualType ExDeclType = TInfo->getType();
9572
Sebastian Redl4b07b292008-12-22 19:15:10 +00009573 // Arrays and functions decay.
9574 if (ExDeclType->isArrayType())
9575 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9576 else if (ExDeclType->isFunctionType())
9577 ExDeclType = Context.getPointerType(ExDeclType);
9578
9579 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9580 // The exception-declaration shall not denote a pointer or reference to an
9581 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009582 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009583 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009584 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009585 Invalid = true;
9586 }
Douglas Gregord308e622009-05-18 20:51:54 +00009587
Douglas Gregora2762912010-03-08 01:47:36 +00009588 // GCC allows catching pointers and references to incomplete types
9589 // as an extension; so do we, but we warn by default.
9590
Sebastian Redl4b07b292008-12-22 19:15:10 +00009591 QualType BaseType = ExDeclType;
9592 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009593 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00009594 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00009595 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009596 BaseType = Ptr->getPointeeType();
9597 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00009598 DK = diag::ext_catch_incomplete_ptr;
9599 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009600 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009601 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009602 BaseType = Ref->getPointeeType();
9603 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00009604 DK = diag::ext_catch_incomplete_ref;
9605 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009606 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009607 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00009608 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9609 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00009610 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009611
Mike Stump1eb44332009-09-09 15:08:12 +00009612 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009613 RequireNonAbstractType(Loc, ExDeclType,
9614 diag::err_abstract_type_in_decl,
9615 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009616 Invalid = true;
9617
John McCall5a180392010-07-24 00:37:23 +00009618 // Only the non-fragile NeXT runtime currently supports C++ catches
9619 // of ObjC types, and no runtime supports catching ObjC types by value.
9620 if (!Invalid && getLangOptions().ObjC1) {
9621 QualType T = ExDeclType;
9622 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9623 T = RT->getPointeeType();
9624
9625 if (T->isObjCObjectType()) {
9626 Diag(Loc, diag::err_objc_object_catch);
9627 Invalid = true;
9628 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009629 if (!getLangOptions().ObjCNonFragileABI)
9630 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009631 }
9632 }
9633
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009634 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9635 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009636 ExDecl->setExceptionVariable(true);
9637
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009638 // In ARC, infer 'retaining' for variables of retainable type.
9639 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9640 Invalid = true;
9641
Douglas Gregorc41b8782011-07-06 18:14:43 +00009642 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009643 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009644 // C++ [except.handle]p16:
9645 // The object declared in an exception-declaration or, if the
9646 // exception-declaration does not specify a name, a temporary (12.2) is
9647 // copy-initialized (8.5) from the exception object. [...]
9648 // The object is destroyed when the handler exits, after the destruction
9649 // of any automatic objects initialized within the handler.
9650 //
9651 // We just pretend to initialize the object with itself, then make sure
9652 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009653 QualType initType = ExDeclType;
9654
9655 InitializedEntity entity =
9656 InitializedEntity::InitializeVariable(ExDecl);
9657 InitializationKind initKind =
9658 InitializationKind::CreateCopy(Loc, SourceLocation());
9659
9660 Expr *opaqueValue =
9661 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9662 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9663 ExprResult result = sequence.Perform(*this, entity, initKind,
9664 MultiExprArg(&opaqueValue, 1));
9665 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009666 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009667 else {
9668 // If the constructor used was non-trivial, set this as the
9669 // "initializer".
9670 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9671 if (!construct->getConstructor()->isTrivial()) {
9672 Expr *init = MaybeCreateExprWithCleanups(construct);
9673 ExDecl->setInit(init);
9674 }
9675
9676 // And make sure it's destructable.
9677 FinalizeVarWithDestructor(ExDecl, recordType);
9678 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009679 }
9680 }
9681
Douglas Gregord308e622009-05-18 20:51:54 +00009682 if (Invalid)
9683 ExDecl->setInvalidDecl();
9684
9685 return ExDecl;
9686}
9687
9688/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9689/// handler.
John McCalld226f652010-08-21 09:40:31 +00009690Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009691 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009692 bool Invalid = D.isInvalidType();
9693
9694 // Check for unexpanded parameter packs.
9695 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9696 UPPC_ExceptionType)) {
9697 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9698 D.getIdentifierLoc());
9699 Invalid = true;
9700 }
9701
Sebastian Redl4b07b292008-12-22 19:15:10 +00009702 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009703 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009704 LookupOrdinaryName,
9705 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009706 // The scope should be freshly made just for us. There is just no way
9707 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009708 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009709 if (PrevDecl->isTemplateParameter()) {
9710 // Maybe we will complain about the shadowed template parameter.
9711 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009712 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009713 }
9714 }
9715
Chris Lattnereaaebc72009-04-25 08:06:05 +00009716 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009717 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9718 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009719 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009720 }
9721
Douglas Gregor83cb9422010-09-09 17:09:21 +00009722 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009723 D.getSourceRange().getBegin(),
9724 D.getIdentifierLoc(),
9725 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009726 if (Invalid)
9727 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009728
Sebastian Redl4b07b292008-12-22 19:15:10 +00009729 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009730 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009731 PushOnScopeChains(ExDecl, S);
9732 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009733 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009734
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009735 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009736 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009737}
Anders Carlssonfb311762009-03-14 00:25:26 +00009738
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009739Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009740 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009741 Expr *AssertMessageExpr_,
9742 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009743 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009744
Anders Carlssonc3082412009-03-14 00:33:21 +00009745 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009746 llvm::APSInt Cond;
9747 if (VerifyIntegerConstantExpression(AssertExpr, &Cond,
9748 diag::err_static_assert_expression_is_not_constant,
9749 /*AllowFold=*/false))
John McCalld226f652010-08-21 09:40:31 +00009750 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009751
Richard Smithdaaefc52011-12-14 23:32:26 +00009752 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009753 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009754 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009755 }
Mike Stump1eb44332009-09-09 15:08:12 +00009756
Douglas Gregor399ad972010-12-15 23:55:21 +00009757 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9758 return 0;
9759
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009760 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9761 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009762
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009763 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009764 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009765}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009766
Douglas Gregor1d869352010-04-07 16:53:43 +00009767/// \brief Perform semantic analysis of the given friend type declaration.
9768///
9769/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009770FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9771 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009772 TypeSourceInfo *TSInfo) {
9773 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9774
9775 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009776 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009777
Richard Smith6b130222011-10-18 21:39:00 +00009778 // C++03 [class.friend]p2:
9779 // An elaborated-type-specifier shall be used in a friend declaration
9780 // for a class.*
9781 //
9782 // * The class-key of the elaborated-type-specifier is required.
9783 if (!ActiveTemplateInstantiations.empty()) {
9784 // Do not complain about the form of friend template types during
9785 // template instantiation; we will already have complained when the
9786 // template was declared.
9787 } else if (!T->isElaboratedTypeSpecifier()) {
9788 // If we evaluated the type to a record type, suggest putting
9789 // a tag in front.
9790 if (const RecordType *RT = T->getAs<RecordType>()) {
9791 RecordDecl *RD = RT->getDecl();
9792
9793 std::string InsertionText = std::string(" ") + RD->getKindName();
9794
9795 Diag(TypeRange.getBegin(),
9796 getLangOptions().CPlusPlus0x ?
9797 diag::warn_cxx98_compat_unelaborated_friend_type :
9798 diag::ext_unelaborated_friend_type)
9799 << (unsigned) RD->getTagKind()
9800 << T
9801 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9802 InsertionText);
9803 } else {
9804 Diag(FriendLoc,
9805 getLangOptions().CPlusPlus0x ?
9806 diag::warn_cxx98_compat_nonclass_type_friend :
9807 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009808 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009809 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009810 }
Richard Smith6b130222011-10-18 21:39:00 +00009811 } else if (T->getAs<EnumType>()) {
9812 Diag(FriendLoc,
9813 getLangOptions().CPlusPlus0x ?
9814 diag::warn_cxx98_compat_enum_friend :
9815 diag::ext_enum_friend)
9816 << T
9817 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009818 }
9819
Douglas Gregor06245bf2010-04-07 17:57:12 +00009820 // C++0x [class.friend]p3:
9821 // If the type specifier in a friend declaration designates a (possibly
9822 // cv-qualified) class type, that class is declared as a friend; otherwise,
9823 // the friend declaration is ignored.
9824
9825 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9826 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009827
Abramo Bagnara0216df82011-10-29 20:52:52 +00009828 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009829}
9830
John McCall9a34edb2010-10-19 01:40:49 +00009831/// Handle a friend tag declaration where the scope specifier was
9832/// templated.
9833Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9834 unsigned TagSpec, SourceLocation TagLoc,
9835 CXXScopeSpec &SS,
9836 IdentifierInfo *Name, SourceLocation NameLoc,
9837 AttributeList *Attr,
9838 MultiTemplateParamsArg TempParamLists) {
9839 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9840
9841 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009842 bool Invalid = false;
9843
9844 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009845 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009846 TempParamLists.get(),
9847 TempParamLists.size(),
9848 /*friend*/ true,
9849 isExplicitSpecialization,
9850 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009851 if (TemplateParams->size() > 0) {
9852 // This is a declaration of a class template.
9853 if (Invalid)
9854 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009855
Eric Christopher4110e132011-07-21 05:34:24 +00009856 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9857 SS, Name, NameLoc, Attr,
9858 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009859 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009860 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009861 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009862 } else {
9863 // The "template<>" header is extraneous.
9864 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9865 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9866 isExplicitSpecialization = true;
9867 }
9868 }
9869
9870 if (Invalid) return 0;
9871
John McCall9a34edb2010-10-19 01:40:49 +00009872 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009873 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009874 if (TempParamLists.get()[I]->size()) {
9875 isAllExplicitSpecializations = false;
9876 break;
9877 }
9878 }
9879
9880 // FIXME: don't ignore attributes.
9881
9882 // If it's explicit specializations all the way down, just forget
9883 // about the template header and build an appropriate non-templated
9884 // friend. TODO: for source fidelity, remember the headers.
9885 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009886 if (SS.isEmpty()) {
9887 bool Owned = false;
9888 bool IsDependent = false;
9889 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9890 Attr, AS_public,
9891 /*ModulePrivateLoc=*/SourceLocation(),
9892 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009893 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009894 /*ScopedEnumUsesClassTag=*/false,
9895 /*UnderlyingType=*/TypeResult());
9896 }
9897
Douglas Gregor2494dd02011-03-01 01:34:45 +00009898 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009899 ElaboratedTypeKeyword Keyword
9900 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009901 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009902 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009903 if (T.isNull())
9904 return 0;
9905
9906 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9907 if (isa<DependentNameType>(T)) {
9908 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9909 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009910 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009911 TL.setNameLoc(NameLoc);
9912 } else {
9913 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9914 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009915 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009916 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9917 }
9918
9919 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9920 TSI, FriendLoc);
9921 Friend->setAccess(AS_public);
9922 CurContext->addDecl(Friend);
9923 return Friend;
9924 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009925
9926 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9927
9928
John McCall9a34edb2010-10-19 01:40:49 +00009929
9930 // Handle the case of a templated-scope friend class. e.g.
9931 // template <class T> class A<T>::B;
9932 // FIXME: we don't support these right now.
9933 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9934 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9935 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9936 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9937 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009938 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009939 TL.setNameLoc(NameLoc);
9940
9941 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9942 TSI, FriendLoc);
9943 Friend->setAccess(AS_public);
9944 Friend->setUnsupportedFriend(true);
9945 CurContext->addDecl(Friend);
9946 return Friend;
9947}
9948
9949
John McCalldd4a3b02009-09-16 22:47:08 +00009950/// Handle a friend type declaration. This works in tandem with
9951/// ActOnTag.
9952///
9953/// Notes on friend class templates:
9954///
9955/// We generally treat friend class declarations as if they were
9956/// declaring a class. So, for example, the elaborated type specifier
9957/// in a friend declaration is required to obey the restrictions of a
9958/// class-head (i.e. no typedefs in the scope chain), template
9959/// parameters are required to match up with simple template-ids, &c.
9960/// However, unlike when declaring a template specialization, it's
9961/// okay to refer to a template specialization without an empty
9962/// template parameter declaration, e.g.
9963/// friend class A<T>::B<unsigned>;
9964/// We permit this as a special case; if there are any template
9965/// parameters present at all, require proper matching, i.e.
9966/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00009967Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00009968 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00009969 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00009970
9971 assert(DS.isFriendSpecified());
9972 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9973
John McCalldd4a3b02009-09-16 22:47:08 +00009974 // Try to convert the decl specifier to a type. This works for
9975 // friend templates because ActOnTag never produces a ClassTemplateDecl
9976 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00009977 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00009978 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9979 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00009980 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00009981 return 0;
John McCall67d1a672009-08-06 02:15:43 +00009982
Douglas Gregor6ccab972010-12-16 01:14:37 +00009983 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9984 return 0;
9985
John McCalldd4a3b02009-09-16 22:47:08 +00009986 // This is definitely an error in C++98. It's probably meant to
9987 // be forbidden in C++0x, too, but the specification is just
9988 // poorly written.
9989 //
9990 // The problem is with declarations like the following:
9991 // template <T> friend A<T>::foo;
9992 // where deciding whether a class C is a friend or not now hinges
9993 // on whether there exists an instantiation of A that causes
9994 // 'foo' to equal C. There are restrictions on class-heads
9995 // (which we declare (by fiat) elaborated friend declarations to
9996 // be) that makes this tractable.
9997 //
9998 // FIXME: handle "template <> friend class A<T>;", which
9999 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010000 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010001 Diag(Loc, diag::err_tagless_friend_type_template)
10002 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010003 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010004 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010005
John McCall02cace72009-08-28 07:59:38 +000010006 // C++98 [class.friend]p1: A friend of a class is a function
10007 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010008 // This is fixed in DR77, which just barely didn't make the C++03
10009 // deadline. It's also a very silly restriction that seriously
10010 // affects inner classes and which nobody else seems to implement;
10011 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010012 //
10013 // But note that we could warn about it: it's always useless to
10014 // friend one of your own members (it's not, however, worthless to
10015 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010016
John McCalldd4a3b02009-09-16 22:47:08 +000010017 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010018 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010019 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010020 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010021 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010022 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010023 DS.getFriendSpecLoc());
10024 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010025 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010026
10027 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010028 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010029
John McCalldd4a3b02009-09-16 22:47:08 +000010030 D->setAccess(AS_public);
10031 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010032
John McCalld226f652010-08-21 09:40:31 +000010033 return D;
John McCall02cace72009-08-28 07:59:38 +000010034}
10035
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010036Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010037 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010038 const DeclSpec &DS = D.getDeclSpec();
10039
10040 assert(DS.isFriendSpecified());
10041 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10042
10043 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010044 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010045
10046 // C++ [class.friend]p1
10047 // A friend of a class is a function or class....
10048 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010049 // It *doesn't* see through dependent types, which is correct
10050 // according to [temp.arg.type]p3:
10051 // If a declaration acquires a function type through a
10052 // type dependent on a template-parameter and this causes
10053 // a declaration that does not use the syntactic form of a
10054 // function declarator to have a function type, the program
10055 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010056 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010057 Diag(Loc, diag::err_unexpected_friend);
10058
10059 // It might be worthwhile to try to recover by creating an
10060 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010061 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010062 }
10063
10064 // C++ [namespace.memdef]p3
10065 // - If a friend declaration in a non-local class first declares a
10066 // class or function, the friend class or function is a member
10067 // of the innermost enclosing namespace.
10068 // - The name of the friend is not found by simple name lookup
10069 // until a matching declaration is provided in that namespace
10070 // scope (either before or after the class declaration granting
10071 // friendship).
10072 // - If a friend function is called, its name may be found by the
10073 // name lookup that considers functions from namespaces and
10074 // classes associated with the types of the function arguments.
10075 // - When looking for a prior declaration of a class or a function
10076 // declared as a friend, scopes outside the innermost enclosing
10077 // namespace scope are not considered.
10078
John McCall337ec3d2010-10-12 23:13:28 +000010079 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010080 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10081 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010082 assert(Name);
10083
Douglas Gregor6ccab972010-12-16 01:14:37 +000010084 // Check for unexpanded parameter packs.
10085 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10086 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10087 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10088 return 0;
10089
John McCall67d1a672009-08-06 02:15:43 +000010090 // The context we found the declaration in, or in which we should
10091 // create the declaration.
10092 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010093 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010094 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010095 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010096
John McCall337ec3d2010-10-12 23:13:28 +000010097 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010098
John McCall337ec3d2010-10-12 23:13:28 +000010099 // There are four cases here.
10100 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010101 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010102 // there as appropriate.
10103 // Recover from invalid scope qualifiers as if they just weren't there.
10104 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010105 // C++0x [namespace.memdef]p3:
10106 // If the name in a friend declaration is neither qualified nor
10107 // a template-id and the declaration is a function or an
10108 // elaborated-type-specifier, the lookup to determine whether
10109 // the entity has been previously declared shall not consider
10110 // any scopes outside the innermost enclosing namespace.
10111 // C++0x [class.friend]p11:
10112 // If a friend declaration appears in a local class and the name
10113 // specified is an unqualified name, a prior declaration is
10114 // looked up without considering scopes that are outside the
10115 // innermost enclosing non-class scope. For a friend function
10116 // declaration, if there is no prior declaration, the program is
10117 // ill-formed.
10118 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010119 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010120
John McCall29ae6e52010-10-13 05:45:15 +000010121 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010122 DC = CurContext;
10123 while (true) {
10124 // Skip class contexts. If someone can cite chapter and verse
10125 // for this behavior, that would be nice --- it's what GCC and
10126 // EDG do, and it seems like a reasonable intent, but the spec
10127 // really only says that checks for unqualified existing
10128 // declarations should stop at the nearest enclosing namespace,
10129 // not that they should only consider the nearest enclosing
10130 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010131 while (DC->isRecord())
10132 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010133
John McCall68263142009-11-18 22:49:29 +000010134 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010135
10136 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010137 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010138 break;
John McCall29ae6e52010-10-13 05:45:15 +000010139
John McCall8a407372010-10-14 22:22:28 +000010140 if (isTemplateId) {
10141 if (isa<TranslationUnitDecl>(DC)) break;
10142 } else {
10143 if (DC->isFileContext()) break;
10144 }
John McCall67d1a672009-08-06 02:15:43 +000010145 DC = DC->getParent();
10146 }
10147
10148 // C++ [class.friend]p1: A friend of a class is a function or
10149 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010150 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010151 // Most C++ 98 compilers do seem to give an error here, so
10152 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010153 if (!Previous.empty() && DC->Equals(CurContext))
10154 Diag(DS.getFriendSpecLoc(),
10155 getLangOptions().CPlusPlus0x ?
10156 diag::warn_cxx98_compat_friend_is_member :
10157 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010158
John McCall380aaa42010-10-13 06:22:15 +000010159 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010160
Douglas Gregor883af832011-10-10 01:11:59 +000010161 // C++ [class.friend]p6:
10162 // A function can be defined in a friend declaration of a class if and
10163 // only if the class is a non-local class (9.8), the function name is
10164 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010165 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010166 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10167 }
10168
John McCall337ec3d2010-10-12 23:13:28 +000010169 // - There's a non-dependent scope specifier, in which case we
10170 // compute it and do a previous lookup there for a function
10171 // or function template.
10172 } else if (!SS.getScopeRep()->isDependent()) {
10173 DC = computeDeclContext(SS);
10174 if (!DC) return 0;
10175
10176 if (RequireCompleteDeclContext(SS, DC)) return 0;
10177
10178 LookupQualifiedName(Previous, DC);
10179
10180 // Ignore things found implicitly in the wrong scope.
10181 // TODO: better diagnostics for this case. Suggesting the right
10182 // qualified scope would be nice...
10183 LookupResult::Filter F = Previous.makeFilter();
10184 while (F.hasNext()) {
10185 NamedDecl *D = F.next();
10186 if (!DC->InEnclosingNamespaceSetOf(
10187 D->getDeclContext()->getRedeclContext()))
10188 F.erase();
10189 }
10190 F.done();
10191
10192 if (Previous.empty()) {
10193 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010194 Diag(Loc, diag::err_qualified_friend_not_found)
10195 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010196 return 0;
10197 }
10198
10199 // C++ [class.friend]p1: A friend of a class is a function or
10200 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010201 if (DC->Equals(CurContext))
10202 Diag(DS.getFriendSpecLoc(),
10203 getLangOptions().CPlusPlus0x ?
10204 diag::warn_cxx98_compat_friend_is_member :
10205 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010206
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010207 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010208 // C++ [class.friend]p6:
10209 // A function can be defined in a friend declaration of a class if and
10210 // only if the class is a non-local class (9.8), the function name is
10211 // unqualified, and the function has namespace scope.
10212 SemaDiagnosticBuilder DB
10213 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10214
10215 DB << SS.getScopeRep();
10216 if (DC->isFileContext())
10217 DB << FixItHint::CreateRemoval(SS.getRange());
10218 SS.clear();
10219 }
John McCall337ec3d2010-10-12 23:13:28 +000010220
10221 // - There's a scope specifier that does not match any template
10222 // parameter lists, in which case we use some arbitrary context,
10223 // create a method or method template, and wait for instantiation.
10224 // - There's a scope specifier that does match some template
10225 // parameter lists, which we don't handle right now.
10226 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010227 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010228 // C++ [class.friend]p6:
10229 // A function can be defined in a friend declaration of a class if and
10230 // only if the class is a non-local class (9.8), the function name is
10231 // unqualified, and the function has namespace scope.
10232 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10233 << SS.getScopeRep();
10234 }
10235
John McCall337ec3d2010-10-12 23:13:28 +000010236 DC = CurContext;
10237 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010238 }
Douglas Gregor883af832011-10-10 01:11:59 +000010239
John McCall29ae6e52010-10-13 05:45:15 +000010240 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010241 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010242 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10243 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10244 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010245 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010246 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10247 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010248 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010249 }
John McCall67d1a672009-08-06 02:15:43 +000010250 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010251
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010252 // FIXME: This is an egregious hack to cope with cases where the scope stack
10253 // does not contain the declaration context, i.e., in an out-of-line
10254 // definition of a class.
10255 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10256 if (!DCScope) {
10257 FakeDCScope.setEntity(DC);
10258 DCScope = &FakeDCScope;
10259 }
10260
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010261 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010262 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10263 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010264 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010265
Douglas Gregor182ddf02009-09-28 00:08:27 +000010266 assert(ND->getDeclContext() == DC);
10267 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010268
John McCallab88d972009-08-31 22:39:49 +000010269 // Add the function declaration to the appropriate lookup tables,
10270 // adjusting the redeclarations list as necessary. We don't
10271 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010272 //
John McCallab88d972009-08-31 22:39:49 +000010273 // Also update the scope-based lookup if the target context's
10274 // lookup context is in lexical scope.
10275 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010276 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010277 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010278 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010279 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010280 }
John McCall02cace72009-08-28 07:59:38 +000010281
10282 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010283 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010284 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010285 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010286 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010287
John McCall337ec3d2010-10-12 23:13:28 +000010288 if (ND->isInvalidDecl())
10289 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010290 else {
10291 FunctionDecl *FD;
10292 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10293 FD = FTD->getTemplatedDecl();
10294 else
10295 FD = cast<FunctionDecl>(ND);
10296
10297 // Mark templated-scope function declarations as unsupported.
10298 if (FD->getNumTemplateParameterLists())
10299 FrD->setUnsupportedFriend(true);
10300 }
John McCall337ec3d2010-10-12 23:13:28 +000010301
John McCalld226f652010-08-21 09:40:31 +000010302 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010303}
10304
John McCalld226f652010-08-21 09:40:31 +000010305void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10306 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010307
Sebastian Redl50de12f2009-03-24 22:27:57 +000010308 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10309 if (!Fn) {
10310 Diag(DelLoc, diag::err_deleted_non_function);
10311 return;
10312 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010313 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010314 Diag(DelLoc, diag::err_deleted_decl_not_first);
10315 Diag(Prev->getLocation(), diag::note_previous_declaration);
10316 // If the declaration wasn't the first, we delete the function anyway for
10317 // recovery.
10318 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010319 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010320}
Sebastian Redl13e88542009-04-27 21:33:24 +000010321
Sean Hunte4246a62011-05-12 06:15:49 +000010322void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10323 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10324
10325 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010326 if (MD->getParent()->isDependentType()) {
10327 MD->setDefaulted();
10328 MD->setExplicitlyDefaulted();
10329 return;
10330 }
10331
Sean Hunte4246a62011-05-12 06:15:49 +000010332 CXXSpecialMember Member = getSpecialMember(MD);
10333 if (Member == CXXInvalid) {
10334 Diag(DefaultLoc, diag::err_default_special_members);
10335 return;
10336 }
10337
10338 MD->setDefaulted();
10339 MD->setExplicitlyDefaulted();
10340
Sean Huntcd10dec2011-05-23 23:14:04 +000010341 // If this definition appears within the record, do the checking when
10342 // the record is complete.
10343 const FunctionDecl *Primary = MD;
10344 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10345 // Find the uninstantiated declaration that actually had the '= default'
10346 // on it.
10347 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10348
10349 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010350 return;
10351
10352 switch (Member) {
10353 case CXXDefaultConstructor: {
10354 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10355 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010356 if (!CD->isInvalidDecl())
10357 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10358 break;
10359 }
10360
10361 case CXXCopyConstructor: {
10362 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10363 CheckExplicitlyDefaultedCopyConstructor(CD);
10364 if (!CD->isInvalidDecl())
10365 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010366 break;
10367 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010368
Sean Hunt2b188082011-05-14 05:23:28 +000010369 case CXXCopyAssignment: {
10370 CheckExplicitlyDefaultedCopyAssignment(MD);
10371 if (!MD->isInvalidDecl())
10372 DefineImplicitCopyAssignment(DefaultLoc, MD);
10373 break;
10374 }
10375
Sean Huntcb45a0f2011-05-12 22:46:25 +000010376 case CXXDestructor: {
10377 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10378 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010379 if (!DD->isInvalidDecl())
10380 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010381 break;
10382 }
10383
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010384 case CXXMoveConstructor: {
10385 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10386 CheckExplicitlyDefaultedMoveConstructor(CD);
10387 if (!CD->isInvalidDecl())
10388 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010389 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010390 }
Sean Hunt82713172011-05-25 23:16:36 +000010391
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010392 case CXXMoveAssignment: {
10393 CheckExplicitlyDefaultedMoveAssignment(MD);
10394 if (!MD->isInvalidDecl())
10395 DefineImplicitMoveAssignment(DefaultLoc, MD);
10396 break;
10397 }
10398
10399 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010400 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010401 }
10402 } else {
10403 Diag(DefaultLoc, diag::err_default_special_members);
10404 }
10405}
10406
Sebastian Redl13e88542009-04-27 21:33:24 +000010407static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010408 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010409 Stmt *SubStmt = *CI;
10410 if (!SubStmt)
10411 continue;
10412 if (isa<ReturnStmt>(SubStmt))
10413 Self.Diag(SubStmt->getSourceRange().getBegin(),
10414 diag::err_return_in_constructor_handler);
10415 if (!isa<Expr>(SubStmt))
10416 SearchForReturnInStmt(Self, SubStmt);
10417 }
10418}
10419
10420void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10421 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10422 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10423 SearchForReturnInStmt(*this, Handler);
10424 }
10425}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010426
Mike Stump1eb44332009-09-09 15:08:12 +000010427bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010428 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010429 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10430 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010431
Chandler Carruth73857792010-02-15 11:53:20 +000010432 if (Context.hasSameType(NewTy, OldTy) ||
10433 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010434 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010435
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010436 // Check if the return types are covariant
10437 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010438
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010439 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010440 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10441 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010442 NewClassTy = NewPT->getPointeeType();
10443 OldClassTy = OldPT->getPointeeType();
10444 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010445 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10446 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10447 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10448 NewClassTy = NewRT->getPointeeType();
10449 OldClassTy = OldRT->getPointeeType();
10450 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010451 }
10452 }
Mike Stump1eb44332009-09-09 15:08:12 +000010453
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010454 // The return types aren't either both pointers or references to a class type.
10455 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010456 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010457 diag::err_different_return_type_for_overriding_virtual_function)
10458 << New->getDeclName() << NewTy << OldTy;
10459 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010460
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010461 return true;
10462 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010463
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010464 // C++ [class.virtual]p6:
10465 // If the return type of D::f differs from the return type of B::f, the
10466 // class type in the return type of D::f shall be complete at the point of
10467 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010468 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10469 if (!RT->isBeingDefined() &&
10470 RequireCompleteType(New->getLocation(), NewClassTy,
10471 PDiag(diag::err_covariant_return_incomplete)
10472 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010473 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010474 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010475
Douglas Gregora4923eb2009-11-16 21:35:15 +000010476 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010477 // Check if the new class derives from the old class.
10478 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10479 Diag(New->getLocation(),
10480 diag::err_covariant_return_not_derived)
10481 << New->getDeclName() << NewTy << OldTy;
10482 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10483 return true;
10484 }
Mike Stump1eb44332009-09-09 15:08:12 +000010485
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010486 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010487 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010488 diag::err_covariant_return_inaccessible_base,
10489 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10490 // FIXME: Should this point to the return type?
10491 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010492 // FIXME: this note won't trigger for delayed access control
10493 // diagnostics, and it's impossible to get an undelayed error
10494 // here from access control during the original parse because
10495 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010496 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10497 return true;
10498 }
10499 }
Mike Stump1eb44332009-09-09 15:08:12 +000010500
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010501 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010502 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010503 Diag(New->getLocation(),
10504 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010505 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010506 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10507 return true;
10508 };
Mike Stump1eb44332009-09-09 15:08:12 +000010509
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010510
10511 // The new class type must have the same or less qualifiers as the old type.
10512 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10513 Diag(New->getLocation(),
10514 diag::err_covariant_return_type_class_type_more_qualified)
10515 << New->getDeclName() << NewTy << OldTy;
10516 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10517 return true;
10518 };
Mike Stump1eb44332009-09-09 15:08:12 +000010519
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010520 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010521}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010522
Douglas Gregor4ba31362009-12-01 17:24:26 +000010523/// \brief Mark the given method pure.
10524///
10525/// \param Method the method to be marked pure.
10526///
10527/// \param InitRange the source range that covers the "0" initializer.
10528bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010529 SourceLocation EndLoc = InitRange.getEnd();
10530 if (EndLoc.isValid())
10531 Method->setRangeEnd(EndLoc);
10532
Douglas Gregor4ba31362009-12-01 17:24:26 +000010533 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10534 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010535 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010536 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010537
10538 if (!Method->isInvalidDecl())
10539 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10540 << Method->getDeclName() << InitRange;
10541 return true;
10542}
10543
John McCall731ad842009-12-19 09:28:58 +000010544/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10545/// an initializer for the out-of-line declaration 'Dcl'. The scope
10546/// is a fresh scope pushed for just this purpose.
10547///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010548/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10549/// static data member of class X, names should be looked up in the scope of
10550/// class X.
John McCalld226f652010-08-21 09:40:31 +000010551void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010552 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010553 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010554
John McCall731ad842009-12-19 09:28:58 +000010555 // We should only get called for declarations with scope specifiers, like:
10556 // int foo::bar;
10557 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010558 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010559}
10560
10561/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010562/// initializer for the out-of-line declaration 'D'.
10563void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010564 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010565 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010566
John McCall731ad842009-12-19 09:28:58 +000010567 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010568 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010569}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010570
10571/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10572/// C++ if/switch/while/for statement.
10573/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010574DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010575 // C++ 6.4p2:
10576 // The declarator shall not specify a function or an array.
10577 // The type-specifier-seq shall not contain typedef and shall not declare a
10578 // new class or enumeration.
10579 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10580 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010581
10582 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010583 if (!Dcl)
10584 return true;
10585
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010586 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10587 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010588 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010589 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010590 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010591
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010592 return Dcl;
10593}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010594
Douglas Gregordfe65432011-07-28 19:11:31 +000010595void Sema::LoadExternalVTableUses() {
10596 if (!ExternalSource)
10597 return;
10598
10599 SmallVector<ExternalVTableUse, 4> VTables;
10600 ExternalSource->ReadUsedVTables(VTables);
10601 SmallVector<VTableUse, 4> NewUses;
10602 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10603 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10604 = VTablesUsed.find(VTables[I].Record);
10605 // Even if a definition wasn't required before, it may be required now.
10606 if (Pos != VTablesUsed.end()) {
10607 if (!Pos->second && VTables[I].DefinitionRequired)
10608 Pos->second = true;
10609 continue;
10610 }
10611
10612 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10613 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10614 }
10615
10616 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10617}
10618
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010619void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10620 bool DefinitionRequired) {
10621 // Ignore any vtable uses in unevaluated operands or for classes that do
10622 // not have a vtable.
10623 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10624 CurContext->isDependentContext() ||
Richard Smithf6702a32011-12-20 02:08:33 +000010625 ExprEvalContexts.back().Context == Unevaluated ||
10626 ExprEvalContexts.back().Context == ConstantEvaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010627 return;
10628
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010629 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010630 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010631 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10632 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10633 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10634 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010635 // If we already had an entry, check to see if we are promoting this vtable
10636 // to required a definition. If so, we need to reappend to the VTableUses
10637 // list, since we may have already processed the first entry.
10638 if (DefinitionRequired && !Pos.first->second) {
10639 Pos.first->second = true;
10640 } else {
10641 // Otherwise, we can early exit.
10642 return;
10643 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010644 }
10645
10646 // Local classes need to have their virtual members marked
10647 // immediately. For all other classes, we mark their virtual members
10648 // at the end of the translation unit.
10649 if (Class->isLocalClass())
10650 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010651 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010652 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010653}
10654
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010655bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010656 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010657 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010658 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010659
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010660 // Note: The VTableUses vector could grow as a result of marking
10661 // the members of a class as "used", so we check the size each
10662 // time through the loop and prefer indices (with are stable) to
10663 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010664 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010665 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010666 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010667 if (!Class)
10668 continue;
10669
10670 SourceLocation Loc = VTableUses[I].second;
10671
10672 // If this class has a key function, but that key function is
10673 // defined in another translation unit, we don't need to emit the
10674 // vtable even though we're using it.
10675 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010676 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010677 switch (KeyFunction->getTemplateSpecializationKind()) {
10678 case TSK_Undeclared:
10679 case TSK_ExplicitSpecialization:
10680 case TSK_ExplicitInstantiationDeclaration:
10681 // The key function is in another translation unit.
10682 continue;
10683
10684 case TSK_ExplicitInstantiationDefinition:
10685 case TSK_ImplicitInstantiation:
10686 // We will be instantiating the key function.
10687 break;
10688 }
10689 } else if (!KeyFunction) {
10690 // If we have a class with no key function that is the subject
10691 // of an explicit instantiation declaration, suppress the
10692 // vtable; it will live with the explicit instantiation
10693 // definition.
10694 bool IsExplicitInstantiationDeclaration
10695 = Class->getTemplateSpecializationKind()
10696 == TSK_ExplicitInstantiationDeclaration;
10697 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10698 REnd = Class->redecls_end();
10699 R != REnd; ++R) {
10700 TemplateSpecializationKind TSK
10701 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10702 if (TSK == TSK_ExplicitInstantiationDeclaration)
10703 IsExplicitInstantiationDeclaration = true;
10704 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10705 IsExplicitInstantiationDeclaration = false;
10706 break;
10707 }
10708 }
10709
10710 if (IsExplicitInstantiationDeclaration)
10711 continue;
10712 }
10713
10714 // Mark all of the virtual members of this class as referenced, so
10715 // that we can build a vtable. Then, tell the AST consumer that a
10716 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010717 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010718 MarkVirtualMembersReferenced(Loc, Class);
10719 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10720 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10721
10722 // Optionally warn if we're emitting a weak vtable.
10723 if (Class->getLinkage() == ExternalLinkage &&
10724 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010725 const FunctionDecl *KeyFunctionDef = 0;
10726 if (!KeyFunction ||
10727 (KeyFunction->hasBody(KeyFunctionDef) &&
10728 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010729 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10730 TSK_ExplicitInstantiationDefinition
10731 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10732 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010733 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010734 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010735 VTableUses.clear();
10736
Douglas Gregor78844032011-04-22 22:25:37 +000010737 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010738}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010739
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010740void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10741 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010742 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10743 e = RD->method_end(); i != e; ++i) {
10744 CXXMethodDecl *MD = *i;
10745
10746 // C++ [basic.def.odr]p2:
10747 // [...] A virtual member function is used if it is not pure. [...]
10748 if (MD->isVirtual() && !MD->isPure())
10749 MarkDeclarationReferenced(Loc, MD);
10750 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010751
10752 // Only classes that have virtual bases need a VTT.
10753 if (RD->getNumVBases() == 0)
10754 return;
10755
10756 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10757 e = RD->bases_end(); i != e; ++i) {
10758 const CXXRecordDecl *Base =
10759 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010760 if (Base->getNumVBases() == 0)
10761 continue;
10762 MarkVirtualMembersReferenced(Loc, Base);
10763 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010764}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010765
10766/// SetIvarInitializers - This routine builds initialization ASTs for the
10767/// Objective-C implementation whose ivars need be initialized.
10768void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10769 if (!getLangOptions().CPlusPlus)
10770 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010771 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010772 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010773 CollectIvarsToConstructOrDestruct(OID, ivars);
10774 if (ivars.empty())
10775 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010776 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010777 for (unsigned i = 0; i < ivars.size(); i++) {
10778 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010779 if (Field->isInvalidDecl())
10780 continue;
10781
Sean Huntcbb67482011-01-08 20:30:50 +000010782 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010783 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10784 InitializationKind InitKind =
10785 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10786
10787 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010788 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010789 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010790 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010791 // Note, MemberInit could actually come back empty if no initialization
10792 // is required (e.g., because it would call a trivial default constructor)
10793 if (!MemberInit.get() || MemberInit.isInvalid())
10794 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010795
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010796 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010797 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10798 SourceLocation(),
10799 MemberInit.takeAs<Expr>(),
10800 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010801 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010802
10803 // Be sure that the destructor is accessible and is marked as referenced.
10804 if (const RecordType *RecordTy
10805 = Context.getBaseElementType(Field->getType())
10806 ->getAs<RecordType>()) {
10807 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010808 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010809 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10810 CheckDestructorAccess(Field->getLocation(), Destructor,
10811 PDiag(diag::err_access_dtor_ivar)
10812 << Context.getBaseElementType(Field->getType()));
10813 }
10814 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010815 }
10816 ObjCImplementation->setIvarInitializers(Context,
10817 AllToInit.data(), AllToInit.size());
10818 }
10819}
Sean Huntfe57eef2011-05-04 05:57:24 +000010820
Sean Huntebcbe1d2011-05-04 23:29:54 +000010821static
10822void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10823 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10824 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10825 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10826 Sema &S) {
10827 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10828 CE = Current.end();
10829 if (Ctor->isInvalidDecl())
10830 return;
10831
10832 const FunctionDecl *FNTarget = 0;
10833 CXXConstructorDecl *Target;
10834
10835 // We ignore the result here since if we don't have a body, Target will be
10836 // null below.
10837 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10838 Target
10839= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10840
10841 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10842 // Avoid dereferencing a null pointer here.
10843 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10844
10845 if (!Current.insert(Canonical))
10846 return;
10847
10848 // We know that beyond here, we aren't chaining into a cycle.
10849 if (!Target || !Target->isDelegatingConstructor() ||
10850 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10851 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10852 Valid.insert(*CI);
10853 Current.clear();
10854 // We've hit a cycle.
10855 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10856 Current.count(TCanonical)) {
10857 // If we haven't diagnosed this cycle yet, do so now.
10858 if (!Invalid.count(TCanonical)) {
10859 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010860 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010861 << Ctor;
10862
10863 // Don't add a note for a function delegating directo to itself.
10864 if (TCanonical != Canonical)
10865 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10866
10867 CXXConstructorDecl *C = Target;
10868 while (C->getCanonicalDecl() != Canonical) {
10869 (void)C->getTargetConstructor()->hasBody(FNTarget);
10870 assert(FNTarget && "Ctor cycle through bodiless function");
10871
10872 C
10873 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10874 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10875 }
10876 }
10877
10878 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10879 Invalid.insert(*CI);
10880 Current.clear();
10881 } else {
10882 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10883 }
10884}
10885
10886
Sean Huntfe57eef2011-05-04 05:57:24 +000010887void Sema::CheckDelegatingCtorCycles() {
10888 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10889
Sean Huntebcbe1d2011-05-04 23:29:54 +000010890 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10891 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010892
Douglas Gregor0129b562011-07-27 21:57:17 +000010893 for (DelegatingCtorDeclsType::iterator
10894 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010895 E = DelegatingCtorDecls.end();
10896 I != E; ++I) {
10897 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010898 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010899
10900 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10901 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010902}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010903
10904/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10905Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10906 // Implicitly declared functions (e.g. copy constructors) are
10907 // __host__ __device__
10908 if (D->isImplicit())
10909 return CFT_HostDevice;
10910
10911 if (D->hasAttr<CUDAGlobalAttr>())
10912 return CFT_Global;
10913
10914 if (D->hasAttr<CUDADeviceAttr>()) {
10915 if (D->hasAttr<CUDAHostAttr>())
10916 return CFT_HostDevice;
10917 else
10918 return CFT_Device;
10919 }
10920
10921 return CFT_Host;
10922}
10923
10924bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10925 CUDAFunctionTarget CalleeTarget) {
10926 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10927 // Callable from the device only."
10928 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10929 return true;
10930
10931 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10932 // Callable from the host only."
10933 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10934 // Callable from the host only."
10935 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10936 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10937 return true;
10938
10939 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10940 return true;
10941
10942 return false;
10943}