blob: d83bf088917479e59b7f3e0c146f028b54a52e5b [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
Richard Smith745f5142012-01-27 01:14:48 +0000975 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
976 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
977 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
978 << isa<CXXConstructorDecl>(Dcl);
979 for (size_t I = 0, N = Diags.size(); I != N; ++I)
980 Diag(Diags[I].first, Diags[I].second);
981 return false;
982 }
983
Richard Smith9f569cc2011-10-01 02:31:28 +0000984 return true;
985}
986
Douglas Gregorb48fe382008-10-31 09:07:45 +0000987/// isCurrentClassName - Determine whether the identifier II is the
988/// name of the class type currently being defined. In the case of
989/// nested classes, this will only return true if II is the name of
990/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000991bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
992 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000993 assert(getLangOptions().CPlusPlus && "No class names in C!");
994
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000995 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000996 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000997 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000998 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
999 } else
1000 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1001
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001002 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001003 return &II == CurDecl->getIdentifier();
1004 else
1005 return false;
1006}
1007
Mike Stump1eb44332009-09-09 15:08:12 +00001008/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001009///
1010/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1011/// and returns NULL otherwise.
1012CXXBaseSpecifier *
1013Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1014 SourceRange SpecifierRange,
1015 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001016 TypeSourceInfo *TInfo,
1017 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001018 QualType BaseType = TInfo->getType();
1019
Douglas Gregor2943aed2009-03-03 04:44:36 +00001020 // C++ [class.union]p1:
1021 // A union shall not have base classes.
1022 if (Class->isUnion()) {
1023 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1024 << SpecifierRange;
1025 return 0;
1026 }
1027
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001028 if (EllipsisLoc.isValid() &&
1029 !TInfo->getType()->containsUnexpandedParameterPack()) {
1030 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1031 << TInfo->getTypeLoc().getSourceRange();
1032 EllipsisLoc = SourceLocation();
1033 }
1034
Douglas Gregor2943aed2009-03-03 04:44:36 +00001035 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001036 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001037 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001038 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001039
1040 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001041
1042 // Base specifiers must be record types.
1043 if (!BaseType->isRecordType()) {
1044 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1045 return 0;
1046 }
1047
1048 // C++ [class.union]p1:
1049 // A union shall not be used as a base class.
1050 if (BaseType->isUnionType()) {
1051 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1052 return 0;
1053 }
1054
1055 // C++ [class.derived]p2:
1056 // The class-name in a base-specifier shall not be an incompletely
1057 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001058 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001059 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001060 << SpecifierRange)) {
1061 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001062 return 0;
John McCall572fc622010-08-17 07:23:57 +00001063 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001064
Eli Friedman1d954f62009-08-15 21:55:26 +00001065 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001066 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001067 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001068 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001069 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001070 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1071 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001072
Anders Carlsson1d209272011-03-25 14:55:14 +00001073 // C++ [class]p3:
1074 // If a class is marked final and it appears as a base-type-specifier in
1075 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001076 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001077 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1078 << CXXBaseDecl->getDeclName();
1079 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1080 << CXXBaseDecl->getDeclName();
1081 return 0;
1082 }
1083
John McCall572fc622010-08-17 07:23:57 +00001084 if (BaseDecl->isInvalidDecl())
1085 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001086
1087 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001088 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001089 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001090 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001091}
1092
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001093/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1094/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001095/// example:
1096/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001097/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001098BaseResult
John McCalld226f652010-08-21 09:40:31 +00001099Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001100 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001101 ParsedType basetype, SourceLocation BaseLoc,
1102 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001103 if (!classdecl)
1104 return true;
1105
Douglas Gregor40808ce2009-03-09 23:48:35 +00001106 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001107 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001108 if (!Class)
1109 return true;
1110
Nick Lewycky56062202010-07-26 16:56:01 +00001111 TypeSourceInfo *TInfo = 0;
1112 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001113
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001114 if (EllipsisLoc.isInvalid() &&
1115 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001116 UPPC_BaseType))
1117 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001118
Douglas Gregor2943aed2009-03-03 04:44:36 +00001119 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001120 Virtual, Access, TInfo,
1121 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001122 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Douglas Gregor2943aed2009-03-03 04:44:36 +00001124 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001125}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001126
Douglas Gregor2943aed2009-03-03 04:44:36 +00001127/// \brief Performs the actual work of attaching the given base class
1128/// specifiers to a C++ class.
1129bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1130 unsigned NumBases) {
1131 if (NumBases == 0)
1132 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001133
1134 // Used to keep track of which base types we have already seen, so
1135 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001136 // that the key is always the unqualified canonical type of the base
1137 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001138 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1139
1140 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001141 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001143 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001144 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001145 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001146 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001147 if (KnownBaseTypes[NewBaseType]) {
1148 // C++ [class.mi]p3:
1149 // A class shall not be specified as a direct base class of a
1150 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001151 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001152 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001153 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001154 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001155
1156 // Delete the duplicate base class specifier; we're going to
1157 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001158 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001159
1160 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001161 } else {
1162 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001163 KnownBaseTypes[NewBaseType] = Bases[idx];
1164 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001165 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001166 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1167 if (RD->hasAttr<WeakAttr>())
1168 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001169 }
1170 }
1171
1172 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001173 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001174
1175 // Delete the remaining (good) base class specifiers, since their
1176 // data has been copied into the CXXRecordDecl.
1177 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001178 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001179
1180 return Invalid;
1181}
1182
1183/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1184/// class, after checking whether there are any duplicate base
1185/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001186void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001187 unsigned NumBases) {
1188 if (!ClassDecl || !Bases || !NumBases)
1189 return;
1190
1191 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001192 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001193 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001194}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001195
John McCall3cb0ebd2010-03-10 03:28:59 +00001196static CXXRecordDecl *GetClassForType(QualType T) {
1197 if (const RecordType *RT = T->getAs<RecordType>())
1198 return cast<CXXRecordDecl>(RT->getDecl());
1199 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1200 return ICT->getDecl();
1201 else
1202 return 0;
1203}
1204
Douglas Gregora8f32e02009-10-06 17:59:45 +00001205/// \brief Determine whether the type \p Derived is a C++ class that is
1206/// derived from the type \p Base.
1207bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1208 if (!getLangOptions().CPlusPlus)
1209 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001210
1211 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1212 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001213 return false;
1214
John McCall3cb0ebd2010-03-10 03:28:59 +00001215 CXXRecordDecl *BaseRD = GetClassForType(Base);
1216 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001217 return false;
1218
John McCall86ff3082010-02-04 22:26:26 +00001219 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1220 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001221}
1222
1223/// \brief Determine whether the type \p Derived is a C++ class that is
1224/// derived from the type \p Base.
1225bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1226 if (!getLangOptions().CPlusPlus)
1227 return false;
1228
John McCall3cb0ebd2010-03-10 03:28:59 +00001229 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1230 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001231 return false;
1232
John McCall3cb0ebd2010-03-10 03:28:59 +00001233 CXXRecordDecl *BaseRD = GetClassForType(Base);
1234 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001235 return false;
1236
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1238}
1239
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001240void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001241 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001242 assert(BasePathArray.empty() && "Base path array must be empty!");
1243 assert(Paths.isRecordingPaths() && "Must record paths!");
1244
1245 const CXXBasePath &Path = Paths.front();
1246
1247 // We first go backward and check if we have a virtual base.
1248 // FIXME: It would be better if CXXBasePath had the base specifier for
1249 // the nearest virtual base.
1250 unsigned Start = 0;
1251 for (unsigned I = Path.size(); I != 0; --I) {
1252 if (Path[I - 1].Base->isVirtual()) {
1253 Start = I - 1;
1254 break;
1255 }
1256 }
1257
1258 // Now add all bases.
1259 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001260 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001261}
1262
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001263/// \brief Determine whether the given base path includes a virtual
1264/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001265bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1266 for (CXXCastPath::const_iterator B = BasePath.begin(),
1267 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001268 B != BEnd; ++B)
1269 if ((*B)->isVirtual())
1270 return true;
1271
1272 return false;
1273}
1274
Douglas Gregora8f32e02009-10-06 17:59:45 +00001275/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1276/// conversion (where Derived and Base are class types) is
1277/// well-formed, meaning that the conversion is unambiguous (and
1278/// that all of the base classes are accessible). Returns true
1279/// and emits a diagnostic if the code is ill-formed, returns false
1280/// otherwise. Loc is the location where this routine should point to
1281/// if there is an error, and Range is the source range to highlight
1282/// if there is an error.
1283bool
1284Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001285 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001286 unsigned AmbigiousBaseConvID,
1287 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001288 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001289 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001290 // First, determine whether the path from Derived to Base is
1291 // ambiguous. This is slightly more expensive than checking whether
1292 // the Derived to Base conversion exists, because here we need to
1293 // explore multiple paths to determine if there is an ambiguity.
1294 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1295 /*DetectVirtual=*/false);
1296 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1297 assert(DerivationOkay &&
1298 "Can only be used with a derived-to-base conversion");
1299 (void)DerivationOkay;
1300
1301 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001302 if (InaccessibleBaseID) {
1303 // Check that the base class can be accessed.
1304 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1305 InaccessibleBaseID)) {
1306 case AR_inaccessible:
1307 return true;
1308 case AR_accessible:
1309 case AR_dependent:
1310 case AR_delayed:
1311 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001312 }
John McCall6b2accb2010-02-10 09:31:12 +00001313 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001314
1315 // Build a base path if necessary.
1316 if (BasePath)
1317 BuildBasePathArray(Paths, *BasePath);
1318 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001319 }
1320
1321 // We know that the derived-to-base conversion is ambiguous, and
1322 // we're going to produce a diagnostic. Perform the derived-to-base
1323 // search just one more time to compute all of the possible paths so
1324 // that we can print them out. This is more expensive than any of
1325 // the previous derived-to-base checks we've done, but at this point
1326 // performance isn't as much of an issue.
1327 Paths.clear();
1328 Paths.setRecordingPaths(true);
1329 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1330 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1331 (void)StillOkay;
1332
1333 // Build up a textual representation of the ambiguous paths, e.g.,
1334 // D -> B -> A, that will be used to illustrate the ambiguous
1335 // conversions in the diagnostic. We only print one of the paths
1336 // to each base class subobject.
1337 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1338
1339 Diag(Loc, AmbigiousBaseConvID)
1340 << Derived << Base << PathDisplayStr << Range << Name;
1341 return true;
1342}
1343
1344bool
1345Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001346 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001347 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001348 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001349 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001350 IgnoreAccess ? 0
1351 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001352 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001353 Loc, Range, DeclarationName(),
1354 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001355}
1356
1357
1358/// @brief Builds a string representing ambiguous paths from a
1359/// specific derived class to different subobjects of the same base
1360/// class.
1361///
1362/// This function builds a string that can be used in error messages
1363/// to show the different paths that one can take through the
1364/// inheritance hierarchy to go from the derived class to different
1365/// subobjects of a base class. The result looks something like this:
1366/// @code
1367/// struct D -> struct B -> struct A
1368/// struct D -> struct C -> struct A
1369/// @endcode
1370std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1371 std::string PathDisplayStr;
1372 std::set<unsigned> DisplayedPaths;
1373 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1374 Path != Paths.end(); ++Path) {
1375 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1376 // We haven't displayed a path to this particular base
1377 // class subobject yet.
1378 PathDisplayStr += "\n ";
1379 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1380 for (CXXBasePath::const_iterator Element = Path->begin();
1381 Element != Path->end(); ++Element)
1382 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1383 }
1384 }
1385
1386 return PathDisplayStr;
1387}
1388
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001389//===----------------------------------------------------------------------===//
1390// C++ class member Handling
1391//===----------------------------------------------------------------------===//
1392
Abramo Bagnara6206d532010-06-05 05:09:32 +00001393/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001394bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1395 SourceLocation ASLoc,
1396 SourceLocation ColonLoc,
1397 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001398 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001399 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001400 ASLoc, ColonLoc);
1401 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001402 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001403}
1404
Anders Carlsson9e682d92011-01-20 05:57:14 +00001405/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001406void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001407 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001408 if (!MD || !MD->isVirtual())
1409 return;
1410
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001411 if (MD->isDependentContext())
1412 return;
1413
Anders Carlsson9e682d92011-01-20 05:57:14 +00001414 // C++0x [class.virtual]p3:
1415 // If a virtual function is marked with the virt-specifier override and does
1416 // not override a member function of a base class,
1417 // the program is ill-formed.
1418 bool HasOverriddenMethods =
1419 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001420 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001421 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001422 diag::err_function_marked_override_not_overriding)
1423 << MD->getDeclName();
1424 return;
1425 }
1426}
1427
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001428/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1429/// function overrides a virtual member function marked 'final', according to
1430/// C++0x [class.virtual]p3.
1431bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1432 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001433 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001434 return false;
1435
1436 Diag(New->getLocation(), diag::err_final_function_overridden)
1437 << New->getDeclName();
1438 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1439 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001440}
1441
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001442/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1443/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001444/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1445/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1446/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001447Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001448Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001449 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001450 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001451 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001452 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001453 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1454 DeclarationName Name = NameInfo.getName();
1455 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001456
1457 // For anonymous bitfields, the location should point to the type.
1458 if (Loc.isInvalid())
1459 Loc = D.getSourceRange().getBegin();
1460
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001461 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001462
John McCall4bde1e12010-06-04 08:34:12 +00001463 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001464 assert(!DS.isFriendSpecified());
1465
Richard Smith1ab0d902011-06-25 02:28:38 +00001466 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001467
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001468 // C++ 9.2p6: A member shall not be declared to have automatic storage
1469 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001470 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1471 // data members and cannot be applied to names declared const or static,
1472 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001473 switch (DS.getStorageClassSpec()) {
1474 case DeclSpec::SCS_unspecified:
1475 case DeclSpec::SCS_typedef:
1476 case DeclSpec::SCS_static:
1477 // FALL THROUGH.
1478 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001479 case DeclSpec::SCS_mutable:
1480 if (isFunc) {
1481 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001482 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001483 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001484 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Sebastian Redla11f42f2008-11-17 23:24:37 +00001486 // FIXME: It would be nicer if the keyword was ignored only for this
1487 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001488 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001489 }
1490 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001491 default:
1492 if (DS.getStorageClassSpecLoc().isValid())
1493 Diag(DS.getStorageClassSpecLoc(),
1494 diag::err_storageclass_invalid_for_member);
1495 else
1496 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1497 D.getMutableDeclSpec().ClearStorageClassSpecs();
1498 }
1499
Sebastian Redl669d5d72008-11-14 23:42:31 +00001500 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1501 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001502 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001503
1504 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001505 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001506 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001507
1508 // Data members must have identifiers for names.
1509 if (Name.getNameKind() != DeclarationName::Identifier) {
1510 Diag(Loc, diag::err_bad_variable_name)
1511 << Name;
1512 return 0;
1513 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001514
Douglas Gregorf2503652011-09-21 14:40:46 +00001515 IdentifierInfo *II = Name.getAsIdentifierInfo();
1516
1517 // Member field could not be with "template" keyword.
1518 // So TemplateParameterLists should be empty in this case.
1519 if (TemplateParameterLists.size()) {
1520 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1521 if (TemplateParams->size()) {
1522 // There is no such thing as a member field template.
1523 Diag(D.getIdentifierLoc(), diag::err_template_member)
1524 << II
1525 << SourceRange(TemplateParams->getTemplateLoc(),
1526 TemplateParams->getRAngleLoc());
1527 } else {
1528 // There is an extraneous 'template<>' for this member.
1529 Diag(TemplateParams->getTemplateLoc(),
1530 diag::err_template_member_noparams)
1531 << II
1532 << SourceRange(TemplateParams->getTemplateLoc(),
1533 TemplateParams->getRAngleLoc());
1534 }
1535 return 0;
1536 }
1537
Douglas Gregor922fff22010-10-13 22:19:53 +00001538 if (SS.isSet() && !SS.isInvalid()) {
1539 // The user provided a superfluous scope specifier inside a class
1540 // definition:
1541 //
1542 // class X {
1543 // int X::member;
1544 // };
1545 DeclContext *DC = 0;
1546 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1547 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001548 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001549 else
1550 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1551 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001552
Douglas Gregor922fff22010-10-13 22:19:53 +00001553 SS.clear();
1554 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001555
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001556 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001557 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001558 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001559 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001560 assert(!HasDeferredInit);
1561
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001562 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001563 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001564 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001565 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001566
1567 // Non-instance-fields can't have a bitfield.
1568 if (BitWidth) {
1569 if (Member->isInvalidDecl()) {
1570 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001571 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001572 // C++ 9.6p3: A bit-field shall not be a static member.
1573 // "static member 'A' cannot be a bit-field"
1574 Diag(Loc, diag::err_static_not_bitfield)
1575 << Name << BitWidth->getSourceRange();
1576 } else if (isa<TypedefDecl>(Member)) {
1577 // "typedef member 'x' cannot be a bit-field"
1578 Diag(Loc, diag::err_typedef_not_bitfield)
1579 << Name << BitWidth->getSourceRange();
1580 } else {
1581 // A function typedef ("typedef int f(); f a;").
1582 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1583 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001584 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001585 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Chris Lattner8b963ef2009-03-05 23:01:03 +00001588 BitWidth = 0;
1589 Member->setInvalidDecl();
1590 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001591
1592 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Douglas Gregor37b372b2009-08-20 22:52:58 +00001594 // If we have declared a member function template, set the access of the
1595 // templated declaration as well.
1596 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1597 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001598 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001599
Anders Carlssonaae5af22011-01-20 04:34:22 +00001600 if (VS.isOverrideSpecified()) {
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 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001606 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001607 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001608 }
1609 if (VS.isFinalSpecified()) {
1610 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1611 if (!MD || !MD->isVirtual()) {
1612 Diag(Member->getLocStart(),
1613 diag::override_keyword_only_allowed_on_virtual_member_functions)
1614 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001615 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001616 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001617 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001618
Douglas Gregorf5251602011-03-08 17:10:18 +00001619 if (VS.getLastLocation().isValid()) {
1620 // Update the end location of a method that has a virt-specifiers.
1621 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1622 MD->setRangeEnd(VS.getLastLocation());
1623 }
1624
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001625 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001626
Douglas Gregor10bd3682008-11-17 22:58:34 +00001627 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001628
John McCallb25b2952011-02-15 07:12:36 +00001629 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001630 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001631 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001632}
1633
Richard Smith7a614d82011-06-11 17:19:42 +00001634/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001635/// in-class initializer for a non-static C++ class member, and after
1636/// instantiating an in-class initializer in a class template. Such actions
1637/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001638void
1639Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1640 Expr *InitExpr) {
1641 FieldDecl *FD = cast<FieldDecl>(D);
1642
1643 if (!InitExpr) {
1644 FD->setInvalidDecl();
1645 FD->removeInClassInitializer();
1646 return;
1647 }
1648
Peter Collingbournefef21892011-10-23 18:59:44 +00001649 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1650 FD->setInvalidDecl();
1651 FD->removeInClassInitializer();
1652 return;
1653 }
1654
Richard Smith7a614d82011-06-11 17:19:42 +00001655 ExprResult Init = InitExpr;
1656 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1657 // FIXME: if there is no EqualLoc, this is list-initialization.
1658 Init = PerformCopyInitialization(
1659 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1660 if (Init.isInvalid()) {
1661 FD->setInvalidDecl();
1662 return;
1663 }
1664
1665 CheckImplicitConversions(Init.get(), EqualLoc);
1666 }
1667
1668 // C++0x [class.base.init]p7:
1669 // The initialization of each base and member constitutes a
1670 // full-expression.
1671 Init = MaybeCreateExprWithCleanups(Init);
1672 if (Init.isInvalid()) {
1673 FD->setInvalidDecl();
1674 return;
1675 }
1676
1677 InitExpr = Init.release();
1678
1679 FD->setInClassInitializer(InitExpr);
1680}
1681
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001682/// \brief Find the direct and/or virtual base specifiers that
1683/// correspond to the given base type, for use in base initialization
1684/// within a constructor.
1685static bool FindBaseInitializer(Sema &SemaRef,
1686 CXXRecordDecl *ClassDecl,
1687 QualType BaseType,
1688 const CXXBaseSpecifier *&DirectBaseSpec,
1689 const CXXBaseSpecifier *&VirtualBaseSpec) {
1690 // First, check for a direct base class.
1691 DirectBaseSpec = 0;
1692 for (CXXRecordDecl::base_class_const_iterator Base
1693 = ClassDecl->bases_begin();
1694 Base != ClassDecl->bases_end(); ++Base) {
1695 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1696 // We found a direct base of this type. That's what we're
1697 // initializing.
1698 DirectBaseSpec = &*Base;
1699 break;
1700 }
1701 }
1702
1703 // Check for a virtual base class.
1704 // FIXME: We might be able to short-circuit this if we know in advance that
1705 // there are no virtual bases.
1706 VirtualBaseSpec = 0;
1707 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1708 // We haven't found a base yet; search the class hierarchy for a
1709 // virtual base class.
1710 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1711 /*DetectVirtual=*/false);
1712 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1713 BaseType, Paths)) {
1714 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1715 Path != Paths.end(); ++Path) {
1716 if (Path->back().Base->isVirtual()) {
1717 VirtualBaseSpec = Path->back().Base;
1718 break;
1719 }
1720 }
1721 }
1722 }
1723
1724 return DirectBaseSpec || VirtualBaseSpec;
1725}
1726
Sebastian Redl6df65482011-09-24 17:48:25 +00001727/// \brief Handle a C++ member initializer using braced-init-list syntax.
1728MemInitResult
1729Sema::ActOnMemInitializer(Decl *ConstructorD,
1730 Scope *S,
1731 CXXScopeSpec &SS,
1732 IdentifierInfo *MemberOrBase,
1733 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001734 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001735 SourceLocation IdLoc,
1736 Expr *InitList,
1737 SourceLocation EllipsisLoc) {
1738 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001739 DS, IdLoc, MultiInitializer(InitList),
1740 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001741}
1742
1743/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001744MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001745Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001746 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001747 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001748 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001749 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001750 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001751 SourceLocation IdLoc,
1752 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001753 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001754 SourceLocation RParenLoc,
1755 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001756 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001757 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1758 NumArgs, RParenLoc),
Sebastian Redl6df65482011-09-24 17:48:25 +00001759 EllipsisLoc);
1760}
1761
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001762namespace {
1763
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001764// Callback to only accept typo corrections that can be a valid C++ member
1765// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001766class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1767 public:
1768 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1769 : ClassDecl(ClassDecl) {}
1770
1771 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1772 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1773 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1774 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1775 else
1776 return isa<TypeDecl>(ND);
1777 }
1778 return false;
1779 }
1780
1781 private:
1782 CXXRecordDecl *ClassDecl;
1783};
1784
1785}
1786
Sebastian Redl6df65482011-09-24 17:48:25 +00001787/// \brief Handle a C++ member initializer.
1788MemInitResult
1789Sema::BuildMemInitializer(Decl *ConstructorD,
1790 Scope *S,
1791 CXXScopeSpec &SS,
1792 IdentifierInfo *MemberOrBase,
1793 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001794 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001795 SourceLocation IdLoc,
1796 const MultiInitializer &Args,
1797 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001798 if (!ConstructorD)
1799 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001801 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001802
1803 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001804 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001805 if (!Constructor) {
1806 // The user wrote a constructor initializer on a function that is
1807 // not a C++ constructor. Ignore the error for now, because we may
1808 // have more member initializers coming; we'll diagnose it just
1809 // once in ActOnMemInitializers.
1810 return true;
1811 }
1812
1813 CXXRecordDecl *ClassDecl = Constructor->getParent();
1814
1815 // C++ [class.base.init]p2:
1816 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001817 // constructor's class and, if not found in that scope, are looked
1818 // up in the scope containing the constructor's definition.
1819 // [Note: if the constructor's class contains a member with the
1820 // same name as a direct or virtual base class of the class, a
1821 // mem-initializer-id naming the member or base class and composed
1822 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001823 // mem-initializer-id for the hidden base class may be specified
1824 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001825 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001826 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001827 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001828 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001829 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001830 ValueDecl *Member;
1831 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1832 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001833 if (EllipsisLoc.isValid())
1834 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001835 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1836
1837 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001838 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001839 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001840 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001841 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001842 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001843 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001844
1845 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001846 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001847 } else if (DS.getTypeSpecType() == TST_decltype) {
1848 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001849 } else {
1850 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1851 LookupParsedName(R, S, &SS);
1852
1853 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1854 if (!TyD) {
1855 if (R.isAmbiguous()) return true;
1856
John McCallfd225442010-04-09 19:01:14 +00001857 // We don't want access-control diagnostics here.
1858 R.suppressDiagnostics();
1859
Douglas Gregor7a886e12010-01-19 06:46:48 +00001860 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1861 bool NotUnknownSpecialization = false;
1862 DeclContext *DC = computeDeclContext(SS, false);
1863 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1864 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1865
1866 if (!NotUnknownSpecialization) {
1867 // When the scope specifier can refer to a member of an unknown
1868 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001869 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1870 SS.getWithLocInContext(Context),
1871 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001872 if (BaseType.isNull())
1873 return true;
1874
Douglas Gregor7a886e12010-01-19 06:46:48 +00001875 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001876 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001877 }
1878 }
1879
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001880 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001881 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001882 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001883 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001884 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001885 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001886 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1887 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1888 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001889 // We have found a non-static data member with a similar
1890 // name to what was typed; complain and initialize that
1891 // member.
1892 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1893 << MemberOrBase << true << CorrectedQuotedStr
1894 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1895 Diag(Member->getLocation(), diag::note_previous_decl)
1896 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001897
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001898 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001899 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001900 const CXXBaseSpecifier *DirectBaseSpec;
1901 const CXXBaseSpecifier *VirtualBaseSpec;
1902 if (FindBaseInitializer(*this, ClassDecl,
1903 Context.getTypeDeclType(Type),
1904 DirectBaseSpec, VirtualBaseSpec)) {
1905 // We have found a direct or virtual base class with a
1906 // similar name to what was typed; complain and initialize
1907 // that base class.
1908 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001909 << MemberOrBase << false << CorrectedQuotedStr
1910 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001911
1912 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1913 : VirtualBaseSpec;
1914 Diag(BaseSpec->getSourceRange().getBegin(),
1915 diag::note_base_class_specified_here)
1916 << BaseSpec->getType()
1917 << BaseSpec->getSourceRange();
1918
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001919 TyD = Type;
1920 }
1921 }
1922 }
1923
Douglas Gregor7a886e12010-01-19 06:46:48 +00001924 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001925 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001926 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001927 return true;
1928 }
John McCall2b194412009-12-21 10:41:20 +00001929 }
1930
Douglas Gregor7a886e12010-01-19 06:46:48 +00001931 if (BaseType.isNull()) {
1932 BaseType = Context.getTypeDeclType(TyD);
1933 if (SS.isSet()) {
1934 NestedNameSpecifier *Qualifier =
1935 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001936
Douglas Gregor7a886e12010-01-19 06:46:48 +00001937 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001938 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001939 }
John McCall2b194412009-12-21 10:41:20 +00001940 }
1941 }
Mike Stump1eb44332009-09-09 15:08:12 +00001942
John McCalla93c9342009-12-07 02:54:59 +00001943 if (!TInfo)
1944 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001945
Sebastian Redl6df65482011-09-24 17:48:25 +00001946 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001947}
1948
Chandler Carruth81c64772011-09-03 01:14:15 +00001949/// Checks a member initializer expression for cases where reference (or
1950/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001951static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1952 Expr *Init,
1953 SourceLocation IdLoc) {
1954 QualType MemberTy = Member->getType();
1955
1956 // We only handle pointers and references currently.
1957 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1958 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1959 return;
1960
1961 const bool IsPointer = MemberTy->isPointerType();
1962 if (IsPointer) {
1963 if (const UnaryOperator *Op
1964 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1965 // The only case we're worried about with pointers requires taking the
1966 // address.
1967 if (Op->getOpcode() != UO_AddrOf)
1968 return;
1969
1970 Init = Op->getSubExpr();
1971 } else {
1972 // We only handle address-of expression initializers for pointers.
1973 return;
1974 }
1975 }
1976
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001977 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1978 // Taking the address of a temporary will be diagnosed as a hard error.
1979 if (IsPointer)
1980 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001981
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001982 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1983 << Member << Init->getSourceRange();
1984 } else if (const DeclRefExpr *DRE
1985 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1986 // We only warn when referring to a non-reference parameter declaration.
1987 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1988 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001989 return;
1990
1991 S.Diag(Init->getExprLoc(),
1992 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1993 : diag::warn_bind_ref_member_to_parameter)
1994 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001995 } else {
1996 // Other initializers are fine.
1997 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001998 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001999
2000 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2001 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002002}
2003
John McCallb4190042009-11-04 23:02:40 +00002004/// Checks an initializer expression for use of uninitialized fields, such as
2005/// containing the field that is being initialized. Returns true if there is an
2006/// uninitialized field was used an updates the SourceLocation parameter; false
2007/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002008static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002009 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002010 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002011 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2012
Nick Lewycky43ad1822010-06-15 07:32:55 +00002013 if (isa<CallExpr>(S)) {
2014 // Do not descend into function calls or constructors, as the use
2015 // of an uninitialized field may be valid. One would have to inspect
2016 // the contents of the function/ctor to determine if it is safe or not.
2017 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2018 // may be safe, depending on what the function/ctor does.
2019 return false;
2020 }
2021 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2022 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002023
2024 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2025 // The member expression points to a static data member.
2026 assert(VD->isStaticDataMember() &&
2027 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002028 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002029 return false;
2030 }
2031
2032 if (isa<EnumConstantDecl>(RhsField)) {
2033 // The member expression points to an enum.
2034 return false;
2035 }
2036
John McCallb4190042009-11-04 23:02:40 +00002037 if (RhsField == LhsField) {
2038 // Initializing a field with itself. Throw a warning.
2039 // But wait; there are exceptions!
2040 // Exception #1: The field may not belong to this record.
2041 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002042 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002043 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2044 // Even though the field matches, it does not belong to this record.
2045 return false;
2046 }
2047 // None of the exceptions triggered; return true to indicate an
2048 // uninitialized field was used.
2049 *L = ME->getMemberLoc();
2050 return true;
2051 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002052 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002053 // sizeof/alignof doesn't reference contents, do not warn.
2054 return false;
2055 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2056 // address-of doesn't reference contents (the pointer may be dereferenced
2057 // in the same expression but it would be rare; and weird).
2058 if (UOE->getOpcode() == UO_AddrOf)
2059 return false;
John McCallb4190042009-11-04 23:02:40 +00002060 }
John McCall7502c1d2011-02-13 04:07:26 +00002061 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002062 if (!*it) {
2063 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002064 continue;
2065 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002066 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2067 return true;
John McCallb4190042009-11-04 23:02:40 +00002068 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002069 return false;
John McCallb4190042009-11-04 23:02:40 +00002070}
2071
John McCallf312b1e2010-08-26 23:41:50 +00002072MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002073Sema::BuildMemberInitializer(ValueDecl *Member,
2074 const MultiInitializer &Args,
2075 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002076 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2077 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2078 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002079 "Member must be a FieldDecl or IndirectFieldDecl");
2080
Peter Collingbournefef21892011-10-23 18:59:44 +00002081 if (Args.DiagnoseUnexpandedParameterPack(*this))
2082 return true;
2083
Douglas Gregor464b2f02010-11-05 22:21:31 +00002084 if (Member->isInvalidDecl())
2085 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002086
John McCallb4190042009-11-04 23:02:40 +00002087 // Diagnose value-uses of fields to initialize themselves, e.g.
2088 // foo(foo)
2089 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002090 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00002091 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2092 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002093 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002094 Expr *Arg = *I;
2095 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2096 Arg = DIE->getInit();
2097 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002098 // FIXME: Return true in the case when other fields are used before being
2099 // uninitialized. For example, let this field be the i'th field. When
2100 // initializing the i'th field, throw a warning if any of the >= i'th
2101 // fields are used, as they are not yet initialized.
2102 // Right now we are only handling the case where the i'th field uses
2103 // itself in its initializer.
2104 Diag(L, diag::warn_field_is_uninit);
2105 }
2106 }
2107
Sebastian Redl6df65482011-09-24 17:48:25 +00002108 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002109
Chandler Carruth894aed92010-12-06 09:23:57 +00002110 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002111 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002112 // Can't check initialization for a member of dependent type or when
2113 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002114 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002115
John McCallf85e1932011-06-15 23:02:42 +00002116 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002117 } else {
2118 // Initialize the member.
2119 InitializedEntity MemberEntity =
2120 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2121 : InitializedEntity::InitializeMember(IndirectMember, 0);
2122 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002123 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2124 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002125
Sebastian Redl6df65482011-09-24 17:48:25 +00002126 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002127 if (MemberInit.isInvalid())
2128 return true;
2129
Sebastian Redl6df65482011-09-24 17:48:25 +00002130 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002131
2132 // C++0x [class.base.init]p7:
2133 // The initialization of each base and member constitutes a
2134 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002135 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002136 if (MemberInit.isInvalid())
2137 return true;
2138
2139 // If we are in a dependent context, template instantiation will
2140 // perform this type-checking again. Just save the arguments that we
2141 // received in a ParenListExpr.
2142 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2143 // of the information that we have about the member
2144 // initializer. However, deconstructing the ASTs is a dicey process,
2145 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002146 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002147 Init = Args.CreateInitExpr(Context,
2148 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002149 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002150 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002151 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2152 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002153 }
2154
Chandler Carruth894aed92010-12-06 09:23:57 +00002155 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002156 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002157 IdLoc, Args.getStartLoc(),
2158 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002159 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002160 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002161 IdLoc, Args.getStartLoc(),
2162 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002163 }
Eli Friedman59c04372009-07-29 19:44:27 +00002164}
2165
John McCallf312b1e2010-08-26 23:41:50 +00002166MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002167Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002168 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002169 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002170 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002171 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002172 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002173 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002174 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002175
Sean Hunt41717662011-02-26 19:13:13 +00002176 // Initialize the object.
2177 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2178 QualType(ClassDecl->getTypeForDecl(), 0));
2179 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002180 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2181 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002182
Sebastian Redl6df65482011-09-24 17:48:25 +00002183 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002184 if (DelegationInit.isInvalid())
2185 return true;
2186
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002187 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2188 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002189
Sebastian Redl6df65482011-09-24 17:48:25 +00002190 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002191
2192 // C++0x [class.base.init]p7:
2193 // The initialization of each base and member constitutes a
2194 // full-expression.
2195 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2196 if (DelegationInit.isInvalid())
2197 return true;
2198
Douglas Gregor76852c22011-11-01 01:16:03 +00002199 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Sean Hunt41717662011-02-26 19:13:13 +00002200 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002201 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002202}
2203
2204MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002205Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002206 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002207 CXXRecordDecl *ClassDecl,
2208 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002209 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002210
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002211 SourceLocation BaseLoc
2212 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002213
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002214 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2215 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2216 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2217
2218 // C++ [class.base.init]p2:
2219 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002220 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002221 // of that class, the mem-initializer is ill-formed. A
2222 // mem-initializer-list can initialize a base class using any
2223 // name that denotes that base class type.
2224 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2225
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002226 if (EllipsisLoc.isValid()) {
2227 // This is a pack expansion.
2228 if (!BaseType->containsUnexpandedParameterPack()) {
2229 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002230 << SourceRange(BaseLoc, Args.getEndLoc());
2231
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002232 EllipsisLoc = SourceLocation();
2233 }
2234 } else {
2235 // Check for any unexpanded parameter packs.
2236 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2237 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002238
2239 if (Args.DiagnoseUnexpandedParameterPack(*this))
2240 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002241 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002242
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002243 // Check for direct and virtual base classes.
2244 const CXXBaseSpecifier *DirectBaseSpec = 0;
2245 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2246 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002247 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2248 BaseType))
Douglas Gregor76852c22011-11-01 01:16:03 +00002249 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002250
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002251 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2252 VirtualBaseSpec);
2253
2254 // C++ [base.class.init]p2:
2255 // Unless the mem-initializer-id names a nonstatic data member of the
2256 // constructor's class or a direct or virtual base of that class, the
2257 // mem-initializer is ill-formed.
2258 if (!DirectBaseSpec && !VirtualBaseSpec) {
2259 // If the class has any dependent bases, then it's possible that
2260 // one of those types will resolve to the same type as
2261 // BaseType. Therefore, just treat this as a dependent base
2262 // class initialization. FIXME: Should we try to check the
2263 // initialization anyway? It seems odd.
2264 if (ClassDecl->hasAnyDependentBases())
2265 Dependent = true;
2266 else
2267 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2268 << BaseType << Context.getTypeDeclType(ClassDecl)
2269 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2270 }
2271 }
2272
2273 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002274 // Can't check initialization for a base of dependent type or when
2275 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002276 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002277
John McCallf85e1932011-06-15 23:02:42 +00002278 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Sebastian Redl6df65482011-09-24 17:48:25 +00002280 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2281 /*IsVirtual=*/false,
2282 Args.getStartLoc(), BaseInit,
2283 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002284 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002285
2286 // C++ [base.class.init]p2:
2287 // If a mem-initializer-id is ambiguous because it designates both
2288 // a direct non-virtual base class and an inherited virtual base
2289 // class, the mem-initializer is ill-formed.
2290 if (DirectBaseSpec && VirtualBaseSpec)
2291 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002292 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002293
2294 CXXBaseSpecifier *BaseSpec
2295 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2296 if (!BaseSpec)
2297 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2298
2299 // Initialize the base.
2300 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002301 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002302 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002303 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2304 Args.getEndLoc());
2305
2306 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002307 if (BaseInit.isInvalid())
2308 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002309
Sebastian Redl6df65482011-09-24 17:48:25 +00002310 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2311
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002312 // C++0x [class.base.init]p7:
2313 // The initialization of each base and member constitutes a
2314 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002315 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002316 if (BaseInit.isInvalid())
2317 return true;
2318
2319 // If we are in a dependent context, template instantiation will
2320 // perform this type-checking again. Just save the arguments that we
2321 // received in a ParenListExpr.
2322 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2323 // of the information that we have about the base
2324 // initializer. However, deconstructing the ASTs is a dicey process,
2325 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002326 if (CurContext->isDependentContext())
2327 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002328
Sean Huntcbb67482011-01-08 20:30:50 +00002329 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002330 BaseSpec->isVirtual(),
2331 Args.getStartLoc(),
2332 BaseInit.takeAs<Expr>(),
2333 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002334}
2335
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002336// Create a static_cast\<T&&>(expr).
2337static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2338 QualType ExprType = E->getType();
2339 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2340 SourceLocation ExprLoc = E->getLocStart();
2341 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2342 TargetType, ExprLoc);
2343
2344 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2345 SourceRange(ExprLoc, ExprLoc),
2346 E->getSourceRange()).take();
2347}
2348
Anders Carlssone5ef7402010-04-23 03:10:23 +00002349/// ImplicitInitializerKind - How an implicit base or member initializer should
2350/// initialize its base or member.
2351enum ImplicitInitializerKind {
2352 IIK_Default,
2353 IIK_Copy,
2354 IIK_Move
2355};
2356
Anders Carlssondefefd22010-04-23 02:00:02 +00002357static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002358BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002359 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002360 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002361 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002362 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002363 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002364 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2365 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002366
John McCall60d7b3a2010-08-24 06:29:42 +00002367 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002368
2369 switch (ImplicitInitKind) {
2370 case IIK_Default: {
2371 InitializationKind InitKind
2372 = InitializationKind::CreateDefault(Constructor->getLocation());
2373 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2374 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002375 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002376 break;
2377 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002378
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002379 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002380 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002381 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002382 ParmVarDecl *Param = Constructor->getParamDecl(0);
2383 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002384
2385 SemaRef.MarkDeclarationReferenced(Constructor->getLocation(), Param);
2386
Anders Carlssone5ef7402010-04-23 03:10:23 +00002387 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002388 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2389 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002390 Constructor->getLocation(), ParamType,
2391 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002392
Anders Carlssonc7957502010-04-24 22:02:54 +00002393 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002394 QualType ArgTy =
2395 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2396 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002397
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002398 if (Moving) {
2399 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2400 }
2401
John McCallf871d0c2010-08-07 06:22:56 +00002402 CXXCastPath BasePath;
2403 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002404 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2405 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002406 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002407 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002408
Anders Carlssone5ef7402010-04-23 03:10:23 +00002409 InitializationKind InitKind
2410 = InitializationKind::CreateDirect(Constructor->getLocation(),
2411 SourceLocation(), SourceLocation());
2412 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2413 &CopyCtorArg, 1);
2414 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002415 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002416 break;
2417 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002418 }
John McCall9ae2f072010-08-23 23:25:46 +00002419
Douglas Gregor53c374f2010-12-07 00:41:46 +00002420 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002421 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002422 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002423
Anders Carlssondefefd22010-04-23 02:00:02 +00002424 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002425 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002426 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2427 SourceLocation()),
2428 BaseSpec->isVirtual(),
2429 SourceLocation(),
2430 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002431 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002432 SourceLocation());
2433
Anders Carlssondefefd22010-04-23 02:00:02 +00002434 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002435}
2436
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002437static bool RefersToRValueRef(Expr *MemRef) {
2438 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2439 return Referenced->getType()->isRValueReferenceType();
2440}
2441
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002442static bool
2443BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002444 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002445 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002446 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002447 if (Field->isInvalidDecl())
2448 return true;
2449
Chandler Carruthf186b542010-06-29 23:50:44 +00002450 SourceLocation Loc = Constructor->getLocation();
2451
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002452 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2453 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002454 ParmVarDecl *Param = Constructor->getParamDecl(0);
2455 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002456
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002457 SemaRef.MarkDeclarationReferenced(Constructor->getLocation(), Param);
2458
John McCallb77115d2011-06-17 00:18:42 +00002459 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002460 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2461 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002462
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002463 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002464 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2465 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002466 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002467
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002468 if (Moving) {
2469 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2470 }
2471
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002472 // Build a reference to this field within the parameter.
2473 CXXScopeSpec SS;
2474 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2475 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002476 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2477 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002478 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002479 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002480 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002481 ParamType, Loc,
2482 /*IsArrow=*/false,
2483 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002484 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002485 /*FirstQualifierInScope=*/0,
2486 MemberLookup,
2487 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002488 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002489 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002490
2491 // C++11 [class.copy]p15:
2492 // - if a member m has rvalue reference type T&&, it is direct-initialized
2493 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002494 if (RefersToRValueRef(CtorArg.get())) {
2495 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002496 }
2497
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002498 // When the field we are copying is an array, create index variables for
2499 // each dimension of the array. We use these index variables to subscript
2500 // the source array, and other clients (e.g., CodeGen) will perform the
2501 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002502 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002503 QualType BaseType = Field->getType();
2504 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002505 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002506 while (const ConstantArrayType *Array
2507 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002508 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002509 // Create the iteration variable for this array index.
2510 IdentifierInfo *IterationVarName = 0;
2511 {
2512 llvm::SmallString<8> Str;
2513 llvm::raw_svector_ostream OS(Str);
2514 OS << "__i" << IndexVariables.size();
2515 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2516 }
2517 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002518 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002519 IterationVarName, SizeType,
2520 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002521 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002522 IndexVariables.push_back(IterationVar);
2523
2524 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002525 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002526 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002527 assert(!IterationVarRef.isInvalid() &&
2528 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002529 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2530 assert(!IterationVarRef.isInvalid() &&
2531 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002532
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002533 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002534 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002535 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002536 Loc);
2537 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002538 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002539
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002540 BaseType = Array->getElementType();
2541 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002542
2543 // The array subscript expression is an lvalue, which is wrong for moving.
2544 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002545 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002546
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002547 // Construct the entity that we will be initializing. For an array, this
2548 // will be first element in the array, which may require several levels
2549 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002550 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002551 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002552 if (Indirect)
2553 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2554 else
2555 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002556 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2557 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2558 0,
2559 Entities.back()));
2560
2561 // Direct-initialize to use the copy constructor.
2562 InitializationKind InitKind =
2563 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2564
Sebastian Redl74e611a2011-09-04 18:14:28 +00002565 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002566 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002567 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002568
John McCall60d7b3a2010-08-24 06:29:42 +00002569 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002570 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002571 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002572 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002573 if (MemberInit.isInvalid())
2574 return true;
2575
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002576 if (Indirect) {
2577 assert(IndexVariables.size() == 0 &&
2578 "Indirect field improperly initialized");
2579 CXXMemberInit
2580 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2581 Loc, Loc,
2582 MemberInit.takeAs<Expr>(),
2583 Loc);
2584 } else
2585 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2586 Loc, MemberInit.takeAs<Expr>(),
2587 Loc,
2588 IndexVariables.data(),
2589 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002590 return false;
2591 }
2592
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002593 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2594
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002595 QualType FieldBaseElementType =
2596 SemaRef.Context.getBaseElementType(Field->getType());
2597
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002598 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002599 InitializedEntity InitEntity
2600 = Indirect? InitializedEntity::InitializeMember(Indirect)
2601 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002602 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002603 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002604
2605 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002606 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002607 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002608
Douglas Gregor53c374f2010-12-07 00:41:46 +00002609 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002610 if (MemberInit.isInvalid())
2611 return true;
2612
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002613 if (Indirect)
2614 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2615 Indirect, Loc,
2616 Loc,
2617 MemberInit.get(),
2618 Loc);
2619 else
2620 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2621 Field, Loc, Loc,
2622 MemberInit.get(),
2623 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002624 return false;
2625 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002626
Sean Hunt1f2f3842011-05-17 00:19:05 +00002627 if (!Field->getParent()->isUnion()) {
2628 if (FieldBaseElementType->isReferenceType()) {
2629 SemaRef.Diag(Constructor->getLocation(),
2630 diag::err_uninitialized_member_in_ctor)
2631 << (int)Constructor->isImplicit()
2632 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2633 << 0 << Field->getDeclName();
2634 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2635 return true;
2636 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002637
Sean Hunt1f2f3842011-05-17 00:19:05 +00002638 if (FieldBaseElementType.isConstQualified()) {
2639 SemaRef.Diag(Constructor->getLocation(),
2640 diag::err_uninitialized_member_in_ctor)
2641 << (int)Constructor->isImplicit()
2642 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2643 << 1 << Field->getDeclName();
2644 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2645 return true;
2646 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002647 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002648
John McCallf85e1932011-06-15 23:02:42 +00002649 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2650 FieldBaseElementType->isObjCRetainableType() &&
2651 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2652 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2653 // Instant objects:
2654 // Default-initialize Objective-C pointers to NULL.
2655 CXXMemberInit
2656 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2657 Loc, Loc,
2658 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2659 Loc);
2660 return false;
2661 }
2662
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002663 // Nothing to initialize.
2664 CXXMemberInit = 0;
2665 return false;
2666}
John McCallf1860e52010-05-20 23:23:51 +00002667
2668namespace {
2669struct BaseAndFieldInfo {
2670 Sema &S;
2671 CXXConstructorDecl *Ctor;
2672 bool AnyErrorsInInits;
2673 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002674 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002675 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002676
2677 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2678 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002679 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2680 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002681 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002682 else if (Generated && Ctor->isMoveConstructor())
2683 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002684 else
2685 IIK = IIK_Default;
2686 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002687
2688 bool isImplicitCopyOrMove() const {
2689 switch (IIK) {
2690 case IIK_Copy:
2691 case IIK_Move:
2692 return true;
2693
2694 case IIK_Default:
2695 return false;
2696 }
David Blaikie30263482012-01-20 21:50:17 +00002697
2698 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002699 }
John McCallf1860e52010-05-20 23:23:51 +00002700};
2701}
2702
Richard Smitha4950662011-09-19 13:34:43 +00002703/// \brief Determine whether the given indirect field declaration is somewhere
2704/// within an anonymous union.
2705static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2706 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2707 CEnd = F->chain_end();
2708 C != CEnd; ++C)
2709 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2710 if (Record->isUnion())
2711 return true;
2712
2713 return false;
2714}
2715
Douglas Gregorddb21472011-11-02 23:04:16 +00002716/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2717/// array type.
2718static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2719 if (T->isIncompleteArrayType())
2720 return true;
2721
2722 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2723 if (!ArrayT->getSize())
2724 return true;
2725
2726 T = ArrayT->getElementType();
2727 }
2728
2729 return false;
2730}
2731
Richard Smith7a614d82011-06-11 17:19:42 +00002732static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002733 FieldDecl *Field,
2734 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002735
Chandler Carruthe861c602010-06-30 02:59:29 +00002736 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002737 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002738 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002739 return false;
2740 }
2741
Richard Smith7a614d82011-06-11 17:19:42 +00002742 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2743 // has a brace-or-equal-initializer, the entity is initialized as specified
2744 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002745 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002746 CXXCtorInitializer *Init;
2747 if (Indirect)
2748 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2749 SourceLocation(),
2750 SourceLocation(), 0,
2751 SourceLocation());
2752 else
2753 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2754 SourceLocation(),
2755 SourceLocation(), 0,
2756 SourceLocation());
2757 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002758 return false;
2759 }
2760
Richard Smithc115f632011-09-18 11:14:50 +00002761 // Don't build an implicit initializer for union members if none was
2762 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002763 if (Field->getParent()->isUnion() ||
2764 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002765 return false;
2766
Douglas Gregorddb21472011-11-02 23:04:16 +00002767 // Don't initialize incomplete or zero-length arrays.
2768 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2769 return false;
2770
John McCallf1860e52010-05-20 23:23:51 +00002771 // Don't try to build an implicit initializer if there were semantic
2772 // errors in any of the initializers (and therefore we might be
2773 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002774 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002775 return false;
2776
Sean Huntcbb67482011-01-08 20:30:50 +00002777 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002778 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2779 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002780 return true;
John McCallf1860e52010-05-20 23:23:51 +00002781
Francois Pichet00eb3f92010-12-04 09:14:42 +00002782 if (Init)
2783 Info.AllToInit.push_back(Init);
2784
John McCallf1860e52010-05-20 23:23:51 +00002785 return false;
2786}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002787
2788bool
2789Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2790 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002791 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002792 Constructor->setNumCtorInitializers(1);
2793 CXXCtorInitializer **initializer =
2794 new (Context) CXXCtorInitializer*[1];
2795 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2796 Constructor->setCtorInitializers(initializer);
2797
Sean Huntb76af9c2011-05-03 23:05:34 +00002798 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2799 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2800 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2801 }
2802
Sean Huntc1598702011-05-05 00:05:47 +00002803 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002804
Sean Hunt059ce0d2011-05-01 07:04:31 +00002805 return false;
2806}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002807
John McCallb77115d2011-06-17 00:18:42 +00002808bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2809 CXXCtorInitializer **Initializers,
2810 unsigned NumInitializers,
2811 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002812 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002813 // Just store the initializers as written, they will be checked during
2814 // instantiation.
2815 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002816 Constructor->setNumCtorInitializers(NumInitializers);
2817 CXXCtorInitializer **baseOrMemberInitializers =
2818 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002819 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002820 NumInitializers * sizeof(CXXCtorInitializer*));
2821 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002822 }
2823
2824 return false;
2825 }
2826
John McCallf1860e52010-05-20 23:23:51 +00002827 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002828
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002829 // We need to build the initializer AST according to order of construction
2830 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002831 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002832 if (!ClassDecl)
2833 return true;
2834
Eli Friedman80c30da2009-11-09 19:20:36 +00002835 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002836
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002837 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002838 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002839
2840 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002841 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002842 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002843 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002844 }
2845
Anders Carlsson711f34a2010-04-21 19:52:01 +00002846 // Keep track of the direct virtual bases.
2847 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2848 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2849 E = ClassDecl->bases_end(); I != E; ++I) {
2850 if (I->isVirtual())
2851 DirectVBases.insert(I);
2852 }
2853
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002854 // Push virtual bases before others.
2855 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2856 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2857
Sean Huntcbb67482011-01-08 20:30:50 +00002858 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002859 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2860 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002861 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002862 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002863 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002864 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002865 VBase, IsInheritedVirtualBase,
2866 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002867 HadError = true;
2868 continue;
2869 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002870
John McCallf1860e52010-05-20 23:23:51 +00002871 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002872 }
2873 }
Mike Stump1eb44332009-09-09 15:08:12 +00002874
John McCallf1860e52010-05-20 23:23:51 +00002875 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002876 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2877 E = ClassDecl->bases_end(); Base != E; ++Base) {
2878 // Virtuals are in the virtual base list and already constructed.
2879 if (Base->isVirtual())
2880 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002881
Sean Huntcbb67482011-01-08 20:30:50 +00002882 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002883 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2884 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002885 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002886 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002887 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002888 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002889 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002890 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002891 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002892 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002893
John McCallf1860e52010-05-20 23:23:51 +00002894 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002895 }
2896 }
Mike Stump1eb44332009-09-09 15:08:12 +00002897
John McCallf1860e52010-05-20 23:23:51 +00002898 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002899 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2900 MemEnd = ClassDecl->decls_end();
2901 Mem != MemEnd; ++Mem) {
2902 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002903 // C++ [class.bit]p2:
2904 // A declaration for a bit-field that omits the identifier declares an
2905 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2906 // initialized.
2907 if (F->isUnnamedBitfield())
2908 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002909
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002910 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002911 // handle anonymous struct/union fields based on their individual
2912 // indirect fields.
2913 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2914 continue;
2915
2916 if (CollectFieldInitializer(*this, Info, F))
2917 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002918 continue;
2919 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002920
2921 // Beyond this point, we only consider default initialization.
2922 if (Info.IIK != IIK_Default)
2923 continue;
2924
2925 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2926 if (F->getType()->isIncompleteArrayType()) {
2927 assert(ClassDecl->hasFlexibleArrayMember() &&
2928 "Incomplete array type is not valid");
2929 continue;
2930 }
2931
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002932 // Initialize each field of an anonymous struct individually.
2933 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2934 HadError = true;
2935
2936 continue;
2937 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002938 }
Mike Stump1eb44332009-09-09 15:08:12 +00002939
John McCallf1860e52010-05-20 23:23:51 +00002940 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002941 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002942 Constructor->setNumCtorInitializers(NumInitializers);
2943 CXXCtorInitializer **baseOrMemberInitializers =
2944 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002945 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002946 NumInitializers * sizeof(CXXCtorInitializer*));
2947 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002948
John McCallef027fe2010-03-16 21:39:52 +00002949 // Constructors implicitly reference the base and member
2950 // destructors.
2951 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2952 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002953 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002954
2955 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002956}
2957
Eli Friedman6347f422009-07-21 19:28:10 +00002958static void *GetKeyForTopLevelField(FieldDecl *Field) {
2959 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002960 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002961 if (RT->getDecl()->isAnonymousStructOrUnion())
2962 return static_cast<void *>(RT->getDecl());
2963 }
2964 return static_cast<void *>(Field);
2965}
2966
Anders Carlssonea356fb2010-04-02 05:42:15 +00002967static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002968 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002969}
2970
Anders Carlssonea356fb2010-04-02 05:42:15 +00002971static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002972 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002973 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002974 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002975
Eli Friedman6347f422009-07-21 19:28:10 +00002976 // For fields injected into the class via declaration of an anonymous union,
2977 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002978 FieldDecl *Field = Member->getAnyMember();
2979
John McCall3c3ccdb2010-04-10 09:28:51 +00002980 // If the field is a member of an anonymous struct or union, our key
2981 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002982 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002983 if (RD->isAnonymousStructOrUnion()) {
2984 while (true) {
2985 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2986 if (Parent->isAnonymousStructOrUnion())
2987 RD = Parent;
2988 else
2989 break;
2990 }
2991
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002992 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002993 }
Mike Stump1eb44332009-09-09 15:08:12 +00002994
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002995 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002996}
2997
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002998static void
2999DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003000 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003001 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003002 unsigned NumInits) {
3003 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003004 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003006 // Don't check initializers order unless the warning is enabled at the
3007 // location of at least one initializer.
3008 bool ShouldCheckOrder = false;
3009 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003010 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003011 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3012 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003013 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003014 ShouldCheckOrder = true;
3015 break;
3016 }
3017 }
3018 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003019 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003020
John McCalld6ca8da2010-04-10 07:37:23 +00003021 // Build the list of bases and members in the order that they'll
3022 // actually be initialized. The explicit initializers should be in
3023 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003024 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003025
Anders Carlsson071d6102010-04-02 03:38:04 +00003026 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3027
John McCalld6ca8da2010-04-10 07:37:23 +00003028 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003029 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003030 ClassDecl->vbases_begin(),
3031 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003032 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003033
John McCalld6ca8da2010-04-10 07:37:23 +00003034 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003035 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003036 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003037 if (Base->isVirtual())
3038 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003039 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003040 }
Mike Stump1eb44332009-09-09 15:08:12 +00003041
John McCalld6ca8da2010-04-10 07:37:23 +00003042 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003043 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003044 E = ClassDecl->field_end(); Field != E; ++Field) {
3045 if (Field->isUnnamedBitfield())
3046 continue;
3047
John McCalld6ca8da2010-04-10 07:37:23 +00003048 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003049 }
3050
John McCalld6ca8da2010-04-10 07:37:23 +00003051 unsigned NumIdealInits = IdealInitKeys.size();
3052 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003053
Sean Huntcbb67482011-01-08 20:30:50 +00003054 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003055 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003056 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003057 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003058
3059 // Scan forward to try to find this initializer in the idealized
3060 // initializers list.
3061 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3062 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003063 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003064
3065 // If we didn't find this initializer, it must be because we
3066 // scanned past it on a previous iteration. That can only
3067 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003068 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003069 Sema::SemaDiagnosticBuilder D =
3070 SemaRef.Diag(PrevInit->getSourceLocation(),
3071 diag::warn_initializer_out_of_order);
3072
Francois Pichet00eb3f92010-12-04 09:14:42 +00003073 if (PrevInit->isAnyMemberInitializer())
3074 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003075 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003076 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003077
Francois Pichet00eb3f92010-12-04 09:14:42 +00003078 if (Init->isAnyMemberInitializer())
3079 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003080 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003081 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003082
3083 // Move back to the initializer's location in the ideal list.
3084 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3085 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003086 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003087
3088 assert(IdealIndex != NumIdealInits &&
3089 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003090 }
John McCalld6ca8da2010-04-10 07:37:23 +00003091
3092 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003093 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003094}
3095
John McCall3c3ccdb2010-04-10 09:28:51 +00003096namespace {
3097bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003098 CXXCtorInitializer *Init,
3099 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003100 if (!PrevInit) {
3101 PrevInit = Init;
3102 return false;
3103 }
3104
3105 if (FieldDecl *Field = Init->getMember())
3106 S.Diag(Init->getSourceLocation(),
3107 diag::err_multiple_mem_initialization)
3108 << Field->getDeclName()
3109 << Init->getSourceRange();
3110 else {
John McCallf4c73712011-01-19 06:33:43 +00003111 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003112 assert(BaseClass && "neither field nor base");
3113 S.Diag(Init->getSourceLocation(),
3114 diag::err_multiple_base_initialization)
3115 << QualType(BaseClass, 0)
3116 << Init->getSourceRange();
3117 }
3118 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3119 << 0 << PrevInit->getSourceRange();
3120
3121 return true;
3122}
3123
Sean Huntcbb67482011-01-08 20:30:50 +00003124typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003125typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3126
3127bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003128 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003129 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003130 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003131 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003132 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003133
3134 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003135 if (Parent->isUnion()) {
3136 UnionEntry &En = Unions[Parent];
3137 if (En.first && En.first != Child) {
3138 S.Diag(Init->getSourceLocation(),
3139 diag::err_multiple_mem_union_initialization)
3140 << Field->getDeclName()
3141 << Init->getSourceRange();
3142 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3143 << 0 << En.second->getSourceRange();
3144 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003145 }
3146 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003147 En.first = Child;
3148 En.second = Init;
3149 }
David Blaikie6fe29652011-11-17 06:01:57 +00003150 if (!Parent->isAnonymousStructOrUnion())
3151 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003152 }
3153
3154 Child = Parent;
3155 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003156 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003157
3158 return false;
3159}
3160}
3161
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003162/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003163void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003164 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003165 CXXCtorInitializer **meminits,
3166 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003167 bool AnyErrors) {
3168 if (!ConstructorDecl)
3169 return;
3170
3171 AdjustDeclIfTemplate(ConstructorDecl);
3172
3173 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003174 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003175
3176 if (!Constructor) {
3177 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3178 return;
3179 }
3180
Sean Huntcbb67482011-01-08 20:30:50 +00003181 CXXCtorInitializer **MemInits =
3182 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003183
3184 // Mapping for the duplicate initializers check.
3185 // For member initializers, this is keyed with a FieldDecl*.
3186 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003187 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003188
3189 // Mapping for the inconsistent anonymous-union initializers check.
3190 RedundantUnionMap MemberUnions;
3191
Anders Carlssonea356fb2010-04-02 05:42:15 +00003192 bool HadError = false;
3193 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003194 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003195
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003196 // Set the source order index.
3197 Init->setSourceOrder(i);
3198
Francois Pichet00eb3f92010-12-04 09:14:42 +00003199 if (Init->isAnyMemberInitializer()) {
3200 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003201 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3202 CheckRedundantUnionInit(*this, Init, MemberUnions))
3203 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003204 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003205 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3206 if (CheckRedundantInit(*this, Init, Members[Key]))
3207 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003208 } else {
3209 assert(Init->isDelegatingInitializer());
3210 // This must be the only initializer
3211 if (i != 0 || NumMemInits > 1) {
3212 Diag(MemInits[0]->getSourceLocation(),
3213 diag::err_delegating_initializer_alone)
3214 << MemInits[0]->getSourceRange();
3215 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003216 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003217 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003218 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003219 // Return immediately as the initializer is set.
3220 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003221 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003222 }
3223
Anders Carlssonea356fb2010-04-02 05:42:15 +00003224 if (HadError)
3225 return;
3226
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003227 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003228
Sean Huntcbb67482011-01-08 20:30:50 +00003229 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003230}
3231
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003232void
John McCallef027fe2010-03-16 21:39:52 +00003233Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3234 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003235 // Ignore dependent contexts. Also ignore unions, since their members never
3236 // have destructors implicitly called.
3237 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003238 return;
John McCall58e6f342010-03-16 05:22:47 +00003239
3240 // FIXME: all the access-control diagnostics are positioned on the
3241 // field/base declaration. That's probably good; that said, the
3242 // user might reasonably want to know why the destructor is being
3243 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003244
Anders Carlsson9f853df2009-11-17 04:44:12 +00003245 // Non-static data members.
3246 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3247 E = ClassDecl->field_end(); I != E; ++I) {
3248 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003249 if (Field->isInvalidDecl())
3250 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003251
3252 // Don't destroy incomplete or zero-length arrays.
3253 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3254 continue;
3255
Anders Carlsson9f853df2009-11-17 04:44:12 +00003256 QualType FieldType = Context.getBaseElementType(Field->getType());
3257
3258 const RecordType* RT = FieldType->getAs<RecordType>();
3259 if (!RT)
3260 continue;
3261
3262 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003263 if (FieldClassDecl->isInvalidDecl())
3264 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003265 if (FieldClassDecl->hasTrivialDestructor())
3266 continue;
3267
Douglas Gregordb89f282010-07-01 22:47:18 +00003268 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003269 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003270 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003271 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003272 << Field->getDeclName()
3273 << FieldType);
3274
John McCallef027fe2010-03-16 21:39:52 +00003275 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003276 }
3277
John McCall58e6f342010-03-16 05:22:47 +00003278 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3279
Anders Carlsson9f853df2009-11-17 04:44:12 +00003280 // Bases.
3281 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3282 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003283 // Bases are always records in a well-formed non-dependent class.
3284 const RecordType *RT = Base->getType()->getAs<RecordType>();
3285
3286 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003287 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003288 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003289
John McCall58e6f342010-03-16 05:22:47 +00003290 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003291 // If our base class is invalid, we probably can't get its dtor anyway.
3292 if (BaseClassDecl->isInvalidDecl())
3293 continue;
3294 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003295 if (BaseClassDecl->hasTrivialDestructor())
3296 continue;
John McCall58e6f342010-03-16 05:22:47 +00003297
Douglas Gregordb89f282010-07-01 22:47:18 +00003298 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003299 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003300
3301 // FIXME: caret should be on the start of the class name
3302 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003303 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003304 << Base->getType()
3305 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003306
John McCallef027fe2010-03-16 21:39:52 +00003307 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003308 }
3309
3310 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003311 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3312 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003313
3314 // Bases are always records in a well-formed non-dependent class.
3315 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3316
3317 // Ignore direct virtual bases.
3318 if (DirectVirtualBases.count(RT))
3319 continue;
3320
John McCall58e6f342010-03-16 05:22:47 +00003321 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003322 // If our base class is invalid, we probably can't get its dtor anyway.
3323 if (BaseClassDecl->isInvalidDecl())
3324 continue;
3325 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003326 if (BaseClassDecl->hasTrivialDestructor())
3327 continue;
John McCall58e6f342010-03-16 05:22:47 +00003328
Douglas Gregordb89f282010-07-01 22:47:18 +00003329 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003330 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003331 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003332 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003333 << VBase->getType());
3334
John McCallef027fe2010-03-16 21:39:52 +00003335 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003336 }
3337}
3338
John McCalld226f652010-08-21 09:40:31 +00003339void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003340 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003341 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003342
Mike Stump1eb44332009-09-09 15:08:12 +00003343 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003344 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003345 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003346}
3347
Mike Stump1eb44332009-09-09 15:08:12 +00003348bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003349 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003350 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003351 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003352 else
John McCall94c3b562010-08-18 09:41:07 +00003353 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003354}
3355
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003356bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003357 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003358 if (!getLangOptions().CPlusPlus)
3359 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003360
Anders Carlsson11f21a02009-03-23 19:10:31 +00003361 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003362 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003363
Ted Kremenek6217b802009-07-29 21:53:49 +00003364 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003365 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003366 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003367 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003369 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003370 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003371 }
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Ted Kremenek6217b802009-07-29 21:53:49 +00003373 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003374 if (!RT)
3375 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003376
John McCall86ff3082010-02-04 22:26:26 +00003377 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003378
John McCall94c3b562010-08-18 09:41:07 +00003379 // We can't answer whether something is abstract until it has a
3380 // definition. If it's currently being defined, we'll walk back
3381 // over all the declarations when we have a full definition.
3382 const CXXRecordDecl *Def = RD->getDefinition();
3383 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003384 return false;
3385
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003386 if (!RD->isAbstract())
3387 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003389 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003390 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003391
John McCall94c3b562010-08-18 09:41:07 +00003392 return true;
3393}
3394
3395void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3396 // Check if we've already emitted the list of pure virtual functions
3397 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003398 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003399 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003401 CXXFinalOverriderMap FinalOverriders;
3402 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003403
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003404 // Keep a set of seen pure methods so we won't diagnose the same method
3405 // more than once.
3406 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3407
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003408 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3409 MEnd = FinalOverriders.end();
3410 M != MEnd;
3411 ++M) {
3412 for (OverridingMethods::iterator SO = M->second.begin(),
3413 SOEnd = M->second.end();
3414 SO != SOEnd; ++SO) {
3415 // C++ [class.abstract]p4:
3416 // A class is abstract if it contains or inherits at least one
3417 // pure virtual function for which the final overrider is pure
3418 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003419
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003420 //
3421 if (SO->second.size() != 1)
3422 continue;
3423
3424 if (!SO->second.front().Method->isPure())
3425 continue;
3426
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003427 if (!SeenPureMethods.insert(SO->second.front().Method))
3428 continue;
3429
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003430 Diag(SO->second.front().Method->getLocation(),
3431 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003432 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003433 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003434 }
3435
3436 if (!PureVirtualClassDiagSet)
3437 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3438 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003439}
3440
Anders Carlsson8211eff2009-03-24 01:19:16 +00003441namespace {
John McCall94c3b562010-08-18 09:41:07 +00003442struct AbstractUsageInfo {
3443 Sema &S;
3444 CXXRecordDecl *Record;
3445 CanQualType AbstractType;
3446 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003447
John McCall94c3b562010-08-18 09:41:07 +00003448 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3449 : S(S), Record(Record),
3450 AbstractType(S.Context.getCanonicalType(
3451 S.Context.getTypeDeclType(Record))),
3452 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003453
John McCall94c3b562010-08-18 09:41:07 +00003454 void DiagnoseAbstractType() {
3455 if (Invalid) return;
3456 S.DiagnoseAbstractType(Record);
3457 Invalid = true;
3458 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003459
John McCall94c3b562010-08-18 09:41:07 +00003460 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3461};
3462
3463struct CheckAbstractUsage {
3464 AbstractUsageInfo &Info;
3465 const NamedDecl *Ctx;
3466
3467 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3468 : Info(Info), Ctx(Ctx) {}
3469
3470 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3471 switch (TL.getTypeLocClass()) {
3472#define ABSTRACT_TYPELOC(CLASS, PARENT)
3473#define TYPELOC(CLASS, PARENT) \
3474 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3475#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003476 }
John McCall94c3b562010-08-18 09:41:07 +00003477 }
Mike Stump1eb44332009-09-09 15:08:12 +00003478
John McCall94c3b562010-08-18 09:41:07 +00003479 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3480 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3481 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003482 if (!TL.getArg(I))
3483 continue;
3484
John McCall94c3b562010-08-18 09:41:07 +00003485 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3486 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003487 }
John McCall94c3b562010-08-18 09:41:07 +00003488 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003489
John McCall94c3b562010-08-18 09:41:07 +00003490 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3491 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3492 }
Mike Stump1eb44332009-09-09 15:08:12 +00003493
John McCall94c3b562010-08-18 09:41:07 +00003494 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3495 // Visit the type parameters from a permissive context.
3496 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3497 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3498 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3499 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3500 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3501 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003502 }
John McCall94c3b562010-08-18 09:41:07 +00003503 }
Mike Stump1eb44332009-09-09 15:08:12 +00003504
John McCall94c3b562010-08-18 09:41:07 +00003505 // Visit pointee types from a permissive context.
3506#define CheckPolymorphic(Type) \
3507 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3508 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3509 }
3510 CheckPolymorphic(PointerTypeLoc)
3511 CheckPolymorphic(ReferenceTypeLoc)
3512 CheckPolymorphic(MemberPointerTypeLoc)
3513 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003514 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003515
John McCall94c3b562010-08-18 09:41:07 +00003516 /// Handle all the types we haven't given a more specific
3517 /// implementation for above.
3518 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3519 // Every other kind of type that we haven't called out already
3520 // that has an inner type is either (1) sugar or (2) contains that
3521 // inner type in some way as a subobject.
3522 if (TypeLoc Next = TL.getNextTypeLoc())
3523 return Visit(Next, Sel);
3524
3525 // If there's no inner type and we're in a permissive context,
3526 // don't diagnose.
3527 if (Sel == Sema::AbstractNone) return;
3528
3529 // Check whether the type matches the abstract type.
3530 QualType T = TL.getType();
3531 if (T->isArrayType()) {
3532 Sel = Sema::AbstractArrayType;
3533 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003534 }
John McCall94c3b562010-08-18 09:41:07 +00003535 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3536 if (CT != Info.AbstractType) return;
3537
3538 // It matched; do some magic.
3539 if (Sel == Sema::AbstractArrayType) {
3540 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3541 << T << TL.getSourceRange();
3542 } else {
3543 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3544 << Sel << T << TL.getSourceRange();
3545 }
3546 Info.DiagnoseAbstractType();
3547 }
3548};
3549
3550void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3551 Sema::AbstractDiagSelID Sel) {
3552 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3553}
3554
3555}
3556
3557/// Check for invalid uses of an abstract type in a method declaration.
3558static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3559 CXXMethodDecl *MD) {
3560 // No need to do the check on definitions, which require that
3561 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003562 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003563 return;
3564
3565 // For safety's sake, just ignore it if we don't have type source
3566 // information. This should never happen for non-implicit methods,
3567 // but...
3568 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3569 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3570}
3571
3572/// Check for invalid uses of an abstract type within a class definition.
3573static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3574 CXXRecordDecl *RD) {
3575 for (CXXRecordDecl::decl_iterator
3576 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3577 Decl *D = *I;
3578 if (D->isImplicit()) continue;
3579
3580 // Methods and method templates.
3581 if (isa<CXXMethodDecl>(D)) {
3582 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3583 } else if (isa<FunctionTemplateDecl>(D)) {
3584 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3585 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3586
3587 // Fields and static variables.
3588 } else if (isa<FieldDecl>(D)) {
3589 FieldDecl *FD = cast<FieldDecl>(D);
3590 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3591 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3592 } else if (isa<VarDecl>(D)) {
3593 VarDecl *VD = cast<VarDecl>(D);
3594 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3595 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3596
3597 // Nested classes and class templates.
3598 } else if (isa<CXXRecordDecl>(D)) {
3599 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3600 } else if (isa<ClassTemplateDecl>(D)) {
3601 CheckAbstractClassUsage(Info,
3602 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3603 }
3604 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003605}
3606
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003607/// \brief Perform semantic checks on a class definition that has been
3608/// completing, introducing implicitly-declared members, checking for
3609/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003610void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003611 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003612 return;
3613
John McCall94c3b562010-08-18 09:41:07 +00003614 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3615 AbstractUsageInfo Info(*this, Record);
3616 CheckAbstractClassUsage(Info, Record);
3617 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003618
3619 // If this is not an aggregate type and has no user-declared constructor,
3620 // complain about any non-static data members of reference or const scalar
3621 // type, since they will never get initializers.
3622 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3623 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3624 bool Complained = false;
3625 for (RecordDecl::field_iterator F = Record->field_begin(),
3626 FEnd = Record->field_end();
3627 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003628 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003629 continue;
3630
Douglas Gregor325e5932010-04-15 00:00:53 +00003631 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003632 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003633 if (!Complained) {
3634 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3635 << Record->getTagKind() << Record;
3636 Complained = true;
3637 }
3638
3639 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3640 << F->getType()->isReferenceType()
3641 << F->getDeclName();
3642 }
3643 }
3644 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003645
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003646 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003647 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003648
3649 if (Record->getIdentifier()) {
3650 // C++ [class.mem]p13:
3651 // If T is the name of a class, then each of the following shall have a
3652 // name different from T:
3653 // - every member of every anonymous union that is a member of class T.
3654 //
3655 // C++ [class.mem]p14:
3656 // In addition, if class T has a user-declared constructor (12.1), every
3657 // non-static data member of class T shall have a name different from T.
3658 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003659 R.first != R.second; ++R.first) {
3660 NamedDecl *D = *R.first;
3661 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3662 isa<IndirectFieldDecl>(D)) {
3663 Diag(D->getLocation(), diag::err_member_name_of_class)
3664 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003665 break;
3666 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003667 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003668 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003669
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003670 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003671 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003672 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003673 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003674 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3675 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3676 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003677
3678 // See if a method overloads virtual methods in a base
3679 /// class without overriding any.
3680 if (!Record->isDependentType()) {
3681 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3682 MEnd = Record->method_end();
3683 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003684 if (!(*M)->isStatic())
3685 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003686 }
3687 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003688
Richard Smith9f569cc2011-10-01 02:31:28 +00003689 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3690 // function that is not a constructor declares that member function to be
3691 // const. [...] The class of which that function is a member shall be
3692 // a literal type.
3693 //
3694 // It's fine to diagnose constructors here too: such constructors cannot
3695 // produce a constant expression, so are ill-formed (no diagnostic required).
3696 //
3697 // If the class has virtual bases, any constexpr members will already have
3698 // been diagnosed by the checks performed on the member declaration, so
3699 // suppress this (less useful) diagnostic.
3700 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3701 !Record->isLiteral() && !Record->getNumVBases()) {
3702 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3703 MEnd = Record->method_end();
3704 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003705 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003706 switch (Record->getTemplateSpecializationKind()) {
3707 case TSK_ImplicitInstantiation:
3708 case TSK_ExplicitInstantiationDeclaration:
3709 case TSK_ExplicitInstantiationDefinition:
3710 // If a template instantiates to a non-literal type, but its members
3711 // instantiate to constexpr functions, the template is technically
3712 // ill-formed, but we allow it for sanity. Such members are treated as
3713 // non-constexpr.
3714 (*M)->setConstexpr(false);
3715 continue;
3716
3717 case TSK_Undeclared:
3718 case TSK_ExplicitSpecialization:
3719 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3720 PDiag(diag::err_constexpr_method_non_literal));
3721 break;
3722 }
3723
3724 // Only produce one error per class.
3725 break;
3726 }
3727 }
3728 }
3729
Sebastian Redlf677ea32011-02-05 19:23:19 +00003730 // Declare inherited constructors. We do this eagerly here because:
3731 // - The standard requires an eager diagnostic for conflicting inherited
3732 // constructors from different classes.
3733 // - The lazy declaration of the other implicit constructors is so as to not
3734 // waste space and performance on classes that are not meant to be
3735 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3736 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003737 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003738
Sean Hunteb88ae52011-05-23 21:07:59 +00003739 if (!Record->isDependentType())
3740 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003741}
3742
3743void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003744 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3745 ME = Record->method_end();
3746 MI != ME; ++MI) {
3747 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3748 switch (getSpecialMember(*MI)) {
3749 case CXXDefaultConstructor:
3750 CheckExplicitlyDefaultedDefaultConstructor(
3751 cast<CXXConstructorDecl>(*MI));
3752 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003753
Sean Huntcb45a0f2011-05-12 22:46:25 +00003754 case CXXDestructor:
3755 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3756 break;
3757
3758 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003759 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3760 break;
3761
Sean Huntcb45a0f2011-05-12 22:46:25 +00003762 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003763 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003764 break;
3765
Sean Hunt82713172011-05-25 23:16:36 +00003766 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003767 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003768 break;
3769
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003770 case CXXMoveAssignment:
3771 CheckExplicitlyDefaultedMoveAssignment(*MI);
3772 break;
3773
3774 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003775 llvm_unreachable("non-special member explicitly defaulted!");
3776 }
Sean Hunt001cad92011-05-10 00:49:42 +00003777 }
3778 }
3779
Sean Hunt001cad92011-05-10 00:49:42 +00003780}
3781
3782void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3783 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3784
3785 // Whether this was the first-declared instance of the constructor.
3786 // This affects whether we implicitly add an exception spec (and, eventually,
3787 // constexpr). It is also ill-formed to explicitly default a constructor such
3788 // that it would be deleted. (C++0x [decl.fct.def.default])
3789 bool First = CD == CD->getCanonicalDecl();
3790
Sean Hunt49634cf2011-05-13 06:10:58 +00003791 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003792 if (CD->getNumParams() != 0) {
3793 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3794 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003795 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003796 }
3797
3798 ImplicitExceptionSpecification Spec
3799 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3800 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003801 if (EPI.ExceptionSpecType == EST_Delayed) {
3802 // Exception specification depends on some deferred part of the class. We'll
3803 // try again when the class's definition has been fully processed.
3804 return;
3805 }
Sean Hunt001cad92011-05-10 00:49:42 +00003806 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3807 *ExceptionType = Context.getFunctionType(
3808 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3809
Richard Smith61802452011-12-22 02:22:31 +00003810 // C++11 [dcl.fct.def.default]p2:
3811 // An explicitly-defaulted function may be declared constexpr only if it
3812 // would have been implicitly declared as constexpr,
3813 if (CD->isConstexpr()) {
3814 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3815 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3816 << CXXDefaultConstructor;
3817 HadError = true;
3818 }
3819 }
3820 // and may have an explicit exception-specification only if it is compatible
3821 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003822 if (CtorType->hasExceptionSpec()) {
3823 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003824 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003825 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003826 PDiag(),
3827 ExceptionType, SourceLocation(),
3828 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003829 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003830 }
Richard Smith61802452011-12-22 02:22:31 +00003831 }
3832
3833 // If a function is explicitly defaulted on its first declaration,
3834 if (First) {
3835 // -- it is implicitly considered to be constexpr if the implicit
3836 // definition would be,
3837 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3838
3839 // -- it is implicitly considered to have the same
3840 // exception-specification as if it had been implicitly declared
3841 //
3842 // FIXME: a compatible, but different, explicit exception specification
3843 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003844 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003845 }
Sean Huntca46d132011-05-12 03:51:48 +00003846
Sean Hunt49634cf2011-05-13 06:10:58 +00003847 if (HadError) {
3848 CD->setInvalidDecl();
3849 return;
3850 }
3851
Sean Hunte16da072011-10-10 06:18:57 +00003852 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003853 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003854 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003855 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003856 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003857 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003858 CD->setInvalidDecl();
3859 }
3860 }
3861}
3862
3863void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3864 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3865
3866 // Whether this was the first-declared instance of the constructor.
3867 bool First = CD == CD->getCanonicalDecl();
3868
3869 bool HadError = false;
3870 if (CD->getNumParams() != 1) {
3871 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3872 << CD->getSourceRange();
3873 HadError = true;
3874 }
3875
3876 ImplicitExceptionSpecification Spec(Context);
3877 bool Const;
3878 llvm::tie(Spec, Const) =
3879 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3880
3881 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3882 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3883 *ExceptionType = Context.getFunctionType(
3884 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3885
3886 // Check for parameter type matching.
3887 // This is a copy ctor so we know it's a cv-qualified reference to T.
3888 QualType ArgType = CtorType->getArgType(0);
3889 if (ArgType->getPointeeType().isVolatileQualified()) {
3890 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3891 HadError = true;
3892 }
3893 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3894 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3895 HadError = true;
3896 }
3897
Richard Smith61802452011-12-22 02:22:31 +00003898 // C++11 [dcl.fct.def.default]p2:
3899 // An explicitly-defaulted function may be declared constexpr only if it
3900 // would have been implicitly declared as constexpr,
3901 if (CD->isConstexpr()) {
3902 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3903 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3904 << CXXCopyConstructor;
3905 HadError = true;
3906 }
3907 }
3908 // and may have an explicit exception-specification only if it is compatible
3909 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003910 if (CtorType->hasExceptionSpec()) {
3911 if (CheckEquivalentExceptionSpec(
3912 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003913 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003914 PDiag(),
3915 ExceptionType, SourceLocation(),
3916 CtorType, CD->getLocation())) {
3917 HadError = true;
3918 }
Richard Smith61802452011-12-22 02:22:31 +00003919 }
3920
3921 // If a function is explicitly defaulted on its first declaration,
3922 if (First) {
3923 // -- it is implicitly considered to be constexpr if the implicit
3924 // definition would be,
3925 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3926
3927 // -- it is implicitly considered to have the same
3928 // exception-specification as if it had been implicitly declared, and
3929 //
3930 // FIXME: a compatible, but different, explicit exception specification
3931 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003932 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003933
3934 // -- [...] it shall have the same parameter type as if it had been
3935 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003936 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3937 }
3938
3939 if (HadError) {
3940 CD->setInvalidDecl();
3941 return;
3942 }
3943
Sean Huntc32d6842011-10-11 04:55:36 +00003944 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003945 if (First) {
3946 CD->setDeletedAsWritten();
3947 } else {
3948 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003949 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003950 CD->setInvalidDecl();
3951 }
Sean Huntca46d132011-05-12 03:51:48 +00003952 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003953}
Sean Hunt001cad92011-05-10 00:49:42 +00003954
Sean Hunt2b188082011-05-14 05:23:28 +00003955void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3956 assert(MD->isExplicitlyDefaulted());
3957
3958 // Whether this was the first-declared instance of the operator
3959 bool First = MD == MD->getCanonicalDecl();
3960
3961 bool HadError = false;
3962 if (MD->getNumParams() != 1) {
3963 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3964 << MD->getSourceRange();
3965 HadError = true;
3966 }
3967
3968 QualType ReturnType =
3969 MD->getType()->getAs<FunctionType>()->getResultType();
3970 if (!ReturnType->isLValueReferenceType() ||
3971 !Context.hasSameType(
3972 Context.getCanonicalType(ReturnType->getPointeeType()),
3973 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3974 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3975 HadError = true;
3976 }
3977
3978 ImplicitExceptionSpecification Spec(Context);
3979 bool Const;
3980 llvm::tie(Spec, Const) =
3981 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3982
3983 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3984 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3985 *ExceptionType = Context.getFunctionType(
3986 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3987
Sean Hunt2b188082011-05-14 05:23:28 +00003988 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003989 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003990 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003991 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003992 } else {
3993 if (ArgType->getPointeeType().isVolatileQualified()) {
3994 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3995 HadError = true;
3996 }
3997 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3998 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3999 HadError = true;
4000 }
Sean Hunt2b188082011-05-14 05:23:28 +00004001 }
Sean Huntbe631222011-05-17 20:44:43 +00004002
Sean Hunt2b188082011-05-14 05:23:28 +00004003 if (OperType->getTypeQuals()) {
4004 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4005 HadError = true;
4006 }
4007
4008 if (OperType->hasExceptionSpec()) {
4009 if (CheckEquivalentExceptionSpec(
4010 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004011 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004012 PDiag(),
4013 ExceptionType, SourceLocation(),
4014 OperType, MD->getLocation())) {
4015 HadError = true;
4016 }
Richard Smith61802452011-12-22 02:22:31 +00004017 }
4018 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004019 // We set the declaration to have the computed exception spec here.
4020 // We duplicate the one parameter type.
4021 EPI.RefQualifier = OperType->getRefQualifier();
4022 EPI.ExtInfo = OperType->getExtInfo();
4023 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4024 }
4025
4026 if (HadError) {
4027 MD->setInvalidDecl();
4028 return;
4029 }
4030
4031 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4032 if (First) {
4033 MD->setDeletedAsWritten();
4034 } else {
4035 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004036 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004037 MD->setInvalidDecl();
4038 }
4039 }
4040}
4041
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004042void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4043 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4044
4045 // Whether this was the first-declared instance of the constructor.
4046 bool First = CD == CD->getCanonicalDecl();
4047
4048 bool HadError = false;
4049 if (CD->getNumParams() != 1) {
4050 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4051 << CD->getSourceRange();
4052 HadError = true;
4053 }
4054
4055 ImplicitExceptionSpecification Spec(
4056 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4057
4058 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4059 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4060 *ExceptionType = Context.getFunctionType(
4061 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4062
4063 // Check for parameter type matching.
4064 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4065 QualType ArgType = CtorType->getArgType(0);
4066 if (ArgType->getPointeeType().isVolatileQualified()) {
4067 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4068 HadError = true;
4069 }
4070 if (ArgType->getPointeeType().isConstQualified()) {
4071 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4072 HadError = true;
4073 }
4074
Richard Smith61802452011-12-22 02:22:31 +00004075 // C++11 [dcl.fct.def.default]p2:
4076 // An explicitly-defaulted function may be declared constexpr only if it
4077 // would have been implicitly declared as constexpr,
4078 if (CD->isConstexpr()) {
4079 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4080 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4081 << CXXMoveConstructor;
4082 HadError = true;
4083 }
4084 }
4085 // and may have an explicit exception-specification only if it is compatible
4086 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004087 if (CtorType->hasExceptionSpec()) {
4088 if (CheckEquivalentExceptionSpec(
4089 PDiag(diag::err_incorrect_defaulted_exception_spec)
4090 << CXXMoveConstructor,
4091 PDiag(),
4092 ExceptionType, SourceLocation(),
4093 CtorType, CD->getLocation())) {
4094 HadError = true;
4095 }
Richard Smith61802452011-12-22 02:22:31 +00004096 }
4097
4098 // If a function is explicitly defaulted on its first declaration,
4099 if (First) {
4100 // -- it is implicitly considered to be constexpr if the implicit
4101 // definition would be,
4102 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4103
4104 // -- it is implicitly considered to have the same
4105 // exception-specification as if it had been implicitly declared, and
4106 //
4107 // FIXME: a compatible, but different, explicit exception specification
4108 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004109 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004110
4111 // -- [...] it shall have the same parameter type as if it had been
4112 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004113 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4114 }
4115
4116 if (HadError) {
4117 CD->setInvalidDecl();
4118 return;
4119 }
4120
Sean Hunt769bb2d2011-10-11 06:43:29 +00004121 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004122 if (First) {
4123 CD->setDeletedAsWritten();
4124 } else {
4125 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4126 << CXXMoveConstructor;
4127 CD->setInvalidDecl();
4128 }
4129 }
4130}
4131
4132void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4133 assert(MD->isExplicitlyDefaulted());
4134
4135 // Whether this was the first-declared instance of the operator
4136 bool First = MD == MD->getCanonicalDecl();
4137
4138 bool HadError = false;
4139 if (MD->getNumParams() != 1) {
4140 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4141 << MD->getSourceRange();
4142 HadError = true;
4143 }
4144
4145 QualType ReturnType =
4146 MD->getType()->getAs<FunctionType>()->getResultType();
4147 if (!ReturnType->isLValueReferenceType() ||
4148 !Context.hasSameType(
4149 Context.getCanonicalType(ReturnType->getPointeeType()),
4150 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4151 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4152 HadError = true;
4153 }
4154
4155 ImplicitExceptionSpecification Spec(
4156 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4157
4158 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4159 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4160 *ExceptionType = Context.getFunctionType(
4161 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4162
4163 QualType ArgType = OperType->getArgType(0);
4164 if (!ArgType->isRValueReferenceType()) {
4165 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4166 HadError = true;
4167 } else {
4168 if (ArgType->getPointeeType().isVolatileQualified()) {
4169 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4170 HadError = true;
4171 }
4172 if (ArgType->getPointeeType().isConstQualified()) {
4173 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4174 HadError = true;
4175 }
4176 }
4177
4178 if (OperType->getTypeQuals()) {
4179 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4180 HadError = true;
4181 }
4182
4183 if (OperType->hasExceptionSpec()) {
4184 if (CheckEquivalentExceptionSpec(
4185 PDiag(diag::err_incorrect_defaulted_exception_spec)
4186 << CXXMoveAssignment,
4187 PDiag(),
4188 ExceptionType, SourceLocation(),
4189 OperType, MD->getLocation())) {
4190 HadError = true;
4191 }
Richard Smith61802452011-12-22 02:22:31 +00004192 }
4193 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004194 // We set the declaration to have the computed exception spec here.
4195 // We duplicate the one parameter type.
4196 EPI.RefQualifier = OperType->getRefQualifier();
4197 EPI.ExtInfo = OperType->getExtInfo();
4198 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4199 }
4200
4201 if (HadError) {
4202 MD->setInvalidDecl();
4203 return;
4204 }
4205
4206 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4207 if (First) {
4208 MD->setDeletedAsWritten();
4209 } else {
4210 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4211 << CXXMoveAssignment;
4212 MD->setInvalidDecl();
4213 }
4214 }
4215}
4216
Sean Huntcb45a0f2011-05-12 22:46:25 +00004217void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4218 assert(DD->isExplicitlyDefaulted());
4219
4220 // Whether this was the first-declared instance of the destructor.
4221 bool First = DD == DD->getCanonicalDecl();
4222
4223 ImplicitExceptionSpecification Spec
4224 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4225 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4226 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4227 *ExceptionType = Context.getFunctionType(
4228 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4229
4230 if (DtorType->hasExceptionSpec()) {
4231 if (CheckEquivalentExceptionSpec(
4232 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004233 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004234 PDiag(),
4235 ExceptionType, SourceLocation(),
4236 DtorType, DD->getLocation())) {
4237 DD->setInvalidDecl();
4238 return;
4239 }
Richard Smith61802452011-12-22 02:22:31 +00004240 }
4241 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004242 // We set the declaration to have the computed exception spec here.
4243 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004244 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004245 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4246 }
4247
4248 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004249 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004250 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004251 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004252 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004253 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004254 DD->setInvalidDecl();
4255 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004256 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004257}
4258
Sean Hunte16da072011-10-10 06:18:57 +00004259/// This function implements the following C++0x paragraphs:
4260/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004261/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004262bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4263 assert(!MD->isInvalidDecl());
4264 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004265 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004266 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004267 return false;
4268
Sean Hunte16da072011-10-10 06:18:57 +00004269 bool IsUnion = RD->isUnion();
4270 bool IsConstructor = false;
4271 bool IsAssignment = false;
4272 bool IsMove = false;
4273
4274 bool ConstArg = false;
4275
4276 switch (CSM) {
4277 case CXXDefaultConstructor:
4278 IsConstructor = true;
4279 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004280 case CXXCopyConstructor:
4281 IsConstructor = true;
4282 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4283 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004284 case CXXMoveConstructor:
4285 IsConstructor = true;
4286 IsMove = true;
4287 break;
Sean Hunte16da072011-10-10 06:18:57 +00004288 default:
4289 llvm_unreachable("function only currently implemented for default ctors");
4290 }
4291
4292 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004293
Sean Huntc32d6842011-10-11 04:55:36 +00004294 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004295 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004296
Sean Huntcdee3fe2011-05-11 22:34:38 +00004297 bool AllConst = true;
4298
Sean Huntcdee3fe2011-05-11 22:34:38 +00004299 // We do this because we should never actually use an anonymous
4300 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004301 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004302 return false;
4303
4304 // FIXME: We should put some diagnostic logic right into this function.
4305
Sean Huntcdee3fe2011-05-11 22:34:38 +00004306 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4307 BE = RD->bases_end();
4308 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004309 // We'll handle this one later
4310 if (BI->isVirtual())
4311 continue;
4312
Sean Huntcdee3fe2011-05-11 22:34:38 +00004313 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4314 assert(BaseDecl && "base isn't a CXXRecordDecl");
4315
Sean Hunte16da072011-10-10 06:18:57 +00004316 // Unless we have an assignment operator, the base's destructor must
4317 // be accessible and not deleted.
4318 if (!IsAssignment) {
4319 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4320 if (BaseDtor->isDeleted())
4321 return true;
4322 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4323 AR_accessible)
4324 return true;
4325 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004326
Sean Hunte16da072011-10-10 06:18:57 +00004327 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004328 // unique, accessible, non-deleted function. If we are doing
4329 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004330 if (CSM != CXXDestructor) {
4331 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004332 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004333 false);
4334 if (!SMOR->hasSuccess())
4335 return true;
4336 CXXMethodDecl *BaseMember = SMOR->getMethod();
4337 if (IsConstructor) {
4338 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4339 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4340 PDiag()) != AR_accessible)
4341 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004342
4343 // For a move operation, the corresponding operation must actually
4344 // be a move operation (and not a copy selected by overload
4345 // resolution) unless we are working on a trivially copyable class.
4346 if (IsMove && !BaseCtor->isMoveConstructor() &&
4347 !BaseDecl->isTriviallyCopyable())
4348 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004349 }
4350 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004351 }
4352
4353 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4354 BE = RD->vbases_end();
4355 BI != BE; ++BI) {
4356 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4357 assert(BaseDecl && "base isn't a CXXRecordDecl");
4358
Sean Hunte16da072011-10-10 06:18:57 +00004359 // Unless we have an assignment operator, the base's destructor must
4360 // be accessible and not deleted.
4361 if (!IsAssignment) {
4362 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4363 if (BaseDtor->isDeleted())
4364 return true;
4365 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4366 AR_accessible)
4367 return true;
4368 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004369
Sean Hunte16da072011-10-10 06:18:57 +00004370 // Finding the corresponding member in the base should lead to a
4371 // unique, accessible, non-deleted function.
4372 if (CSM != CXXDestructor) {
4373 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004374 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004375 false);
4376 if (!SMOR->hasSuccess())
4377 return true;
4378 CXXMethodDecl *BaseMember = SMOR->getMethod();
4379 if (IsConstructor) {
4380 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4381 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4382 PDiag()) != AR_accessible)
4383 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004384
4385 // For a move operation, the corresponding operation must actually
4386 // be a move operation (and not a copy selected by overload
4387 // resolution) unless we are working on a trivially copyable class.
4388 if (IsMove && !BaseCtor->isMoveConstructor() &&
4389 !BaseDecl->isTriviallyCopyable())
4390 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004391 }
4392 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004393 }
4394
4395 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4396 FE = RD->field_end();
4397 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004398 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004399 continue;
4400
Sean Huntcdee3fe2011-05-11 22:34:38 +00004401 QualType FieldType = Context.getBaseElementType(FI->getType());
4402 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004403
Sean Hunte16da072011-10-10 06:18:57 +00004404 // For a default constructor, all references must be initialized in-class
4405 // and, if a union, it must have a non-const member.
4406 if (CSM == CXXDefaultConstructor) {
4407 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4408 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004409
Sean Hunte16da072011-10-10 06:18:57 +00004410 if (IsUnion && !FieldType.isConstQualified())
4411 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004412 // For a copy constructor, data members must not be of rvalue reference
4413 // type.
4414 } else if (CSM == CXXCopyConstructor) {
4415 if (FieldType->isRValueReferenceType())
4416 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004417 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004418
4419 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004420 // For a default constructor, a const member must have a user-provided
4421 // default constructor or else be explicitly initialized.
4422 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004423 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004424 !FieldRecord->hasUserProvidedDefaultConstructor())
4425 return true;
4426
Sean Huntc32d6842011-10-11 04:55:36 +00004427 // Some additional restrictions exist on the variant members.
4428 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004429 FieldRecord->isAnonymousStructOrUnion()) {
4430 // We're okay to reuse AllConst here since we only care about the
4431 // value otherwise if we're in a union.
4432 AllConst = true;
4433
4434 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4435 UE = FieldRecord->field_end();
4436 UI != UE; ++UI) {
4437 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4438 CXXRecordDecl *UnionFieldRecord =
4439 UnionFieldType->getAsCXXRecordDecl();
4440
4441 if (!UnionFieldType.isConstQualified())
4442 AllConst = false;
4443
Sean Huntc32d6842011-10-11 04:55:36 +00004444 if (UnionFieldRecord) {
4445 // FIXME: Checking for accessibility and validity of this
4446 // destructor is technically going beyond the
4447 // standard, but this is believed to be a defect.
4448 if (!IsAssignment) {
4449 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4450 if (FieldDtor->isDeleted())
4451 return true;
4452 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4453 AR_accessible)
4454 return true;
4455 if (!FieldDtor->isTrivial())
4456 return true;
4457 }
4458
4459 if (CSM != CXXDestructor) {
4460 SpecialMemberOverloadResult *SMOR =
4461 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004462 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004463 // FIXME: Checking for accessibility and validity of this
4464 // corresponding member is technically going beyond the
4465 // standard, but this is believed to be a defect.
4466 if (!SMOR->hasSuccess())
4467 return true;
4468
4469 CXXMethodDecl *FieldMember = SMOR->getMethod();
4470 // A member of a union must have a trivial corresponding
4471 // constructor.
4472 if (!FieldMember->isTrivial())
4473 return true;
4474
4475 if (IsConstructor) {
4476 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4477 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4478 PDiag()) != AR_accessible)
4479 return true;
4480 }
4481 }
4482 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004483 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004484
Sean Huntc32d6842011-10-11 04:55:36 +00004485 // At least one member in each anonymous union must be non-const
4486 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004487 return true;
4488
4489 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004490 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004491 continue;
4492 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004493
Sean Huntc32d6842011-10-11 04:55:36 +00004494 // Unless we're doing assignment, the field's destructor must be
4495 // accessible and not deleted.
4496 if (!IsAssignment) {
4497 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4498 if (FieldDtor->isDeleted())
4499 return true;
4500 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4501 AR_accessible)
4502 return true;
4503 }
4504
Sean Hunte16da072011-10-10 06:18:57 +00004505 // Check that the corresponding member of the field is accessible,
4506 // unique, and non-deleted. We don't do this if it has an explicit
4507 // initialization when default-constructing.
4508 if (CSM != CXXDestructor &&
4509 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4510 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004511 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004512 false);
4513 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004514 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004515
4516 CXXMethodDecl *FieldMember = SMOR->getMethod();
4517 if (IsConstructor) {
4518 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4519 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4520 PDiag()) != AR_accessible)
4521 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004522
4523 // For a move operation, the corresponding operation must actually
4524 // be a move operation (and not a copy selected by overload
4525 // resolution) unless we are working on a trivially copyable class.
4526 if (IsMove && !FieldCtor->isMoveConstructor() &&
4527 !FieldRecord->isTriviallyCopyable())
4528 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004529 }
4530
4531 // We need the corresponding member of a union to be trivial so that
4532 // we can safely copy them all simultaneously.
4533 // FIXME: Note that performing the check here (where we rely on the lack
4534 // of an in-class initializer) is technically ill-formed. However, this
4535 // seems most obviously to be a bug in the standard.
4536 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004537 return true;
4538 }
Sean Hunte16da072011-10-10 06:18:57 +00004539 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4540 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4541 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004542 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004543 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004544 }
4545
Sean Hunte16da072011-10-10 06:18:57 +00004546 // We can't have all const members in a union when default-constructing,
4547 // or else they're all nonsensical garbage values that can't be changed.
4548 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004549 return true;
4550
4551 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004552}
4553
Sean Hunt7f410192011-05-14 05:23:24 +00004554bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4555 CXXRecordDecl *RD = MD->getParent();
4556 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004557 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004558 return false;
4559
Sean Hunt71a682f2011-05-18 03:41:58 +00004560 SourceLocation Loc = MD->getLocation();
4561
Sean Hunt7f410192011-05-14 05:23:24 +00004562 // Do access control from the constructor
4563 ContextRAII MethodContext(*this, MD);
4564
4565 bool Union = RD->isUnion();
4566
Sean Hunt661c67a2011-06-21 23:42:56 +00004567 unsigned ArgQuals =
4568 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4569 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004570
4571 // We do this because we should never actually use an anonymous
4572 // union's constructor.
4573 if (Union && RD->isAnonymousStructOrUnion())
4574 return false;
4575
Sean Hunt7f410192011-05-14 05:23:24 +00004576 // FIXME: We should put some diagnostic logic right into this function.
4577
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004578 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004579 // A defaulted [copy] assignment operator for class X is defined as deleted
4580 // if X has:
4581
4582 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4583 BE = RD->bases_end();
4584 BI != BE; ++BI) {
4585 // We'll handle this one later
4586 if (BI->isVirtual())
4587 continue;
4588
4589 QualType BaseType = BI->getType();
4590 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4591 assert(BaseDecl && "base isn't a CXXRecordDecl");
4592
4593 // -- a [direct base class] B that cannot be [copied] because overload
4594 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004595 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004596 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004597 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4598 0);
4599 if (!CopyOper || CopyOper->isDeleted())
4600 return true;
4601 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004602 return true;
4603 }
4604
4605 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4606 BE = RD->vbases_end();
4607 BI != BE; ++BI) {
4608 QualType BaseType = BI->getType();
4609 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4610 assert(BaseDecl && "base isn't a CXXRecordDecl");
4611
Sean Hunt7f410192011-05-14 05:23:24 +00004612 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004613 // resolution, as applied to B's [copy] assignment operator, results in
4614 // an ambiguity or a function that is deleted or inaccessible from the
4615 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004616 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4617 0);
4618 if (!CopyOper || CopyOper->isDeleted())
4619 return true;
4620 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004621 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004622 }
4623
4624 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4625 FE = RD->field_end();
4626 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004627 if (FI->isUnnamedBitfield())
4628 continue;
4629
Sean Hunt7f410192011-05-14 05:23:24 +00004630 QualType FieldType = Context.getBaseElementType(FI->getType());
4631
4632 // -- a non-static data member of reference type
4633 if (FieldType->isReferenceType())
4634 return true;
4635
4636 // -- a non-static data member of const non-class type (or array thereof)
4637 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4638 return true;
4639
4640 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4641
4642 if (FieldRecord) {
4643 // This is an anonymous union
4644 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4645 // Anonymous unions inside unions do not variant members create
4646 if (!Union) {
4647 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4648 UE = FieldRecord->field_end();
4649 UI != UE; ++UI) {
4650 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4651 CXXRecordDecl *UnionFieldRecord =
4652 UnionFieldType->getAsCXXRecordDecl();
4653
4654 // -- a variant member with a non-trivial [copy] assignment operator
4655 // and X is a union-like class
4656 if (UnionFieldRecord &&
4657 !UnionFieldRecord->hasTrivialCopyAssignment())
4658 return true;
4659 }
4660 }
4661
4662 // Don't try to initalize an anonymous union
4663 continue;
4664 // -- a variant member with a non-trivial [copy] assignment operator
4665 // and X is a union-like class
4666 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4667 return true;
4668 }
Sean Hunt7f410192011-05-14 05:23:24 +00004669
Sean Hunt661c67a2011-06-21 23:42:56 +00004670 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4671 false, 0);
4672 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004673 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004674 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004675 return true;
4676 }
4677 }
4678
4679 return false;
4680}
4681
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004682bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4683 CXXRecordDecl *RD = MD->getParent();
4684 assert(!RD->isDependentType() && "do deletion after instantiation");
4685 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4686 return false;
4687
4688 SourceLocation Loc = MD->getLocation();
4689
4690 // Do access control from the constructor
4691 ContextRAII MethodContext(*this, MD);
4692
4693 bool Union = RD->isUnion();
4694
4695 // We do this because we should never actually use an anonymous
4696 // union's constructor.
4697 if (Union && RD->isAnonymousStructOrUnion())
4698 return false;
4699
4700 // C++0x [class.copy]/20
4701 // A defaulted [move] assignment operator for class X is defined as deleted
4702 // if X has:
4703
4704 // -- for the move constructor, [...] any direct or indirect virtual base
4705 // class.
4706 if (RD->getNumVBases() != 0)
4707 return true;
4708
4709 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4710 BE = RD->bases_end();
4711 BI != BE; ++BI) {
4712
4713 QualType BaseType = BI->getType();
4714 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4715 assert(BaseDecl && "base isn't a CXXRecordDecl");
4716
4717 // -- a [direct base class] B that cannot be [moved] because overload
4718 // resolution, as applied to B's [move] assignment operator, results in
4719 // an ambiguity or a function that is deleted or inaccessible from the
4720 // assignment operator
4721 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4722 if (!MoveOper || MoveOper->isDeleted())
4723 return true;
4724 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4725 return true;
4726
4727 // -- for the move assignment operator, a [direct base class] with a type
4728 // that does not have a move assignment operator and is not trivially
4729 // copyable.
4730 if (!MoveOper->isMoveAssignmentOperator() &&
4731 !BaseDecl->isTriviallyCopyable())
4732 return true;
4733 }
4734
4735 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4736 FE = RD->field_end();
4737 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004738 if (FI->isUnnamedBitfield())
4739 continue;
4740
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004741 QualType FieldType = Context.getBaseElementType(FI->getType());
4742
4743 // -- a non-static data member of reference type
4744 if (FieldType->isReferenceType())
4745 return true;
4746
4747 // -- a non-static data member of const non-class type (or array thereof)
4748 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4749 return true;
4750
4751 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4752
4753 if (FieldRecord) {
4754 // This is an anonymous union
4755 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4756 // Anonymous unions inside unions do not variant members create
4757 if (!Union) {
4758 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4759 UE = FieldRecord->field_end();
4760 UI != UE; ++UI) {
4761 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4762 CXXRecordDecl *UnionFieldRecord =
4763 UnionFieldType->getAsCXXRecordDecl();
4764
4765 // -- a variant member with a non-trivial [move] assignment operator
4766 // and X is a union-like class
4767 if (UnionFieldRecord &&
4768 !UnionFieldRecord->hasTrivialMoveAssignment())
4769 return true;
4770 }
4771 }
4772
4773 // Don't try to initalize an anonymous union
4774 continue;
4775 // -- a variant member with a non-trivial [move] assignment operator
4776 // and X is a union-like class
4777 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4778 return true;
4779 }
4780
4781 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4782 if (!MoveOper || MoveOper->isDeleted())
4783 return true;
4784 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4785 return true;
4786
4787 // -- for the move assignment operator, a [non-static data member] with a
4788 // type that does not have a move assignment operator and is not
4789 // trivially copyable.
4790 if (!MoveOper->isMoveAssignmentOperator() &&
4791 !FieldRecord->isTriviallyCopyable())
4792 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004793 }
Sean Hunt7f410192011-05-14 05:23:24 +00004794 }
4795
4796 return false;
4797}
4798
Sean Huntcb45a0f2011-05-12 22:46:25 +00004799bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4800 CXXRecordDecl *RD = DD->getParent();
4801 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004802 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004803 return false;
4804
Sean Hunt71a682f2011-05-18 03:41:58 +00004805 SourceLocation Loc = DD->getLocation();
4806
Sean Huntcb45a0f2011-05-12 22:46:25 +00004807 // Do access control from the destructor
4808 ContextRAII CtorContext(*this, DD);
4809
4810 bool Union = RD->isUnion();
4811
Sean Hunt49634cf2011-05-13 06:10:58 +00004812 // We do this because we should never actually use an anonymous
4813 // union's destructor.
4814 if (Union && RD->isAnonymousStructOrUnion())
4815 return false;
4816
Sean Huntcb45a0f2011-05-12 22:46:25 +00004817 // C++0x [class.dtor]p5
4818 // A defaulted destructor for a class X is defined as deleted if:
4819 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4820 BE = RD->bases_end();
4821 BI != BE; ++BI) {
4822 // We'll handle this one later
4823 if (BI->isVirtual())
4824 continue;
4825
4826 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4827 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4828 assert(BaseDtor && "base has no destructor");
4829
4830 // -- any direct or virtual base class has a deleted destructor or
4831 // a destructor that is inaccessible from the defaulted destructor
4832 if (BaseDtor->isDeleted())
4833 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004834 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004835 AR_accessible)
4836 return true;
4837 }
4838
4839 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4840 BE = RD->vbases_end();
4841 BI != BE; ++BI) {
4842 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4843 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4844 assert(BaseDtor && "base has no destructor");
4845
4846 // -- any direct or virtual base class has a deleted destructor or
4847 // a destructor that is inaccessible from the defaulted destructor
4848 if (BaseDtor->isDeleted())
4849 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004850 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004851 AR_accessible)
4852 return true;
4853 }
4854
4855 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4856 FE = RD->field_end();
4857 FI != FE; ++FI) {
4858 QualType FieldType = Context.getBaseElementType(FI->getType());
4859 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4860 if (FieldRecord) {
4861 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4862 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4863 UE = FieldRecord->field_end();
4864 UI != UE; ++UI) {
4865 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4866 CXXRecordDecl *UnionFieldRecord =
4867 UnionFieldType->getAsCXXRecordDecl();
4868
4869 // -- X is a union-like class that has a variant member with a non-
4870 // trivial destructor.
4871 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4872 return true;
4873 }
4874 // Technically we are supposed to do this next check unconditionally.
4875 // But that makes absolutely no sense.
4876 } else {
4877 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4878
4879 // -- any of the non-static data members has class type M (or array
4880 // thereof) and M has a deleted destructor or a destructor that is
4881 // inaccessible from the defaulted destructor
4882 if (FieldDtor->isDeleted())
4883 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004884 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004885 AR_accessible)
4886 return true;
4887
4888 // -- X is a union-like class that has a variant member with a non-
4889 // trivial destructor.
4890 if (Union && !FieldDtor->isTrivial())
4891 return true;
4892 }
4893 }
4894 }
4895
4896 if (DD->isVirtual()) {
4897 FunctionDecl *OperatorDelete = 0;
4898 DeclarationName Name =
4899 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004900 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004901 false))
4902 return true;
4903 }
4904
4905
4906 return false;
4907}
4908
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004909/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004910namespace {
4911 struct FindHiddenVirtualMethodData {
4912 Sema *S;
4913 CXXMethodDecl *Method;
4914 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004915 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004916 };
4917}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004918
4919/// \brief Member lookup function that determines whether a given C++
4920/// method overloads virtual methods in a base class without overriding any,
4921/// to be used with CXXRecordDecl::lookupInBases().
4922static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4923 CXXBasePath &Path,
4924 void *UserData) {
4925 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4926
4927 FindHiddenVirtualMethodData &Data
4928 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4929
4930 DeclarationName Name = Data.Method->getDeclName();
4931 assert(Name.getNameKind() == DeclarationName::Identifier);
4932
4933 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004934 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004935 for (Path.Decls = BaseRecord->lookup(Name);
4936 Path.Decls.first != Path.Decls.second;
4937 ++Path.Decls.first) {
4938 NamedDecl *D = *Path.Decls.first;
4939 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004940 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004941 foundSameNameMethod = true;
4942 // Interested only in hidden virtual methods.
4943 if (!MD->isVirtual())
4944 continue;
4945 // If the method we are checking overrides a method from its base
4946 // don't warn about the other overloaded methods.
4947 if (!Data.S->IsOverload(Data.Method, MD, false))
4948 return true;
4949 // Collect the overload only if its hidden.
4950 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4951 overloadedMethods.push_back(MD);
4952 }
4953 }
4954
4955 if (foundSameNameMethod)
4956 Data.OverloadedMethods.append(overloadedMethods.begin(),
4957 overloadedMethods.end());
4958 return foundSameNameMethod;
4959}
4960
4961/// \brief See if a method overloads virtual methods in a base class without
4962/// overriding any.
4963void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4964 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004965 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004966 return;
4967 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4968 return;
4969
4970 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4971 /*bool RecordPaths=*/false,
4972 /*bool DetectVirtual=*/false);
4973 FindHiddenVirtualMethodData Data;
4974 Data.Method = MD;
4975 Data.S = this;
4976
4977 // Keep the base methods that were overriden or introduced in the subclass
4978 // by 'using' in a set. A base method not in this set is hidden.
4979 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4980 res.first != res.second; ++res.first) {
4981 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4982 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4983 E = MD->end_overridden_methods();
4984 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004985 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004986 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4987 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004988 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004989 }
4990
4991 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4992 !Data.OverloadedMethods.empty()) {
4993 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4994 << MD << (Data.OverloadedMethods.size() > 1);
4995
4996 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4997 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4998 Diag(overloadedMD->getLocation(),
4999 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5000 }
5001 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005002}
5003
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005004void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005005 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005006 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005007 SourceLocation RBrac,
5008 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005009 if (!TagDecl)
5010 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005011
Douglas Gregor42af25f2009-05-11 19:58:34 +00005012 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005013
David Blaikie77b6de02011-09-22 02:58:26 +00005014 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005015 // strict aliasing violation!
5016 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005017 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005018
Douglas Gregor23c94db2010-07-02 17:43:08 +00005019 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005020 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005021}
5022
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005023/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5024/// special functions, such as the default constructor, copy
5025/// constructor, or destructor, to the given C++ class (C++
5026/// [special]p1). This routine can only be executed just before the
5027/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005028void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005029 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005030 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005031
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005032 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005033 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005034
Richard Smithb701d3d2011-12-24 21:56:24 +00005035 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5036 ++ASTContext::NumImplicitMoveConstructors;
5037
Douglas Gregora376d102010-07-02 21:50:04 +00005038 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5039 ++ASTContext::NumImplicitCopyAssignmentOperators;
5040
5041 // If we have a dynamic class, then the copy assignment operator may be
5042 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5043 // it shows up in the right place in the vtable and that we diagnose
5044 // problems with the implicit exception specification.
5045 if (ClassDecl->isDynamicClass())
5046 DeclareImplicitCopyAssignment(ClassDecl);
5047 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005048
Richard Smithb701d3d2011-12-24 21:56:24 +00005049 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5050 ++ASTContext::NumImplicitMoveAssignmentOperators;
5051
5052 // Likewise for the move assignment operator.
5053 if (ClassDecl->isDynamicClass())
5054 DeclareImplicitMoveAssignment(ClassDecl);
5055 }
5056
Douglas Gregor4923aa22010-07-02 20:37:36 +00005057 if (!ClassDecl->hasUserDeclaredDestructor()) {
5058 ++ASTContext::NumImplicitDestructors;
5059
5060 // If we have a dynamic class, then the destructor may be virtual, so we
5061 // have to declare the destructor immediately. This ensures that, e.g., it
5062 // shows up in the right place in the vtable and that we diagnose problems
5063 // with the implicit exception specification.
5064 if (ClassDecl->isDynamicClass())
5065 DeclareImplicitDestructor(ClassDecl);
5066 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005067}
5068
Francois Pichet8387e2a2011-04-22 22:18:13 +00005069void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5070 if (!D)
5071 return;
5072
5073 int NumParamList = D->getNumTemplateParameterLists();
5074 for (int i = 0; i < NumParamList; i++) {
5075 TemplateParameterList* Params = D->getTemplateParameterList(i);
5076 for (TemplateParameterList::iterator Param = Params->begin(),
5077 ParamEnd = Params->end();
5078 Param != ParamEnd; ++Param) {
5079 NamedDecl *Named = cast<NamedDecl>(*Param);
5080 if (Named->getDeclName()) {
5081 S->AddDecl(Named);
5082 IdResolver.AddDecl(Named);
5083 }
5084 }
5085 }
5086}
5087
John McCalld226f652010-08-21 09:40:31 +00005088void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005089 if (!D)
5090 return;
5091
5092 TemplateParameterList *Params = 0;
5093 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5094 Params = Template->getTemplateParameters();
5095 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5096 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5097 Params = PartialSpec->getTemplateParameters();
5098 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005099 return;
5100
Douglas Gregor6569d682009-05-27 23:11:45 +00005101 for (TemplateParameterList::iterator Param = Params->begin(),
5102 ParamEnd = Params->end();
5103 Param != ParamEnd; ++Param) {
5104 NamedDecl *Named = cast<NamedDecl>(*Param);
5105 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005106 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005107 IdResolver.AddDecl(Named);
5108 }
5109 }
5110}
5111
John McCalld226f652010-08-21 09:40:31 +00005112void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005113 if (!RecordD) return;
5114 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005115 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005116 PushDeclContext(S, Record);
5117}
5118
John McCalld226f652010-08-21 09:40:31 +00005119void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005120 if (!RecordD) return;
5121 PopDeclContext();
5122}
5123
Douglas Gregor72b505b2008-12-16 21:30:33 +00005124/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5125/// parsing a top-level (non-nested) C++ class, and we are now
5126/// parsing those parts of the given Method declaration that could
5127/// not be parsed earlier (C++ [class.mem]p2), such as default
5128/// arguments. This action should enter the scope of the given
5129/// Method declaration as if we had just parsed the qualified method
5130/// name. However, it should not bring the parameters into scope;
5131/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005132void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005133}
5134
5135/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5136/// C++ method declaration. We're (re-)introducing the given
5137/// function parameter into scope for use in parsing later parts of
5138/// the method declaration. For example, we could see an
5139/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005140void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005141 if (!ParamD)
5142 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005143
John McCalld226f652010-08-21 09:40:31 +00005144 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005145
5146 // If this parameter has an unparsed default argument, clear it out
5147 // to make way for the parsed default argument.
5148 if (Param->hasUnparsedDefaultArg())
5149 Param->setDefaultArg(0);
5150
John McCalld226f652010-08-21 09:40:31 +00005151 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005152 if (Param->getDeclName())
5153 IdResolver.AddDecl(Param);
5154}
5155
5156/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5157/// processing the delayed method declaration for Method. The method
5158/// declaration is now considered finished. There may be a separate
5159/// ActOnStartOfFunctionDef action later (not necessarily
5160/// immediately!) for this method, if it was also defined inside the
5161/// class body.
John McCalld226f652010-08-21 09:40:31 +00005162void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005163 if (!MethodD)
5164 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005166 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005167
John McCalld226f652010-08-21 09:40:31 +00005168 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005169
5170 // Now that we have our default arguments, check the constructor
5171 // again. It could produce additional diagnostics or affect whether
5172 // the class has implicitly-declared destructors, among other
5173 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005174 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5175 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005176
5177 // Check the default arguments, which we may have added.
5178 if (!Method->isInvalidDecl())
5179 CheckCXXDefaultArguments(Method);
5180}
5181
Douglas Gregor42a552f2008-11-05 20:51:48 +00005182/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005183/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005184/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005185/// emit diagnostics and set the invalid bit to true. In any case, the type
5186/// will be updated to reflect a well-formed type for the constructor and
5187/// returned.
5188QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005189 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005190 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005191
5192 // C++ [class.ctor]p3:
5193 // A constructor shall not be virtual (10.3) or static (9.4). A
5194 // constructor can be invoked for a const, volatile or const
5195 // volatile object. A constructor shall not be declared const,
5196 // volatile, or const volatile (9.3.2).
5197 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005198 if (!D.isInvalidType())
5199 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5200 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5201 << SourceRange(D.getIdentifierLoc());
5202 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005203 }
John McCalld931b082010-08-26 03:08:43 +00005204 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005205 if (!D.isInvalidType())
5206 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5207 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5208 << SourceRange(D.getIdentifierLoc());
5209 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005210 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005211 }
Mike Stump1eb44332009-09-09 15:08:12 +00005212
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005213 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005214 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005215 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005216 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5217 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005218 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005219 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5220 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005221 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005222 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5223 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005224 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005225 }
Mike Stump1eb44332009-09-09 15:08:12 +00005226
Douglas Gregorc938c162011-01-26 05:01:58 +00005227 // C++0x [class.ctor]p4:
5228 // A constructor shall not be declared with a ref-qualifier.
5229 if (FTI.hasRefQualifier()) {
5230 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5231 << FTI.RefQualifierIsLValueRef
5232 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5233 D.setInvalidType();
5234 }
5235
Douglas Gregor42a552f2008-11-05 20:51:48 +00005236 // Rebuild the function type "R" without any type qualifiers (in
5237 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005238 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005239 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005240 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5241 return R;
5242
5243 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5244 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005245 EPI.RefQualifier = RQ_None;
5246
Chris Lattner65401802009-04-25 08:28:21 +00005247 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005248 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005249}
5250
Douglas Gregor72b505b2008-12-16 21:30:33 +00005251/// CheckConstructor - Checks a fully-formed constructor for
5252/// well-formedness, issuing any diagnostics required. Returns true if
5253/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005254void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005255 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005256 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5257 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005258 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005259
5260 // C++ [class.copy]p3:
5261 // A declaration of a constructor for a class X is ill-formed if
5262 // its first parameter is of type (optionally cv-qualified) X and
5263 // either there are no other parameters or else all other
5264 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005265 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005266 ((Constructor->getNumParams() == 1) ||
5267 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005268 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5269 Constructor->getTemplateSpecializationKind()
5270 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005271 QualType ParamType = Constructor->getParamDecl(0)->getType();
5272 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5273 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005274 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005275 const char *ConstRef
5276 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5277 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005278 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005279 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005280
5281 // FIXME: Rather that making the constructor invalid, we should endeavor
5282 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005283 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005284 }
5285 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005286}
5287
John McCall15442822010-08-04 01:04:25 +00005288/// CheckDestructor - Checks a fully-formed destructor definition for
5289/// well-formedness, issuing any diagnostics required. Returns true
5290/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005291bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005292 CXXRecordDecl *RD = Destructor->getParent();
5293
5294 if (Destructor->isVirtual()) {
5295 SourceLocation Loc;
5296
5297 if (!Destructor->isImplicit())
5298 Loc = Destructor->getLocation();
5299 else
5300 Loc = RD->getLocation();
5301
5302 // If we have a virtual destructor, look up the deallocation function
5303 FunctionDecl *OperatorDelete = 0;
5304 DeclarationName Name =
5305 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005306 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005307 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005308
5309 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005310
5311 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005312 }
Anders Carlsson37909802009-11-30 21:24:50 +00005313
5314 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005315}
5316
Mike Stump1eb44332009-09-09 15:08:12 +00005317static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005318FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5319 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5320 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005321 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005322}
5323
Douglas Gregor42a552f2008-11-05 20:51:48 +00005324/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5325/// the well-formednes of the destructor declarator @p D with type @p
5326/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005327/// emit diagnostics and set the declarator to invalid. Even if this happens,
5328/// will be updated to reflect a well-formed type for the destructor and
5329/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005330QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005331 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005332 // C++ [class.dtor]p1:
5333 // [...] A typedef-name that names a class is a class-name
5334 // (7.1.3); however, a typedef-name that names a class shall not
5335 // be used as the identifier in the declarator for a destructor
5336 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005337 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005338 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005339 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005340 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005341 else if (const TemplateSpecializationType *TST =
5342 DeclaratorType->getAs<TemplateSpecializationType>())
5343 if (TST->isTypeAlias())
5344 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5345 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005346
5347 // C++ [class.dtor]p2:
5348 // A destructor is used to destroy objects of its class type. A
5349 // destructor takes no parameters, and no return type can be
5350 // specified for it (not even void). The address of a destructor
5351 // shall not be taken. A destructor shall not be static. A
5352 // destructor can be invoked for a const, volatile or const
5353 // volatile object. A destructor shall not be declared const,
5354 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005355 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005356 if (!D.isInvalidType())
5357 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5358 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005359 << SourceRange(D.getIdentifierLoc())
5360 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5361
John McCalld931b082010-08-26 03:08:43 +00005362 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005363 }
Chris Lattner65401802009-04-25 08:28:21 +00005364 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005365 // Destructors don't have return types, but the parser will
5366 // happily parse something like:
5367 //
5368 // class X {
5369 // float ~X();
5370 // };
5371 //
5372 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005373 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5374 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5375 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005376 }
Mike Stump1eb44332009-09-09 15:08:12 +00005377
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005378 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005379 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005380 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005381 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5382 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005383 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005384 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5385 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005386 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005387 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5388 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005389 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005390 }
5391
Douglas Gregorc938c162011-01-26 05:01:58 +00005392 // C++0x [class.dtor]p2:
5393 // A destructor shall not be declared with a ref-qualifier.
5394 if (FTI.hasRefQualifier()) {
5395 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5396 << FTI.RefQualifierIsLValueRef
5397 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5398 D.setInvalidType();
5399 }
5400
Douglas Gregor42a552f2008-11-05 20:51:48 +00005401 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005402 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005403 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5404
5405 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005406 FTI.freeArgs();
5407 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005408 }
5409
Mike Stump1eb44332009-09-09 15:08:12 +00005410 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005411 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005412 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005413 D.setInvalidType();
5414 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005415
5416 // Rebuild the function type "R" without any type qualifiers or
5417 // parameters (in case any of the errors above fired) and with
5418 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005419 // types.
John McCalle23cf432010-12-14 08:05:40 +00005420 if (!D.isInvalidType())
5421 return R;
5422
Douglas Gregord92ec472010-07-01 05:10:53 +00005423 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005424 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5425 EPI.Variadic = false;
5426 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005427 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005428 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005429}
5430
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005431/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5432/// well-formednes of the conversion function declarator @p D with
5433/// type @p R. If there are any errors in the declarator, this routine
5434/// will emit diagnostics and return true. Otherwise, it will return
5435/// false. Either way, the type @p R will be updated to reflect a
5436/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005437void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005438 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005439 // C++ [class.conv.fct]p1:
5440 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005441 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005442 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005443 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005444 if (!D.isInvalidType())
5445 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5446 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5447 << SourceRange(D.getIdentifierLoc());
5448 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005449 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005450 }
John McCalla3f81372010-04-13 00:04:31 +00005451
5452 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5453
Chris Lattner6e475012009-04-25 08:35:12 +00005454 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005455 // Conversion functions don't have return types, but the parser will
5456 // happily parse something like:
5457 //
5458 // class X {
5459 // float operator bool();
5460 // };
5461 //
5462 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005463 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5464 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5465 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005466 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005467 }
5468
John McCalla3f81372010-04-13 00:04:31 +00005469 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5470
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005471 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005472 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005473 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5474
5475 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005476 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005477 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005478 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005479 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005480 D.setInvalidType();
5481 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005482
John McCalla3f81372010-04-13 00:04:31 +00005483 // Diagnose "&operator bool()" and other such nonsense. This
5484 // is actually a gcc extension which we don't support.
5485 if (Proto->getResultType() != ConvType) {
5486 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5487 << Proto->getResultType();
5488 D.setInvalidType();
5489 ConvType = Proto->getResultType();
5490 }
5491
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005492 // C++ [class.conv.fct]p4:
5493 // The conversion-type-id shall not represent a function type nor
5494 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005495 if (ConvType->isArrayType()) {
5496 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5497 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005498 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005499 } else if (ConvType->isFunctionType()) {
5500 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5501 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005502 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005503 }
5504
5505 // Rebuild the function type "R" without any parameters (in case any
5506 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005507 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005508 if (D.isInvalidType())
5509 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005510
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005511 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005512 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005513 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005514 getLangOptions().CPlusPlus0x ?
5515 diag::warn_cxx98_compat_explicit_conversion_functions :
5516 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005517 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005518}
5519
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005520/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5521/// the declaration of the given C++ conversion function. This routine
5522/// is responsible for recording the conversion function in the C++
5523/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005524Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005525 assert(Conversion && "Expected to receive a conversion function declaration");
5526
Douglas Gregor9d350972008-12-12 08:25:50 +00005527 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005528
5529 // Make sure we aren't redeclaring the conversion function.
5530 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005531
5532 // C++ [class.conv.fct]p1:
5533 // [...] A conversion function is never used to convert a
5534 // (possibly cv-qualified) object to the (possibly cv-qualified)
5535 // same object type (or a reference to it), to a (possibly
5536 // cv-qualified) base class of that type (or a reference to it),
5537 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005538 // FIXME: Suppress this warning if the conversion function ends up being a
5539 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005540 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005541 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005542 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005543 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005544 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5545 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005546 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005547 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005548 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5549 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005550 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005551 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005552 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005553 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005554 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005555 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005556 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005557 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005558 }
5559
Douglas Gregore80622f2010-09-29 04:25:11 +00005560 if (FunctionTemplateDecl *ConversionTemplate
5561 = Conversion->getDescribedFunctionTemplate())
5562 return ConversionTemplate;
5563
John McCalld226f652010-08-21 09:40:31 +00005564 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005565}
5566
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005567//===----------------------------------------------------------------------===//
5568// Namespace Handling
5569//===----------------------------------------------------------------------===//
5570
John McCallea318642010-08-26 09:15:37 +00005571
5572
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005573/// ActOnStartNamespaceDef - This is called at the start of a namespace
5574/// definition.
John McCalld226f652010-08-21 09:40:31 +00005575Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005576 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005577 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005578 SourceLocation IdentLoc,
5579 IdentifierInfo *II,
5580 SourceLocation LBrace,
5581 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005582 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5583 // For anonymous namespace, take the location of the left brace.
5584 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005585 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005586 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005587 bool IsStd = false;
5588 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005589 Scope *DeclRegionScope = NamespcScope->getParent();
5590
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005591 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005592 if (II) {
5593 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005594 // The identifier in an original-namespace-definition shall not
5595 // have been previously defined in the declarative region in
5596 // which the original-namespace-definition appears. The
5597 // identifier in an original-namespace-definition is the name of
5598 // the namespace. Subsequently in that declarative region, it is
5599 // treated as an original-namespace-name.
5600 //
5601 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005602 // look through using directives, just look for any ordinary names.
5603
5604 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005605 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5606 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005607 NamedDecl *PrevDecl = 0;
5608 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005609 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005610 R.first != R.second; ++R.first) {
5611 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5612 PrevDecl = *R.first;
5613 break;
5614 }
5615 }
5616
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005617 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5618
5619 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005620 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005621 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005622 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005623 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005624 // The user probably just forgot the 'inline', so suggest that it
5625 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005626 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005627 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5628 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005629 Diag(Loc, diag::err_inline_namespace_mismatch)
5630 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005631 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005632 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5633
5634 IsInline = PrevNS->isInline();
5635 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005636 } else if (PrevDecl) {
5637 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005638 Diag(Loc, diag::err_redefinition_different_kind)
5639 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005640 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005641 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005642 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005643 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005644 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005645 // This is the first "real" definition of the namespace "std", so update
5646 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005647 PrevNS = getStdNamespace();
5648 IsStd = true;
5649 AddToKnown = !IsInline;
5650 } else {
5651 // We've seen this namespace for the first time.
5652 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005653 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005654 } else {
John McCall9aeed322009-10-01 00:25:31 +00005655 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005656
5657 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005658 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005659 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005660 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005661 } else {
5662 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005663 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005664 }
5665
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005666 if (PrevNS && IsInline != PrevNS->isInline()) {
5667 // inline-ness must match
5668 Diag(Loc, diag::err_inline_namespace_mismatch)
5669 << IsInline;
5670 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005671
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005672 // Recover by ignoring the new namespace's inline status.
5673 IsInline = PrevNS->isInline();
5674 }
5675 }
5676
5677 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5678 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005679 if (IsInvalid)
5680 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005681
5682 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005683
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005684 // FIXME: Should we be merging attributes?
5685 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005686 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005687
5688 if (IsStd)
5689 StdNamespace = Namespc;
5690 if (AddToKnown)
5691 KnownNamespaces[Namespc] = false;
5692
5693 if (II) {
5694 PushOnScopeChains(Namespc, DeclRegionScope);
5695 } else {
5696 // Link the anonymous namespace into its parent.
5697 DeclContext *Parent = CurContext->getRedeclContext();
5698 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5699 TU->setAnonymousNamespace(Namespc);
5700 } else {
5701 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005702 }
John McCall9aeed322009-10-01 00:25:31 +00005703
Douglas Gregora4181472010-03-24 00:46:35 +00005704 CurContext->addDecl(Namespc);
5705
John McCall9aeed322009-10-01 00:25:31 +00005706 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5707 // behaves as if it were replaced by
5708 // namespace unique { /* empty body */ }
5709 // using namespace unique;
5710 // namespace unique { namespace-body }
5711 // where all occurrences of 'unique' in a translation unit are
5712 // replaced by the same identifier and this identifier differs
5713 // from all other identifiers in the entire program.
5714
5715 // We just create the namespace with an empty name and then add an
5716 // implicit using declaration, just like the standard suggests.
5717 //
5718 // CodeGen enforces the "universally unique" aspect by giving all
5719 // declarations semantically contained within an anonymous
5720 // namespace internal linkage.
5721
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005722 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005723 UsingDirectiveDecl* UD
5724 = UsingDirectiveDecl::Create(Context, CurContext,
5725 /* 'using' */ LBrace,
5726 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005727 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005728 /* identifier */ SourceLocation(),
5729 Namespc,
5730 /* Ancestor */ CurContext);
5731 UD->setImplicit();
5732 CurContext->addDecl(UD);
5733 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005734 }
5735
5736 // Although we could have an invalid decl (i.e. the namespace name is a
5737 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005738 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5739 // for the namespace has the declarations that showed up in that particular
5740 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005741 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005742 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005743}
5744
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005745/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5746/// is a namespace alias, returns the namespace it points to.
5747static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5748 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5749 return AD->getNamespace();
5750 return dyn_cast_or_null<NamespaceDecl>(D);
5751}
5752
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005753/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5754/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005755void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005756 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5757 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005758 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005759 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005760 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005761 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005762}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005763
John McCall384aff82010-08-25 07:42:41 +00005764CXXRecordDecl *Sema::getStdBadAlloc() const {
5765 return cast_or_null<CXXRecordDecl>(
5766 StdBadAlloc.get(Context.getExternalSource()));
5767}
5768
5769NamespaceDecl *Sema::getStdNamespace() const {
5770 return cast_or_null<NamespaceDecl>(
5771 StdNamespace.get(Context.getExternalSource()));
5772}
5773
Douglas Gregor66992202010-06-29 17:53:46 +00005774/// \brief Retrieve the special "std" namespace, which may require us to
5775/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005776NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005777 if (!StdNamespace) {
5778 // The "std" namespace has not yet been defined, so build one implicitly.
5779 StdNamespace = NamespaceDecl::Create(Context,
5780 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005781 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005782 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005783 &PP.getIdentifierTable().get("std"),
5784 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005785 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005786 }
5787
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005788 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005789}
5790
Sebastian Redl395e04d2012-01-17 22:49:33 +00005791bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5792 assert(getLangOptions().CPlusPlus &&
5793 "Looking for std::initializer_list outside of C++.");
5794
5795 // We're looking for implicit instantiations of
5796 // template <typename E> class std::initializer_list.
5797
5798 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5799 return false;
5800
Sebastian Redl84760e32012-01-17 22:49:58 +00005801 ClassTemplateDecl *Template = 0;
5802 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005803
Sebastian Redl84760e32012-01-17 22:49:58 +00005804 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005805
Sebastian Redl84760e32012-01-17 22:49:58 +00005806 ClassTemplateSpecializationDecl *Specialization =
5807 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5808 if (!Specialization)
5809 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005810
Sebastian Redl84760e32012-01-17 22:49:58 +00005811 if (Specialization->getSpecializationKind() != TSK_ImplicitInstantiation)
5812 return false;
5813
5814 Template = Specialization->getSpecializedTemplate();
5815 Arguments = Specialization->getTemplateArgs().data();
5816 } else if (const TemplateSpecializationType *TST =
5817 Ty->getAs<TemplateSpecializationType>()) {
5818 Template = dyn_cast_or_null<ClassTemplateDecl>(
5819 TST->getTemplateName().getAsTemplateDecl());
5820 Arguments = TST->getArgs();
5821 }
5822 if (!Template)
5823 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005824
5825 if (!StdInitializerList) {
5826 // Haven't recognized std::initializer_list yet, maybe this is it.
5827 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5828 if (TemplateClass->getIdentifier() !=
5829 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005830 !getStdNamespace()->InEnclosingNamespaceSetOf(
5831 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005832 return false;
5833 // This is a template called std::initializer_list, but is it the right
5834 // template?
5835 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005836 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005837 return false;
5838 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5839 return false;
5840
5841 // It's the right template.
5842 StdInitializerList = Template;
5843 }
5844
5845 if (Template != StdInitializerList)
5846 return false;
5847
5848 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005849 if (Element)
5850 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005851 return true;
5852}
5853
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005854static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5855 NamespaceDecl *Std = S.getStdNamespace();
5856 if (!Std) {
5857 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5858 return 0;
5859 }
5860
5861 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5862 Loc, Sema::LookupOrdinaryName);
5863 if (!S.LookupQualifiedName(Result, Std)) {
5864 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5865 return 0;
5866 }
5867 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5868 if (!Template) {
5869 Result.suppressDiagnostics();
5870 // We found something weird. Complain about the first thing we found.
5871 NamedDecl *Found = *Result.begin();
5872 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5873 return 0;
5874 }
5875
5876 // We found some template called std::initializer_list. Now verify that it's
5877 // correct.
5878 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005879 if (Params->getMinRequiredArguments() != 1 ||
5880 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005881 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5882 return 0;
5883 }
5884
5885 return Template;
5886}
5887
5888QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5889 if (!StdInitializerList) {
5890 StdInitializerList = LookupStdInitializerList(*this, Loc);
5891 if (!StdInitializerList)
5892 return QualType();
5893 }
5894
5895 TemplateArgumentListInfo Args(Loc, Loc);
5896 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5897 Context.getTrivialTypeSourceInfo(Element,
5898 Loc)));
5899 return Context.getCanonicalType(
5900 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5901}
5902
Sebastian Redl98d36062012-01-17 22:50:14 +00005903bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5904 // C++ [dcl.init.list]p2:
5905 // A constructor is an initializer-list constructor if its first parameter
5906 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5907 // std::initializer_list<E> for some type E, and either there are no other
5908 // parameters or else all other parameters have default arguments.
5909 if (Ctor->getNumParams() < 1 ||
5910 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5911 return false;
5912
5913 QualType ArgType = Ctor->getParamDecl(0)->getType();
5914 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5915 ArgType = RT->getPointeeType().getUnqualifiedType();
5916
5917 return isStdInitializerList(ArgType, 0);
5918}
5919
Douglas Gregor9172aa62011-03-26 22:25:30 +00005920/// \brief Determine whether a using statement is in a context where it will be
5921/// apply in all contexts.
5922static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5923 switch (CurContext->getDeclKind()) {
5924 case Decl::TranslationUnit:
5925 return true;
5926 case Decl::LinkageSpec:
5927 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5928 default:
5929 return false;
5930 }
5931}
5932
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005933namespace {
5934
5935// Callback to only accept typo corrections that are namespaces.
5936class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5937 public:
5938 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5939 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5940 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5941 }
5942 return false;
5943 }
5944};
5945
5946}
5947
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005948static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5949 CXXScopeSpec &SS,
5950 SourceLocation IdentLoc,
5951 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005952 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005953 R.clear();
5954 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005955 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005956 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005957 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5958 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5959 if (DeclContext *DC = S.computeDeclContext(SS, false))
5960 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5961 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5962 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5963 else
5964 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5965 << Ident << CorrectedQuotedStr
5966 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005967
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005968 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5969 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005970
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005971 Ident = Corrected.getCorrectionAsIdentifierInfo();
5972 R.addDecl(Corrected.getCorrectionDecl());
5973 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005974 }
5975 return false;
5976}
5977
John McCalld226f652010-08-21 09:40:31 +00005978Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005979 SourceLocation UsingLoc,
5980 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005981 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005982 SourceLocation IdentLoc,
5983 IdentifierInfo *NamespcName,
5984 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005985 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5986 assert(NamespcName && "Invalid NamespcName.");
5987 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005988
5989 // This can only happen along a recovery path.
5990 while (S->getFlags() & Scope::TemplateParamScope)
5991 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005992 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005993
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005994 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005995 NestedNameSpecifier *Qualifier = 0;
5996 if (SS.isSet())
5997 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5998
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005999 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006000 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6001 LookupParsedName(R, S, &SS);
6002 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006003 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006004
Douglas Gregor66992202010-06-29 17:53:46 +00006005 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006006 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006007 // Allow "using namespace std;" or "using namespace ::std;" even if
6008 // "std" hasn't been defined yet, for GCC compatibility.
6009 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6010 NamespcName->isStr("std")) {
6011 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006012 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006013 R.resolveKind();
6014 }
6015 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006016 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006017 }
6018
John McCallf36e02d2009-10-09 21:13:30 +00006019 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006020 NamedDecl *Named = R.getFoundDecl();
6021 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6022 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006023 // C++ [namespace.udir]p1:
6024 // A using-directive specifies that the names in the nominated
6025 // namespace can be used in the scope in which the
6026 // using-directive appears after the using-directive. During
6027 // unqualified name lookup (3.4.1), the names appear as if they
6028 // were declared in the nearest enclosing namespace which
6029 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006030 // namespace. [Note: in this context, "contains" means "contains
6031 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006032
6033 // Find enclosing context containing both using-directive and
6034 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006035 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006036 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6037 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6038 CommonAncestor = CommonAncestor->getParent();
6039
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006040 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006041 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006042 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006043
Douglas Gregor9172aa62011-03-26 22:25:30 +00006044 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006045 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006046 Diag(IdentLoc, diag::warn_using_directive_in_header);
6047 }
6048
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006049 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006050 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006051 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006052 }
6053
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006054 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006055 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006056}
6057
6058void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6059 // If scope has associated entity, then using directive is at namespace
6060 // or translation unit scope. We add UsingDirectiveDecls, into
6061 // it's lookup structure.
6062 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006063 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006064 else
6065 // Otherwise it is block-sope. using-directives will affect lookup
6066 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006067 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006068}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006069
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006070
John McCalld226f652010-08-21 09:40:31 +00006071Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006072 AccessSpecifier AS,
6073 bool HasUsingKeyword,
6074 SourceLocation UsingLoc,
6075 CXXScopeSpec &SS,
6076 UnqualifiedId &Name,
6077 AttributeList *AttrList,
6078 bool IsTypeName,
6079 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006080 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006081
Douglas Gregor12c118a2009-11-04 16:30:06 +00006082 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006083 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006084 case UnqualifiedId::IK_Identifier:
6085 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006086 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006087 case UnqualifiedId::IK_ConversionFunctionId:
6088 break;
6089
6090 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006091 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006092 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006093 Diag(Name.getSourceRange().getBegin(),
6094 getLangOptions().CPlusPlus0x ?
6095 diag::warn_cxx98_compat_using_decl_constructor :
6096 diag::err_using_decl_constructor)
6097 << SS.getRange();
6098
John McCall604e7f12009-12-08 07:46:18 +00006099 if (getLangOptions().CPlusPlus0x) break;
6100
John McCalld226f652010-08-21 09:40:31 +00006101 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006102
6103 case UnqualifiedId::IK_DestructorName:
6104 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6105 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006106 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006107
6108 case UnqualifiedId::IK_TemplateId:
6109 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6110 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006111 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006112 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006113
6114 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6115 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006116 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006117 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006118
John McCall60fa3cf2009-12-11 02:10:03 +00006119 // Warn about using declarations.
6120 // TODO: store that the declaration was written without 'using' and
6121 // talk about access decls instead of using decls in the
6122 // diagnostics.
6123 if (!HasUsingKeyword) {
6124 UsingLoc = Name.getSourceRange().getBegin();
6125
6126 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006127 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006128 }
6129
Douglas Gregor56c04582010-12-16 00:46:58 +00006130 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6131 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6132 return 0;
6133
John McCall9488ea12009-11-17 05:59:44 +00006134 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006135 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006136 /* IsInstantiation */ false,
6137 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006138 if (UD)
6139 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006140
John McCalld226f652010-08-21 09:40:31 +00006141 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006142}
6143
Douglas Gregor09acc982010-07-07 23:08:52 +00006144/// \brief Determine whether a using declaration considers the given
6145/// declarations as "equivalent", e.g., if they are redeclarations of
6146/// the same entity or are both typedefs of the same type.
6147static bool
6148IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6149 bool &SuppressRedeclaration) {
6150 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6151 SuppressRedeclaration = false;
6152 return true;
6153 }
6154
Richard Smith162e1c12011-04-15 14:24:37 +00006155 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6156 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006157 SuppressRedeclaration = true;
6158 return Context.hasSameType(TD1->getUnderlyingType(),
6159 TD2->getUnderlyingType());
6160 }
6161
6162 return false;
6163}
6164
6165
John McCall9f54ad42009-12-10 09:41:52 +00006166/// Determines whether to create a using shadow decl for a particular
6167/// decl, given the set of decls existing prior to this using lookup.
6168bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6169 const LookupResult &Previous) {
6170 // Diagnose finding a decl which is not from a base class of the
6171 // current class. We do this now because there are cases where this
6172 // function will silently decide not to build a shadow decl, which
6173 // will pre-empt further diagnostics.
6174 //
6175 // We don't need to do this in C++0x because we do the check once on
6176 // the qualifier.
6177 //
6178 // FIXME: diagnose the following if we care enough:
6179 // struct A { int foo; };
6180 // struct B : A { using A::foo; };
6181 // template <class T> struct C : A {};
6182 // template <class T> struct D : C<T> { using B::foo; } // <---
6183 // This is invalid (during instantiation) in C++03 because B::foo
6184 // resolves to the using decl in B, which is not a base class of D<T>.
6185 // We can't diagnose it immediately because C<T> is an unknown
6186 // specialization. The UsingShadowDecl in D<T> then points directly
6187 // to A::foo, which will look well-formed when we instantiate.
6188 // The right solution is to not collapse the shadow-decl chain.
6189 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6190 DeclContext *OrigDC = Orig->getDeclContext();
6191
6192 // Handle enums and anonymous structs.
6193 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6194 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6195 while (OrigRec->isAnonymousStructOrUnion())
6196 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6197
6198 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6199 if (OrigDC == CurContext) {
6200 Diag(Using->getLocation(),
6201 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006202 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006203 Diag(Orig->getLocation(), diag::note_using_decl_target);
6204 return true;
6205 }
6206
Douglas Gregordc355712011-02-25 00:36:19 +00006207 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006208 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006209 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006210 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006211 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006212 Diag(Orig->getLocation(), diag::note_using_decl_target);
6213 return true;
6214 }
6215 }
6216
6217 if (Previous.empty()) return false;
6218
6219 NamedDecl *Target = Orig;
6220 if (isa<UsingShadowDecl>(Target))
6221 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6222
John McCalld7533ec2009-12-11 02:33:26 +00006223 // If the target happens to be one of the previous declarations, we
6224 // don't have a conflict.
6225 //
6226 // FIXME: but we might be increasing its access, in which case we
6227 // should redeclare it.
6228 NamedDecl *NonTag = 0, *Tag = 0;
6229 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6230 I != E; ++I) {
6231 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006232 bool Result;
6233 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6234 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006235
6236 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6237 }
6238
John McCall9f54ad42009-12-10 09:41:52 +00006239 if (Target->isFunctionOrFunctionTemplate()) {
6240 FunctionDecl *FD;
6241 if (isa<FunctionTemplateDecl>(Target))
6242 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6243 else
6244 FD = cast<FunctionDecl>(Target);
6245
6246 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006247 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006248 case Ovl_Overload:
6249 return false;
6250
6251 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006252 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006253 break;
6254
6255 // We found a decl with the exact signature.
6256 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006257 // If we're in a record, we want to hide the target, so we
6258 // return true (without a diagnostic) to tell the caller not to
6259 // build a shadow decl.
6260 if (CurContext->isRecord())
6261 return true;
6262
6263 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006264 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006265 break;
6266 }
6267
6268 Diag(Target->getLocation(), diag::note_using_decl_target);
6269 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6270 return true;
6271 }
6272
6273 // Target is not a function.
6274
John McCall9f54ad42009-12-10 09:41:52 +00006275 if (isa<TagDecl>(Target)) {
6276 // No conflict between a tag and a non-tag.
6277 if (!Tag) return false;
6278
John McCall41ce66f2009-12-10 19:51:03 +00006279 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006280 Diag(Target->getLocation(), diag::note_using_decl_target);
6281 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6282 return true;
6283 }
6284
6285 // No conflict between a tag and a non-tag.
6286 if (!NonTag) return false;
6287
John McCall41ce66f2009-12-10 19:51:03 +00006288 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006289 Diag(Target->getLocation(), diag::note_using_decl_target);
6290 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6291 return true;
6292}
6293
John McCall9488ea12009-11-17 05:59:44 +00006294/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006295UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006296 UsingDecl *UD,
6297 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006298
6299 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006300 NamedDecl *Target = Orig;
6301 if (isa<UsingShadowDecl>(Target)) {
6302 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6303 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006304 }
6305
6306 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006307 = UsingShadowDecl::Create(Context, CurContext,
6308 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006309 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006310
6311 Shadow->setAccess(UD->getAccess());
6312 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6313 Shadow->setInvalidDecl();
6314
John McCall9488ea12009-11-17 05:59:44 +00006315 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006316 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006317 else
John McCall604e7f12009-12-08 07:46:18 +00006318 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006319
John McCall604e7f12009-12-08 07:46:18 +00006320
John McCall9f54ad42009-12-10 09:41:52 +00006321 return Shadow;
6322}
John McCall604e7f12009-12-08 07:46:18 +00006323
John McCall9f54ad42009-12-10 09:41:52 +00006324/// Hides a using shadow declaration. This is required by the current
6325/// using-decl implementation when a resolvable using declaration in a
6326/// class is followed by a declaration which would hide or override
6327/// one or more of the using decl's targets; for example:
6328///
6329/// struct Base { void foo(int); };
6330/// struct Derived : Base {
6331/// using Base::foo;
6332/// void foo(int);
6333/// };
6334///
6335/// The governing language is C++03 [namespace.udecl]p12:
6336///
6337/// When a using-declaration brings names from a base class into a
6338/// derived class scope, member functions in the derived class
6339/// override and/or hide member functions with the same name and
6340/// parameter types in a base class (rather than conflicting).
6341///
6342/// There are two ways to implement this:
6343/// (1) optimistically create shadow decls when they're not hidden
6344/// by existing declarations, or
6345/// (2) don't create any shadow decls (or at least don't make them
6346/// visible) until we've fully parsed/instantiated the class.
6347/// The problem with (1) is that we might have to retroactively remove
6348/// a shadow decl, which requires several O(n) operations because the
6349/// decl structures are (very reasonably) not designed for removal.
6350/// (2) avoids this but is very fiddly and phase-dependent.
6351void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006352 if (Shadow->getDeclName().getNameKind() ==
6353 DeclarationName::CXXConversionFunctionName)
6354 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6355
John McCall9f54ad42009-12-10 09:41:52 +00006356 // Remove it from the DeclContext...
6357 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006358
John McCall9f54ad42009-12-10 09:41:52 +00006359 // ...and the scope, if applicable...
6360 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006361 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006362 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006363 }
6364
John McCall9f54ad42009-12-10 09:41:52 +00006365 // ...and the using decl.
6366 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6367
6368 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006369 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006370}
6371
John McCall7ba107a2009-11-18 02:36:19 +00006372/// Builds a using declaration.
6373///
6374/// \param IsInstantiation - Whether this call arises from an
6375/// instantiation of an unresolved using declaration. We treat
6376/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006377NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6378 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006379 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006380 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006381 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006382 bool IsInstantiation,
6383 bool IsTypeName,
6384 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006385 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006386 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006387 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006388
Anders Carlsson550b14b2009-08-28 05:49:21 +00006389 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006390
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006391 if (SS.isEmpty()) {
6392 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006393 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006394 }
Mike Stump1eb44332009-09-09 15:08:12 +00006395
John McCall9f54ad42009-12-10 09:41:52 +00006396 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006397 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006398 ForRedeclaration);
6399 Previous.setHideTags(false);
6400 if (S) {
6401 LookupName(Previous, S);
6402
6403 // It is really dumb that we have to do this.
6404 LookupResult::Filter F = Previous.makeFilter();
6405 while (F.hasNext()) {
6406 NamedDecl *D = F.next();
6407 if (!isDeclInScope(D, CurContext, S))
6408 F.erase();
6409 }
6410 F.done();
6411 } else {
6412 assert(IsInstantiation && "no scope in non-instantiation");
6413 assert(CurContext->isRecord() && "scope not record in instantiation");
6414 LookupQualifiedName(Previous, CurContext);
6415 }
6416
John McCall9f54ad42009-12-10 09:41:52 +00006417 // Check for invalid redeclarations.
6418 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6419 return 0;
6420
6421 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006422 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6423 return 0;
6424
John McCallaf8e6ed2009-11-12 03:15:40 +00006425 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006426 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006427 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006428 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006429 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006430 // FIXME: not all declaration name kinds are legal here
6431 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6432 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006433 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006434 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006435 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006436 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6437 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006438 }
John McCalled976492009-12-04 22:46:56 +00006439 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006440 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6441 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006442 }
John McCalled976492009-12-04 22:46:56 +00006443 D->setAccess(AS);
6444 CurContext->addDecl(D);
6445
6446 if (!LookupContext) return D;
6447 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006448
John McCall77bb1aa2010-05-01 00:40:08 +00006449 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006450 UD->setInvalidDecl();
6451 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006452 }
6453
Sebastian Redlf677ea32011-02-05 19:23:19 +00006454 // Constructor inheriting using decls get special treatment.
6455 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006456 if (CheckInheritedConstructorUsingDecl(UD))
6457 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006458 return UD;
6459 }
6460
6461 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006462
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006463 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006464
John McCall604e7f12009-12-08 07:46:18 +00006465 // Unlike most lookups, we don't always want to hide tag
6466 // declarations: tag names are visible through the using declaration
6467 // even if hidden by ordinary names, *except* in a dependent context
6468 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006469 if (!IsInstantiation)
6470 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006471
John McCalla24dc2e2009-11-17 02:14:36 +00006472 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006473
John McCallf36e02d2009-10-09 21:13:30 +00006474 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006475 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006476 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006477 UD->setInvalidDecl();
6478 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006479 }
6480
John McCalled976492009-12-04 22:46:56 +00006481 if (R.isAmbiguous()) {
6482 UD->setInvalidDecl();
6483 return UD;
6484 }
Mike Stump1eb44332009-09-09 15:08:12 +00006485
John McCall7ba107a2009-11-18 02:36:19 +00006486 if (IsTypeName) {
6487 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006488 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006489 Diag(IdentLoc, diag::err_using_typename_non_type);
6490 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6491 Diag((*I)->getUnderlyingDecl()->getLocation(),
6492 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006493 UD->setInvalidDecl();
6494 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006495 }
6496 } else {
6497 // If we asked for a non-typename and we got a type, error out,
6498 // but only if this is an instantiation of an unresolved using
6499 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006500 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006501 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6502 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006503 UD->setInvalidDecl();
6504 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006505 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006506 }
6507
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006508 // C++0x N2914 [namespace.udecl]p6:
6509 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006510 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006511 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6512 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006513 UD->setInvalidDecl();
6514 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006515 }
Mike Stump1eb44332009-09-09 15:08:12 +00006516
John McCall9f54ad42009-12-10 09:41:52 +00006517 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6518 if (!CheckUsingShadowDecl(UD, *I, Previous))
6519 BuildUsingShadowDecl(S, UD, *I);
6520 }
John McCall9488ea12009-11-17 05:59:44 +00006521
6522 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006523}
6524
Sebastian Redlf677ea32011-02-05 19:23:19 +00006525/// Additional checks for a using declaration referring to a constructor name.
6526bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6527 if (UD->isTypeName()) {
6528 // FIXME: Cannot specify typename when specifying constructor
6529 return true;
6530 }
6531
Douglas Gregordc355712011-02-25 00:36:19 +00006532 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006533 assert(SourceType &&
6534 "Using decl naming constructor doesn't have type in scope spec.");
6535 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6536
6537 // Check whether the named type is a direct base class.
6538 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6539 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6540 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6541 BaseIt != BaseE; ++BaseIt) {
6542 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6543 if (CanonicalSourceType == BaseType)
6544 break;
6545 }
6546
6547 if (BaseIt == BaseE) {
6548 // Did not find SourceType in the bases.
6549 Diag(UD->getUsingLocation(),
6550 diag::err_using_decl_constructor_not_in_direct_base)
6551 << UD->getNameInfo().getSourceRange()
6552 << QualType(SourceType, 0) << TargetClass;
6553 return true;
6554 }
6555
6556 BaseIt->setInheritConstructors();
6557
6558 return false;
6559}
6560
John McCall9f54ad42009-12-10 09:41:52 +00006561/// Checks that the given using declaration is not an invalid
6562/// redeclaration. Note that this is checking only for the using decl
6563/// itself, not for any ill-formedness among the UsingShadowDecls.
6564bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6565 bool isTypeName,
6566 const CXXScopeSpec &SS,
6567 SourceLocation NameLoc,
6568 const LookupResult &Prev) {
6569 // C++03 [namespace.udecl]p8:
6570 // C++0x [namespace.udecl]p10:
6571 // A using-declaration is a declaration and can therefore be used
6572 // repeatedly where (and only where) multiple declarations are
6573 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006574 //
John McCall8a726212010-11-29 18:01:58 +00006575 // That's in non-member contexts.
6576 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006577 return false;
6578
6579 NestedNameSpecifier *Qual
6580 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6581
6582 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6583 NamedDecl *D = *I;
6584
6585 bool DTypename;
6586 NestedNameSpecifier *DQual;
6587 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6588 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006589 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006590 } else if (UnresolvedUsingValueDecl *UD
6591 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6592 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006593 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006594 } else if (UnresolvedUsingTypenameDecl *UD
6595 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6596 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006597 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006598 } else continue;
6599
6600 // using decls differ if one says 'typename' and the other doesn't.
6601 // FIXME: non-dependent using decls?
6602 if (isTypeName != DTypename) continue;
6603
6604 // using decls differ if they name different scopes (but note that
6605 // template instantiation can cause this check to trigger when it
6606 // didn't before instantiation).
6607 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6608 Context.getCanonicalNestedNameSpecifier(DQual))
6609 continue;
6610
6611 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006612 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006613 return true;
6614 }
6615
6616 return false;
6617}
6618
John McCall604e7f12009-12-08 07:46:18 +00006619
John McCalled976492009-12-04 22:46:56 +00006620/// Checks that the given nested-name qualifier used in a using decl
6621/// in the current context is appropriately related to the current
6622/// scope. If an error is found, diagnoses it and returns true.
6623bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6624 const CXXScopeSpec &SS,
6625 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006626 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006627
John McCall604e7f12009-12-08 07:46:18 +00006628 if (!CurContext->isRecord()) {
6629 // C++03 [namespace.udecl]p3:
6630 // C++0x [namespace.udecl]p8:
6631 // A using-declaration for a class member shall be a member-declaration.
6632
6633 // If we weren't able to compute a valid scope, it must be a
6634 // dependent class scope.
6635 if (!NamedContext || NamedContext->isRecord()) {
6636 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6637 << SS.getRange();
6638 return true;
6639 }
6640
6641 // Otherwise, everything is known to be fine.
6642 return false;
6643 }
6644
6645 // The current scope is a record.
6646
6647 // If the named context is dependent, we can't decide much.
6648 if (!NamedContext) {
6649 // FIXME: in C++0x, we can diagnose if we can prove that the
6650 // nested-name-specifier does not refer to a base class, which is
6651 // still possible in some cases.
6652
6653 // Otherwise we have to conservatively report that things might be
6654 // okay.
6655 return false;
6656 }
6657
6658 if (!NamedContext->isRecord()) {
6659 // Ideally this would point at the last name in the specifier,
6660 // but we don't have that level of source info.
6661 Diag(SS.getRange().getBegin(),
6662 diag::err_using_decl_nested_name_specifier_is_not_class)
6663 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6664 return true;
6665 }
6666
Douglas Gregor6fb07292010-12-21 07:41:49 +00006667 if (!NamedContext->isDependentContext() &&
6668 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6669 return true;
6670
John McCall604e7f12009-12-08 07:46:18 +00006671 if (getLangOptions().CPlusPlus0x) {
6672 // C++0x [namespace.udecl]p3:
6673 // In a using-declaration used as a member-declaration, the
6674 // nested-name-specifier shall name a base class of the class
6675 // being defined.
6676
6677 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6678 cast<CXXRecordDecl>(NamedContext))) {
6679 if (CurContext == NamedContext) {
6680 Diag(NameLoc,
6681 diag::err_using_decl_nested_name_specifier_is_current_class)
6682 << SS.getRange();
6683 return true;
6684 }
6685
6686 Diag(SS.getRange().getBegin(),
6687 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6688 << (NestedNameSpecifier*) SS.getScopeRep()
6689 << cast<CXXRecordDecl>(CurContext)
6690 << SS.getRange();
6691 return true;
6692 }
6693
6694 return false;
6695 }
6696
6697 // C++03 [namespace.udecl]p4:
6698 // A using-declaration used as a member-declaration shall refer
6699 // to a member of a base class of the class being defined [etc.].
6700
6701 // Salient point: SS doesn't have to name a base class as long as
6702 // lookup only finds members from base classes. Therefore we can
6703 // diagnose here only if we can prove that that can't happen,
6704 // i.e. if the class hierarchies provably don't intersect.
6705
6706 // TODO: it would be nice if "definitely valid" results were cached
6707 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6708 // need to be repeated.
6709
6710 struct UserData {
6711 llvm::DenseSet<const CXXRecordDecl*> Bases;
6712
6713 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6714 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6715 Data->Bases.insert(Base);
6716 return true;
6717 }
6718
6719 bool hasDependentBases(const CXXRecordDecl *Class) {
6720 return !Class->forallBases(collect, this);
6721 }
6722
6723 /// Returns true if the base is dependent or is one of the
6724 /// accumulated base classes.
6725 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6726 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6727 return !Data->Bases.count(Base);
6728 }
6729
6730 bool mightShareBases(const CXXRecordDecl *Class) {
6731 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6732 }
6733 };
6734
6735 UserData Data;
6736
6737 // Returns false if we find a dependent base.
6738 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6739 return false;
6740
6741 // Returns false if the class has a dependent base or if it or one
6742 // of its bases is present in the base set of the current context.
6743 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6744 return false;
6745
6746 Diag(SS.getRange().getBegin(),
6747 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6748 << (NestedNameSpecifier*) SS.getScopeRep()
6749 << cast<CXXRecordDecl>(CurContext)
6750 << SS.getRange();
6751
6752 return true;
John McCalled976492009-12-04 22:46:56 +00006753}
6754
Richard Smith162e1c12011-04-15 14:24:37 +00006755Decl *Sema::ActOnAliasDeclaration(Scope *S,
6756 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006757 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006758 SourceLocation UsingLoc,
6759 UnqualifiedId &Name,
6760 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006761 // Skip up to the relevant declaration scope.
6762 while (S->getFlags() & Scope::TemplateParamScope)
6763 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006764 assert((S->getFlags() & Scope::DeclScope) &&
6765 "got alias-declaration outside of declaration scope");
6766
6767 if (Type.isInvalid())
6768 return 0;
6769
6770 bool Invalid = false;
6771 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6772 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006773 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006774
6775 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6776 return 0;
6777
6778 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006779 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006780 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006781 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6782 TInfo->getTypeLoc().getBeginLoc());
6783 }
Richard Smith162e1c12011-04-15 14:24:37 +00006784
6785 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6786 LookupName(Previous, S);
6787
6788 // Warn about shadowing the name of a template parameter.
6789 if (Previous.isSingleResult() &&
6790 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006791 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006792 Previous.clear();
6793 }
6794
6795 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6796 "name in alias declaration must be an identifier");
6797 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6798 Name.StartLocation,
6799 Name.Identifier, TInfo);
6800
6801 NewTD->setAccess(AS);
6802
6803 if (Invalid)
6804 NewTD->setInvalidDecl();
6805
Richard Smith3e4c6c42011-05-05 21:57:07 +00006806 CheckTypedefForVariablyModifiedType(S, NewTD);
6807 Invalid |= NewTD->isInvalidDecl();
6808
Richard Smith162e1c12011-04-15 14:24:37 +00006809 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006810
6811 NamedDecl *NewND;
6812 if (TemplateParamLists.size()) {
6813 TypeAliasTemplateDecl *OldDecl = 0;
6814 TemplateParameterList *OldTemplateParams = 0;
6815
6816 if (TemplateParamLists.size() != 1) {
6817 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6818 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6819 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6820 }
6821 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6822
6823 // Only consider previous declarations in the same scope.
6824 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6825 /*ExplicitInstantiationOrSpecialization*/false);
6826 if (!Previous.empty()) {
6827 Redeclaration = true;
6828
6829 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6830 if (!OldDecl && !Invalid) {
6831 Diag(UsingLoc, diag::err_redefinition_different_kind)
6832 << Name.Identifier;
6833
6834 NamedDecl *OldD = Previous.getRepresentativeDecl();
6835 if (OldD->getLocation().isValid())
6836 Diag(OldD->getLocation(), diag::note_previous_definition);
6837
6838 Invalid = true;
6839 }
6840
6841 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6842 if (TemplateParameterListsAreEqual(TemplateParams,
6843 OldDecl->getTemplateParameters(),
6844 /*Complain=*/true,
6845 TPL_TemplateMatch))
6846 OldTemplateParams = OldDecl->getTemplateParameters();
6847 else
6848 Invalid = true;
6849
6850 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6851 if (!Invalid &&
6852 !Context.hasSameType(OldTD->getUnderlyingType(),
6853 NewTD->getUnderlyingType())) {
6854 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6855 // but we can't reasonably accept it.
6856 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6857 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6858 if (OldTD->getLocation().isValid())
6859 Diag(OldTD->getLocation(), diag::note_previous_definition);
6860 Invalid = true;
6861 }
6862 }
6863 }
6864
6865 // Merge any previous default template arguments into our parameters,
6866 // and check the parameter list.
6867 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6868 TPC_TypeAliasTemplate))
6869 return 0;
6870
6871 TypeAliasTemplateDecl *NewDecl =
6872 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6873 Name.Identifier, TemplateParams,
6874 NewTD);
6875
6876 NewDecl->setAccess(AS);
6877
6878 if (Invalid)
6879 NewDecl->setInvalidDecl();
6880 else if (OldDecl)
6881 NewDecl->setPreviousDeclaration(OldDecl);
6882
6883 NewND = NewDecl;
6884 } else {
6885 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6886 NewND = NewTD;
6887 }
Richard Smith162e1c12011-04-15 14:24:37 +00006888
6889 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006890 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006891
Richard Smith3e4c6c42011-05-05 21:57:07 +00006892 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006893}
6894
John McCalld226f652010-08-21 09:40:31 +00006895Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006896 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006897 SourceLocation AliasLoc,
6898 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006899 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006900 SourceLocation IdentLoc,
6901 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006902
Anders Carlsson81c85c42009-03-28 23:53:49 +00006903 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006904 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6905 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006906
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006907 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006908 NamedDecl *PrevDecl
6909 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6910 ForRedeclaration);
6911 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6912 PrevDecl = 0;
6913
6914 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006915 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006916 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006917 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006918 // FIXME: At some point, we'll want to create the (redundant)
6919 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006920 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006921 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006922 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006923 }
Mike Stump1eb44332009-09-09 15:08:12 +00006924
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006925 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6926 diag::err_redefinition_different_kind;
6927 Diag(AliasLoc, DiagID) << Alias;
6928 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006929 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006930 }
6931
John McCalla24dc2e2009-11-17 02:14:36 +00006932 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006933 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006934
John McCallf36e02d2009-10-09 21:13:30 +00006935 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006936 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006937 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006938 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006939 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006940 }
Mike Stump1eb44332009-09-09 15:08:12 +00006941
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006942 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006943 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006944 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006945 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006946
John McCall3dbd3d52010-02-16 06:53:13 +00006947 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006948 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006949}
6950
Douglas Gregor39957dc2010-05-01 15:04:51 +00006951namespace {
6952 /// \brief Scoped object used to handle the state changes required in Sema
6953 /// to implicitly define the body of a C++ member function;
6954 class ImplicitlyDefinedFunctionScope {
6955 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006956 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006957
6958 public:
6959 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006960 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006961 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006962 S.PushFunctionScope();
6963 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6964 }
6965
6966 ~ImplicitlyDefinedFunctionScope() {
6967 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006968 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006969 }
6970 };
6971}
6972
Sean Hunt001cad92011-05-10 00:49:42 +00006973Sema::ImplicitExceptionSpecification
6974Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006975 // C++ [except.spec]p14:
6976 // An implicitly declared special member function (Clause 12) shall have an
6977 // exception-specification. [...]
6978 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006979 if (ClassDecl->isInvalidDecl())
6980 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006981
Sebastian Redl60618fa2011-03-12 11:50:43 +00006982 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006983 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6984 BEnd = ClassDecl->bases_end();
6985 B != BEnd; ++B) {
6986 if (B->isVirtual()) // Handled below.
6987 continue;
6988
Douglas Gregor18274032010-07-03 00:47:00 +00006989 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6990 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006991 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6992 // If this is a deleted function, add it anyway. This might be conformant
6993 // with the standard. This might not. I'm not sure. It might not matter.
6994 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006995 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006996 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006997 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006998
6999 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007000 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7001 BEnd = ClassDecl->vbases_end();
7002 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007003 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7004 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007005 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7006 // If this is a deleted function, add it anyway. This might be conformant
7007 // with the standard. This might not. I'm not sure. It might not matter.
7008 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007009 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007010 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007011 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007012
7013 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007014 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7015 FEnd = ClassDecl->field_end();
7016 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007017 if (F->hasInClassInitializer()) {
7018 if (Expr *E = F->getInClassInitializer())
7019 ExceptSpec.CalledExpr(E);
7020 else if (!F->isInvalidDecl())
7021 ExceptSpec.SetDelayed();
7022 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007023 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007024 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7025 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7026 // If this is a deleted function, add it anyway. This might be conformant
7027 // with the standard. This might not. I'm not sure. It might not matter.
7028 // In particular, the problem is that this function never gets called. It
7029 // might just be ill-formed because this function attempts to refer to
7030 // a deleted function here.
7031 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007032 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007033 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007034 }
John McCalle23cf432010-12-14 08:05:40 +00007035
Sean Hunt001cad92011-05-10 00:49:42 +00007036 return ExceptSpec;
7037}
7038
7039CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7040 CXXRecordDecl *ClassDecl) {
7041 // C++ [class.ctor]p5:
7042 // A default constructor for a class X is a constructor of class X
7043 // that can be called without an argument. If there is no
7044 // user-declared constructor for class X, a default constructor is
7045 // implicitly declared. An implicitly-declared default constructor
7046 // is an inline public member of its class.
7047 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7048 "Should not build implicit default constructor!");
7049
7050 ImplicitExceptionSpecification Spec =
7051 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7052 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007053
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007054 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007055 CanQualType ClassType
7056 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007057 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007058 DeclarationName Name
7059 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007060 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007061 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7062 Context, ClassDecl, ClassLoc, NameInfo,
7063 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7064 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7065 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7066 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007067 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007068 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007069 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007070 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007071
7072 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007073 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7074
Douglas Gregor23c94db2010-07-02 17:43:08 +00007075 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007076 PushOnScopeChains(DefaultCon, S, false);
7077 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007078
Sean Hunte16da072011-10-10 06:18:57 +00007079 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007080 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007081
Douglas Gregor32df23e2010-07-01 22:02:46 +00007082 return DefaultCon;
7083}
7084
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007085void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7086 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007087 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007088 !Constructor->doesThisDeclarationHaveABody() &&
7089 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007090 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007091
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007092 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007093 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007094
Douglas Gregor39957dc2010-05-01 15:04:51 +00007095 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007096 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007097 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007098 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007099 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007100 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007101 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007102 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007103 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007104
7105 SourceLocation Loc = Constructor->getLocation();
7106 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7107
7108 Constructor->setUsed();
7109 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007110
7111 if (ASTMutationListener *L = getASTMutationListener()) {
7112 L->CompletedImplicitDefinition(Constructor);
7113 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007114}
7115
Richard Smith7a614d82011-06-11 17:19:42 +00007116/// Get any existing defaulted default constructor for the given class. Do not
7117/// implicitly define one if it does not exist.
7118static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7119 CXXRecordDecl *D) {
7120 ASTContext &Context = Self.Context;
7121 QualType ClassType = Context.getTypeDeclType(D);
7122 DeclarationName ConstructorName
7123 = Context.DeclarationNames.getCXXConstructorName(
7124 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7125
7126 DeclContext::lookup_const_iterator Con, ConEnd;
7127 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7128 Con != ConEnd; ++Con) {
7129 // A function template cannot be defaulted.
7130 if (isa<FunctionTemplateDecl>(*Con))
7131 continue;
7132
7133 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7134 if (Constructor->isDefaultConstructor())
7135 return Constructor->isDefaulted() ? Constructor : 0;
7136 }
7137 return 0;
7138}
7139
7140void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7141 if (!D) return;
7142 AdjustDeclIfTemplate(D);
7143
7144 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7145 CXXConstructorDecl *CtorDecl
7146 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7147
7148 if (!CtorDecl) return;
7149
7150 // Compute the exception specification for the default constructor.
7151 const FunctionProtoType *CtorTy =
7152 CtorDecl->getType()->castAs<FunctionProtoType>();
7153 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7154 ImplicitExceptionSpecification Spec =
7155 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7156 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7157 assert(EPI.ExceptionSpecType != EST_Delayed);
7158
7159 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7160 }
7161
7162 // If the default constructor is explicitly defaulted, checking the exception
7163 // specification is deferred until now.
7164 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7165 !ClassDecl->isDependentType())
7166 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7167}
7168
Sebastian Redlf677ea32011-02-05 19:23:19 +00007169void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7170 // We start with an initial pass over the base classes to collect those that
7171 // inherit constructors from. If there are none, we can forgo all further
7172 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007173 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007174 BasesVector BasesToInheritFrom;
7175 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7176 BaseE = ClassDecl->bases_end();
7177 BaseIt != BaseE; ++BaseIt) {
7178 if (BaseIt->getInheritConstructors()) {
7179 QualType Base = BaseIt->getType();
7180 if (Base->isDependentType()) {
7181 // If we inherit constructors from anything that is dependent, just
7182 // abort processing altogether. We'll get another chance for the
7183 // instantiations.
7184 return;
7185 }
7186 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7187 }
7188 }
7189 if (BasesToInheritFrom.empty())
7190 return;
7191
7192 // Now collect the constructors that we already have in the current class.
7193 // Those take precedence over inherited constructors.
7194 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7195 // unless there is a user-declared constructor with the same signature in
7196 // the class where the using-declaration appears.
7197 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7198 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7199 CtorE = ClassDecl->ctor_end();
7200 CtorIt != CtorE; ++CtorIt) {
7201 ExistingConstructors.insert(
7202 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7203 }
7204
7205 Scope *S = getScopeForContext(ClassDecl);
7206 DeclarationName CreatedCtorName =
7207 Context.DeclarationNames.getCXXConstructorName(
7208 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7209
7210 // Now comes the true work.
7211 // First, we keep a map from constructor types to the base that introduced
7212 // them. Needed for finding conflicting constructors. We also keep the
7213 // actually inserted declarations in there, for pretty diagnostics.
7214 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7215 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7216 ConstructorToSourceMap InheritedConstructors;
7217 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7218 BaseE = BasesToInheritFrom.end();
7219 BaseIt != BaseE; ++BaseIt) {
7220 const RecordType *Base = *BaseIt;
7221 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7222 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7223 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7224 CtorE = BaseDecl->ctor_end();
7225 CtorIt != CtorE; ++CtorIt) {
7226 // Find the using declaration for inheriting this base's constructors.
7227 DeclarationName Name =
7228 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7229 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7230 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7231 SourceLocation UsingLoc = UD ? UD->getLocation() :
7232 ClassDecl->getLocation();
7233
7234 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7235 // from the class X named in the using-declaration consists of actual
7236 // constructors and notional constructors that result from the
7237 // transformation of defaulted parameters as follows:
7238 // - all non-template default constructors of X, and
7239 // - for each non-template constructor of X that has at least one
7240 // parameter with a default argument, the set of constructors that
7241 // results from omitting any ellipsis parameter specification and
7242 // successively omitting parameters with a default argument from the
7243 // end of the parameter-type-list.
7244 CXXConstructorDecl *BaseCtor = *CtorIt;
7245 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7246 const FunctionProtoType *BaseCtorType =
7247 BaseCtor->getType()->getAs<FunctionProtoType>();
7248
7249 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7250 maxParams = BaseCtor->getNumParams();
7251 params <= maxParams; ++params) {
7252 // Skip default constructors. They're never inherited.
7253 if (params == 0)
7254 continue;
7255 // Skip copy and move constructors for the same reason.
7256 if (CanBeCopyOrMove && params == 1)
7257 continue;
7258
7259 // Build up a function type for this particular constructor.
7260 // FIXME: The working paper does not consider that the exception spec
7261 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007262 // source. This code doesn't yet, either. When it does, this code will
7263 // need to be delayed until after exception specifications and in-class
7264 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007265 const Type *NewCtorType;
7266 if (params == maxParams)
7267 NewCtorType = BaseCtorType;
7268 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007269 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007270 for (unsigned i = 0; i < params; ++i) {
7271 Args.push_back(BaseCtorType->getArgType(i));
7272 }
7273 FunctionProtoType::ExtProtoInfo ExtInfo =
7274 BaseCtorType->getExtProtoInfo();
7275 ExtInfo.Variadic = false;
7276 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7277 Args.data(), params, ExtInfo)
7278 .getTypePtr();
7279 }
7280 const Type *CanonicalNewCtorType =
7281 Context.getCanonicalType(NewCtorType);
7282
7283 // Now that we have the type, first check if the class already has a
7284 // constructor with this signature.
7285 if (ExistingConstructors.count(CanonicalNewCtorType))
7286 continue;
7287
7288 // Then we check if we have already declared an inherited constructor
7289 // with this signature.
7290 std::pair<ConstructorToSourceMap::iterator, bool> result =
7291 InheritedConstructors.insert(std::make_pair(
7292 CanonicalNewCtorType,
7293 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7294 if (!result.second) {
7295 // Already in the map. If it came from a different class, that's an
7296 // error. Not if it's from the same.
7297 CanQualType PreviousBase = result.first->second.first;
7298 if (CanonicalBase != PreviousBase) {
7299 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7300 const CXXConstructorDecl *PrevBaseCtor =
7301 PrevCtor->getInheritedConstructor();
7302 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7303
7304 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7305 Diag(BaseCtor->getLocation(),
7306 diag::note_using_decl_constructor_conflict_current_ctor);
7307 Diag(PrevBaseCtor->getLocation(),
7308 diag::note_using_decl_constructor_conflict_previous_ctor);
7309 Diag(PrevCtor->getLocation(),
7310 diag::note_using_decl_constructor_conflict_previous_using);
7311 }
7312 continue;
7313 }
7314
7315 // OK, we're there, now add the constructor.
7316 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007317 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007318 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7319 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007320 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7321 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007322 /*ImplicitlyDeclared=*/true,
7323 // FIXME: Due to a defect in the standard, we treat inherited
7324 // constructors as constexpr even if that makes them ill-formed.
7325 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007326 NewCtor->setAccess(BaseCtor->getAccess());
7327
7328 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007329 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007330 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007331 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7332 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007333 /*IdentifierInfo=*/0,
7334 BaseCtorType->getArgType(i),
7335 /*TInfo=*/0, SC_None,
7336 SC_None, /*DefaultArg=*/0));
7337 }
David Blaikie4278c652011-09-21 18:16:56 +00007338 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007339 NewCtor->setInheritedConstructor(BaseCtor);
7340
7341 PushOnScopeChains(NewCtor, S, false);
7342 ClassDecl->addDecl(NewCtor);
7343 result.first->second.second = NewCtor;
7344 }
7345 }
7346 }
7347}
7348
Sean Huntcb45a0f2011-05-12 22:46:25 +00007349Sema::ImplicitExceptionSpecification
7350Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007351 // C++ [except.spec]p14:
7352 // An implicitly declared special member function (Clause 12) shall have
7353 // an exception-specification.
7354 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007355 if (ClassDecl->isInvalidDecl())
7356 return ExceptSpec;
7357
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007358 // Direct base-class destructors.
7359 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7360 BEnd = ClassDecl->bases_end();
7361 B != BEnd; ++B) {
7362 if (B->isVirtual()) // Handled below.
7363 continue;
7364
7365 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7366 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007367 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007368 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007369
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007370 // Virtual base-class destructors.
7371 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7372 BEnd = ClassDecl->vbases_end();
7373 B != BEnd; ++B) {
7374 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7375 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007376 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007377 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007378
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007379 // Field destructors.
7380 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7381 FEnd = ClassDecl->field_end();
7382 F != FEnd; ++F) {
7383 if (const RecordType *RecordTy
7384 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7385 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007386 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007387 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007388
Sean Huntcb45a0f2011-05-12 22:46:25 +00007389 return ExceptSpec;
7390}
7391
7392CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7393 // C++ [class.dtor]p2:
7394 // If a class has no user-declared destructor, a destructor is
7395 // declared implicitly. An implicitly-declared destructor is an
7396 // inline public member of its class.
7397
7398 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007399 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007400 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7401
Douglas Gregor4923aa22010-07-02 20:37:36 +00007402 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007403 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007404
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007405 CanQualType ClassType
7406 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007407 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007408 DeclarationName Name
7409 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007410 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007411 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007412 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7413 /*isInline=*/true,
7414 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007415 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007416 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007417 Destructor->setImplicit();
7418 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007419
7420 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007421 ++ASTContext::NumImplicitDestructorsDeclared;
7422
7423 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007424 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007425 PushOnScopeChains(Destructor, S, false);
7426 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007427
7428 // This could be uniqued if it ever proves significant.
7429 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007430
7431 if (ShouldDeleteDestructor(Destructor))
7432 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007433
7434 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007435
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007436 return Destructor;
7437}
7438
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007439void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007440 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007441 assert((Destructor->isDefaulted() &&
7442 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007443 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007444 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007445 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007446
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007447 if (Destructor->isInvalidDecl())
7448 return;
7449
Douglas Gregor39957dc2010-05-01 15:04:51 +00007450 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007451
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007452 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007453 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7454 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007455
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007456 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007457 Diag(CurrentLocation, diag::note_member_synthesized_at)
7458 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7459
7460 Destructor->setInvalidDecl();
7461 return;
7462 }
7463
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007464 SourceLocation Loc = Destructor->getLocation();
7465 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007466 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007467 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007468 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007469
7470 if (ASTMutationListener *L = getASTMutationListener()) {
7471 L->CompletedImplicitDefinition(Destructor);
7472 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007473}
7474
Sebastian Redl0ee33912011-05-19 05:13:44 +00007475void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7476 CXXDestructorDecl *destructor) {
7477 // C++11 [class.dtor]p3:
7478 // A declaration of a destructor that does not have an exception-
7479 // specification is implicitly considered to have the same exception-
7480 // specification as an implicit declaration.
7481 const FunctionProtoType *dtorType = destructor->getType()->
7482 getAs<FunctionProtoType>();
7483 if (dtorType->hasExceptionSpec())
7484 return;
7485
7486 ImplicitExceptionSpecification exceptSpec =
7487 ComputeDefaultedDtorExceptionSpec(classDecl);
7488
Chandler Carruth3f224b22011-09-20 04:55:26 +00007489 // Replace the destructor's type, building off the existing one. Fortunately,
7490 // the only thing of interest in the destructor type is its extended info.
7491 // The return and arguments are fixed.
7492 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007493 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7494 epi.NumExceptions = exceptSpec.size();
7495 epi.Exceptions = exceptSpec.data();
7496 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7497
7498 destructor->setType(ty);
7499
7500 // FIXME: If the destructor has a body that could throw, and the newly created
7501 // spec doesn't allow exceptions, we should emit a warning, because this
7502 // change in behavior can break conforming C++03 programs at runtime.
7503 // However, we don't have a body yet, so it needs to be done somewhere else.
7504}
7505
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007506/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007507/// \c To.
7508///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007509/// This routine is used to copy/move the members of a class with an
7510/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007511/// copied are arrays, this routine builds for loops to copy them.
7512///
7513/// \param S The Sema object used for type-checking.
7514///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007515/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007516///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007517/// \param T The type of the expressions being copied/moved. Both expressions
7518/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007519///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007520/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007521///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007522/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007523///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007524/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007525/// Otherwise, it's a non-static member subobject.
7526///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007527/// \param Copying Whether we're copying or moving.
7528///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007529/// \param Depth Internal parameter recording the depth of the recursion.
7530///
7531/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007532static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007533BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007534 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007535 bool CopyingBaseSubobject, bool Copying,
7536 unsigned Depth = 0) {
7537 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007538 // Each subobject is assigned in the manner appropriate to its type:
7539 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007540 // - if the subobject is of class type, as if by a call to operator= with
7541 // the subobject as the object expression and the corresponding
7542 // subobject of x as a single function argument (as if by explicit
7543 // qualification; that is, ignoring any possible virtual overriding
7544 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007545 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7546 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7547
7548 // Look for operator=.
7549 DeclarationName Name
7550 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7551 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7552 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7553
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007554 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007555 LookupResult::Filter F = OpLookup.makeFilter();
7556 while (F.hasNext()) {
7557 NamedDecl *D = F.next();
7558 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007559 if (Copying ? Method->isCopyAssignmentOperator() :
7560 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007561 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007562
Douglas Gregor06a9f362010-05-01 20:49:11 +00007563 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007564 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007565 F.done();
7566
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007567 // Suppress the protected check (C++ [class.protected]) for each of the
7568 // assignment operators we found. This strange dance is required when
7569 // we're assigning via a base classes's copy-assignment operator. To
7570 // ensure that we're getting the right base class subobject (without
7571 // ambiguities), we need to cast "this" to that subobject type; to
7572 // ensure that we don't go through the virtual call mechanism, we need
7573 // to qualify the operator= name with the base class (see below). However,
7574 // this means that if the base class has a protected copy assignment
7575 // operator, the protected member access check will fail. So, we
7576 // rewrite "protected" access to "public" access in this case, since we
7577 // know by construction that we're calling from a derived class.
7578 if (CopyingBaseSubobject) {
7579 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7580 L != LEnd; ++L) {
7581 if (L.getAccess() == AS_protected)
7582 L.setAccess(AS_public);
7583 }
7584 }
7585
Douglas Gregor06a9f362010-05-01 20:49:11 +00007586 // Create the nested-name-specifier that will be used to qualify the
7587 // reference to operator=; this is required to suppress the virtual
7588 // call mechanism.
7589 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007590 SS.MakeTrivial(S.Context,
7591 NestedNameSpecifier::Create(S.Context, 0, false,
7592 T.getTypePtr()),
7593 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007594
7595 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007596 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007597 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007598 /*TemplateKWLoc=*/SourceLocation(),
7599 /*FirstQualifierInScope=*/0,
7600 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007601 /*TemplateArgs=*/0,
7602 /*SuppressQualifierCheck=*/true);
7603 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007604 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007605
7606 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007607
John McCall60d7b3a2010-08-24 06:29:42 +00007608 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007609 OpEqualRef.takeAs<Expr>(),
7610 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007611 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007612 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007613
7614 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007615 }
John McCallb0207482010-03-16 06:11:48 +00007616
Douglas Gregor06a9f362010-05-01 20:49:11 +00007617 // - if the subobject is of scalar type, the built-in assignment
7618 // operator is used.
7619 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7620 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007621 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007622 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007623 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007624
7625 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007626 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007627
7628 // - if the subobject is an array, each element is assigned, in the
7629 // manner appropriate to the element type;
7630
7631 // Construct a loop over the array bounds, e.g.,
7632 //
7633 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7634 //
7635 // that will copy each of the array elements.
7636 QualType SizeType = S.Context.getSizeType();
7637
7638 // Create the iteration variable.
7639 IdentifierInfo *IterationVarName = 0;
7640 {
7641 llvm::SmallString<8> Str;
7642 llvm::raw_svector_ostream OS(Str);
7643 OS << "__i" << Depth;
7644 IterationVarName = &S.Context.Idents.get(OS.str());
7645 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007646 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007647 IterationVarName, SizeType,
7648 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007649 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007650
7651 // Initialize the iteration variable to zero.
7652 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007653 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007654
7655 // Create a reference to the iteration variable; we'll use this several
7656 // times throughout.
7657 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007658 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007659 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007660 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7661 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7662
Douglas Gregor06a9f362010-05-01 20:49:11 +00007663 // Create the DeclStmt that holds the iteration variable.
7664 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7665
7666 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007667 llvm::APInt Upper
7668 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007669 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007670 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007671 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7672 BO_NE, S.Context.BoolTy,
7673 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007674
7675 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007676 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007677 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7678 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007679
7680 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007681 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007682 IterationVarRefRVal,
7683 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007684 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007685 IterationVarRefRVal,
7686 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007687 if (!Copying) // Cast to rvalue
7688 From = CastForMoving(S, From);
7689
7690 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007691 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7692 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007693 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007694 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007695 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007696
7697 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007698 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007699 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007700 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007701 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007702}
7703
Sean Hunt30de05c2011-05-14 05:23:20 +00007704std::pair<Sema::ImplicitExceptionSpecification, bool>
7705Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7706 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007707 if (ClassDecl->isInvalidDecl())
7708 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7709
Douglas Gregord3c35902010-07-01 16:36:15 +00007710 // C++ [class.copy]p10:
7711 // If the class definition does not explicitly declare a copy
7712 // assignment operator, one is declared implicitly.
7713 // The implicitly-defined copy assignment operator for a class X
7714 // will have the form
7715 //
7716 // X& X::operator=(const X&)
7717 //
7718 // if
7719 bool HasConstCopyAssignment = true;
7720
7721 // -- each direct base class B of X has a copy assignment operator
7722 // whose parameter is of type const B&, const volatile B& or B,
7723 // and
7724 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7725 BaseEnd = ClassDecl->bases_end();
7726 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007727 // We'll handle this below
7728 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7729 continue;
7730
Douglas Gregord3c35902010-07-01 16:36:15 +00007731 assert(!Base->getType()->isDependentType() &&
7732 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007733 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7734 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7735 &HasConstCopyAssignment);
7736 }
7737
Richard Smithebaf0e62011-10-18 20:49:44 +00007738 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007739 if (LangOpts.CPlusPlus0x) {
7740 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7741 BaseEnd = ClassDecl->vbases_end();
7742 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7743 assert(!Base->getType()->isDependentType() &&
7744 "Cannot generate implicit members for class with dependent bases.");
7745 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7746 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7747 &HasConstCopyAssignment);
7748 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007749 }
7750
7751 // -- for all the nonstatic data members of X that are of a class
7752 // type M (or array thereof), each such class type has a copy
7753 // assignment operator whose parameter is of type const M&,
7754 // const volatile M& or M.
7755 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7756 FieldEnd = ClassDecl->field_end();
7757 HasConstCopyAssignment && Field != FieldEnd;
7758 ++Field) {
7759 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007760 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7761 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7762 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007763 }
7764 }
7765
7766 // Otherwise, the implicitly declared copy assignment operator will
7767 // have the form
7768 //
7769 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007770
Douglas Gregorb87786f2010-07-01 17:48:08 +00007771 // C++ [except.spec]p14:
7772 // An implicitly declared special member function (Clause 12) shall have an
7773 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007774
7775 // It is unspecified whether or not an implicit copy assignment operator
7776 // attempts to deduplicate calls to assignment operators of virtual bases are
7777 // made. As such, this exception specification is effectively unspecified.
7778 // Based on a similar decision made for constness in C++0x, we're erring on
7779 // the side of assuming such calls to be made regardless of whether they
7780 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007781 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007782 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007783 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7784 BaseEnd = ClassDecl->bases_end();
7785 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007786 if (Base->isVirtual())
7787 continue;
7788
Douglas Gregora376d102010-07-02 21:50:04 +00007789 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007790 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007791 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7792 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007793 ExceptSpec.CalledDecl(CopyAssign);
7794 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007795
7796 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7797 BaseEnd = ClassDecl->vbases_end();
7798 Base != BaseEnd; ++Base) {
7799 CXXRecordDecl *BaseClassDecl
7800 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7801 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7802 ArgQuals, false, 0))
7803 ExceptSpec.CalledDecl(CopyAssign);
7804 }
7805
Douglas Gregorb87786f2010-07-01 17:48:08 +00007806 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7807 FieldEnd = ClassDecl->field_end();
7808 Field != FieldEnd;
7809 ++Field) {
7810 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007811 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7812 if (CXXMethodDecl *CopyAssign =
7813 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7814 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007815 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007816 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007817
Sean Hunt30de05c2011-05-14 05:23:20 +00007818 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7819}
7820
7821CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7822 // Note: The following rules are largely analoguous to the copy
7823 // constructor rules. Note that virtual bases are not taken into account
7824 // for determining the argument type of the operator. Note also that
7825 // operators taking an object instead of a reference are allowed.
7826
7827 ImplicitExceptionSpecification Spec(Context);
7828 bool Const;
7829 llvm::tie(Spec, Const) =
7830 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7831
7832 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7833 QualType RetType = Context.getLValueReferenceType(ArgType);
7834 if (Const)
7835 ArgType = ArgType.withConst();
7836 ArgType = Context.getLValueReferenceType(ArgType);
7837
Douglas Gregord3c35902010-07-01 16:36:15 +00007838 // An implicitly-declared copy assignment operator is an inline public
7839 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007840 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007841 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007842 SourceLocation ClassLoc = ClassDecl->getLocation();
7843 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007844 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007845 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007846 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007847 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007848 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007849 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007850 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007851 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007852 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007853 CopyAssignment->setImplicit();
7854 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007855
7856 // Add the parameter to the operator.
7857 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007858 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007859 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007860 SC_None,
7861 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007862 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007863
Douglas Gregora376d102010-07-02 21:50:04 +00007864 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007865 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007866
Douglas Gregor23c94db2010-07-02 17:43:08 +00007867 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007868 PushOnScopeChains(CopyAssignment, S, false);
7869 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007870
Nico Weberafcc96a2012-01-23 03:19:29 +00007871 // C++0x [class.copy]p19:
7872 // .... If the class definition does not explicitly declare a copy
7873 // assignment operator, there is no user-declared move constructor, and
7874 // there is no user-declared move assignment operator, a copy assignment
7875 // operator is implicitly declared as defaulted.
7876 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007877 !getLangOptions().MicrosoftMode) ||
7878 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007879 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007880 CopyAssignment->setDeletedAsWritten();
7881
Douglas Gregord3c35902010-07-01 16:36:15 +00007882 AddOverriddenMethods(ClassDecl, CopyAssignment);
7883 return CopyAssignment;
7884}
7885
Douglas Gregor06a9f362010-05-01 20:49:11 +00007886void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7887 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007888 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007889 CopyAssignOperator->isOverloadedOperator() &&
7890 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007891 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007892 "DefineImplicitCopyAssignment called for wrong function");
7893
7894 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7895
7896 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7897 CopyAssignOperator->setInvalidDecl();
7898 return;
7899 }
7900
7901 CopyAssignOperator->setUsed();
7902
7903 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007904 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007905
7906 // C++0x [class.copy]p30:
7907 // The implicitly-defined or explicitly-defaulted copy assignment operator
7908 // for a non-union class X performs memberwise copy assignment of its
7909 // subobjects. The direct base classes of X are assigned first, in the
7910 // order of their declaration in the base-specifier-list, and then the
7911 // immediate non-static data members of X are assigned, in the order in
7912 // which they were declared in the class definition.
7913
7914 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007915 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007916
7917 // The parameter for the "other" object, which we are copying from.
7918 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7919 Qualifiers OtherQuals = Other->getType().getQualifiers();
7920 QualType OtherRefType = Other->getType();
7921 if (const LValueReferenceType *OtherRef
7922 = OtherRefType->getAs<LValueReferenceType>()) {
7923 OtherRefType = OtherRef->getPointeeType();
7924 OtherQuals = OtherRefType.getQualifiers();
7925 }
7926
7927 // Our location for everything implicitly-generated.
7928 SourceLocation Loc = CopyAssignOperator->getLocation();
7929
7930 // Construct a reference to the "other" object. We'll be using this
7931 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007932 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007933 assert(OtherRef && "Reference to parameter cannot fail!");
7934
7935 // Construct the "this" pointer. We'll be using this throughout the generated
7936 // ASTs.
7937 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7938 assert(This && "Reference to this cannot fail!");
7939
7940 // Assign base classes.
7941 bool Invalid = false;
7942 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7943 E = ClassDecl->bases_end(); Base != E; ++Base) {
7944 // Form the assignment:
7945 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7946 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007947 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007948 Invalid = true;
7949 continue;
7950 }
7951
John McCallf871d0c2010-08-07 06:22:56 +00007952 CXXCastPath BasePath;
7953 BasePath.push_back(Base);
7954
Douglas Gregor06a9f362010-05-01 20:49:11 +00007955 // Construct the "from" expression, which is an implicit cast to the
7956 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007957 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007958 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7959 CK_UncheckedDerivedToBase,
7960 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007961
7962 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007963 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007964
7965 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007966 To = ImpCastExprToType(To.take(),
7967 Context.getCVRQualifiedType(BaseType,
7968 CopyAssignOperator->getTypeQualifiers()),
7969 CK_UncheckedDerivedToBase,
7970 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007971
7972 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007973 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007974 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007975 /*CopyingBaseSubobject=*/true,
7976 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007977 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007978 Diag(CurrentLocation, diag::note_member_synthesized_at)
7979 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7980 CopyAssignOperator->setInvalidDecl();
7981 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007982 }
7983
7984 // Success! Record the copy.
7985 Statements.push_back(Copy.takeAs<Expr>());
7986 }
7987
7988 // \brief Reference to the __builtin_memcpy function.
7989 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007990 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007991 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007992
7993 // Assign non-static members.
7994 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7995 FieldEnd = ClassDecl->field_end();
7996 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007997 if (Field->isUnnamedBitfield())
7998 continue;
7999
Douglas Gregor06a9f362010-05-01 20:49:11 +00008000 // Check for members of reference type; we can't copy those.
8001 if (Field->getType()->isReferenceType()) {
8002 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8003 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8004 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008005 Diag(CurrentLocation, diag::note_member_synthesized_at)
8006 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008007 Invalid = true;
8008 continue;
8009 }
8010
8011 // Check for members of const-qualified, non-class type.
8012 QualType BaseType = Context.getBaseElementType(Field->getType());
8013 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8014 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8015 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8016 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008017 Diag(CurrentLocation, diag::note_member_synthesized_at)
8018 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008019 Invalid = true;
8020 continue;
8021 }
John McCallb77115d2011-06-17 00:18:42 +00008022
8023 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008024 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8025 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008026
8027 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008028 if (FieldType->isIncompleteArrayType()) {
8029 assert(ClassDecl->hasFlexibleArrayMember() &&
8030 "Incomplete array type is not valid");
8031 continue;
8032 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008033
8034 // Build references to the field in the object we're copying from and to.
8035 CXXScopeSpec SS; // Intentionally empty
8036 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8037 LookupMemberName);
8038 MemberLookup.addDecl(*Field);
8039 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008040 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008041 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008042 SS, SourceLocation(), 0,
8043 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008044 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008045 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008046 SS, SourceLocation(), 0,
8047 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008048 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8049 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8050
8051 // If the field should be copied with __builtin_memcpy rather than via
8052 // explicit assignments, do so. This optimization only applies for arrays
8053 // of scalars and arrays of class type with trivial copy-assignment
8054 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008055 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008056 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008057 // Compute the size of the memory buffer to be copied.
8058 QualType SizeType = Context.getSizeType();
8059 llvm::APInt Size(Context.getTypeSize(SizeType),
8060 Context.getTypeSizeInChars(BaseType).getQuantity());
8061 for (const ConstantArrayType *Array
8062 = Context.getAsConstantArrayType(FieldType);
8063 Array;
8064 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008065 llvm::APInt ArraySize
8066 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008067 Size *= ArraySize;
8068 }
8069
8070 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008071 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8072 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008073
8074 bool NeedsCollectableMemCpy =
8075 (BaseType->isRecordType() &&
8076 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8077
8078 if (NeedsCollectableMemCpy) {
8079 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008080 // Create a reference to the __builtin_objc_memmove_collectable function.
8081 LookupResult R(*this,
8082 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008083 Loc, LookupOrdinaryName);
8084 LookupName(R, TUScope, true);
8085
8086 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8087 if (!CollectableMemCpy) {
8088 // Something went horribly wrong earlier, and we will have
8089 // complained about it.
8090 Invalid = true;
8091 continue;
8092 }
8093
8094 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8095 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008096 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008097 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8098 }
8099 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008100 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008101 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008102 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8103 LookupOrdinaryName);
8104 LookupName(R, TUScope, true);
8105
8106 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8107 if (!BuiltinMemCpy) {
8108 // Something went horribly wrong earlier, and we will have complained
8109 // about it.
8110 Invalid = true;
8111 continue;
8112 }
8113
8114 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8115 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008116 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008117 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8118 }
8119
John McCallca0408f2010-08-23 06:44:23 +00008120 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008121 CallArgs.push_back(To.takeAs<Expr>());
8122 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008123 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008124 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008125 if (NeedsCollectableMemCpy)
8126 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008127 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008128 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008129 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008130 else
8131 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008132 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008133 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008134 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008135
Douglas Gregor06a9f362010-05-01 20:49:11 +00008136 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8137 Statements.push_back(Call.takeAs<Expr>());
8138 continue;
8139 }
8140
8141 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008142 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008143 To.get(), From.get(),
8144 /*CopyingBaseSubobject=*/false,
8145 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008146 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008147 Diag(CurrentLocation, diag::note_member_synthesized_at)
8148 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8149 CopyAssignOperator->setInvalidDecl();
8150 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008151 }
8152
8153 // Success! Record the copy.
8154 Statements.push_back(Copy.takeAs<Stmt>());
8155 }
8156
8157 if (!Invalid) {
8158 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008159 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008160
John McCall60d7b3a2010-08-24 06:29:42 +00008161 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008162 if (Return.isInvalid())
8163 Invalid = true;
8164 else {
8165 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008166
8167 if (Trap.hasErrorOccurred()) {
8168 Diag(CurrentLocation, diag::note_member_synthesized_at)
8169 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8170 Invalid = true;
8171 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008172 }
8173 }
8174
8175 if (Invalid) {
8176 CopyAssignOperator->setInvalidDecl();
8177 return;
8178 }
8179
John McCall60d7b3a2010-08-24 06:29:42 +00008180 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008181 /*isStmtExpr=*/false);
8182 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8183 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008184
8185 if (ASTMutationListener *L = getASTMutationListener()) {
8186 L->CompletedImplicitDefinition(CopyAssignOperator);
8187 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008188}
8189
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008190Sema::ImplicitExceptionSpecification
8191Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8192 ImplicitExceptionSpecification ExceptSpec(Context);
8193
8194 if (ClassDecl->isInvalidDecl())
8195 return ExceptSpec;
8196
8197 // C++0x [except.spec]p14:
8198 // An implicitly declared special member function (Clause 12) shall have an
8199 // exception-specification. [...]
8200
8201 // It is unspecified whether or not an implicit move assignment operator
8202 // attempts to deduplicate calls to assignment operators of virtual bases are
8203 // made. As such, this exception specification is effectively unspecified.
8204 // Based on a similar decision made for constness in C++0x, we're erring on
8205 // the side of assuming such calls to be made regardless of whether they
8206 // actually happen.
8207 // Note that a move constructor is not implicitly declared when there are
8208 // virtual bases, but it can still be user-declared and explicitly defaulted.
8209 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8210 BaseEnd = ClassDecl->bases_end();
8211 Base != BaseEnd; ++Base) {
8212 if (Base->isVirtual())
8213 continue;
8214
8215 CXXRecordDecl *BaseClassDecl
8216 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8217 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8218 false, 0))
8219 ExceptSpec.CalledDecl(MoveAssign);
8220 }
8221
8222 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8223 BaseEnd = ClassDecl->vbases_end();
8224 Base != BaseEnd; ++Base) {
8225 CXXRecordDecl *BaseClassDecl
8226 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8227 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8228 false, 0))
8229 ExceptSpec.CalledDecl(MoveAssign);
8230 }
8231
8232 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8233 FieldEnd = ClassDecl->field_end();
8234 Field != FieldEnd;
8235 ++Field) {
8236 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8237 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8238 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8239 false, 0))
8240 ExceptSpec.CalledDecl(MoveAssign);
8241 }
8242 }
8243
8244 return ExceptSpec;
8245}
8246
8247CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8248 // Note: The following rules are largely analoguous to the move
8249 // constructor rules.
8250
8251 ImplicitExceptionSpecification Spec(
8252 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8253
8254 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8255 QualType RetType = Context.getLValueReferenceType(ArgType);
8256 ArgType = Context.getRValueReferenceType(ArgType);
8257
8258 // An implicitly-declared move assignment operator is an inline public
8259 // member of its class.
8260 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8261 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8262 SourceLocation ClassLoc = ClassDecl->getLocation();
8263 DeclarationNameInfo NameInfo(Name, ClassLoc);
8264 CXXMethodDecl *MoveAssignment
8265 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8266 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8267 /*TInfo=*/0, /*isStatic=*/false,
8268 /*StorageClassAsWritten=*/SC_None,
8269 /*isInline=*/true,
8270 /*isConstexpr=*/false,
8271 SourceLocation());
8272 MoveAssignment->setAccess(AS_public);
8273 MoveAssignment->setDefaulted();
8274 MoveAssignment->setImplicit();
8275 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8276
8277 // Add the parameter to the operator.
8278 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8279 ClassLoc, ClassLoc, /*Id=*/0,
8280 ArgType, /*TInfo=*/0,
8281 SC_None,
8282 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008283 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008284
8285 // Note that we have added this copy-assignment operator.
8286 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8287
8288 // C++0x [class.copy]p9:
8289 // If the definition of a class X does not explicitly declare a move
8290 // assignment operator, one will be implicitly declared as defaulted if and
8291 // only if:
8292 // [...]
8293 // - the move assignment operator would not be implicitly defined as
8294 // deleted.
8295 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8296 // Cache this result so that we don't try to generate this over and over
8297 // on every lookup, leaking memory and wasting time.
8298 ClassDecl->setFailedImplicitMoveAssignment();
8299 return 0;
8300 }
8301
8302 if (Scope *S = getScopeForContext(ClassDecl))
8303 PushOnScopeChains(MoveAssignment, S, false);
8304 ClassDecl->addDecl(MoveAssignment);
8305
8306 AddOverriddenMethods(ClassDecl, MoveAssignment);
8307 return MoveAssignment;
8308}
8309
8310void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8311 CXXMethodDecl *MoveAssignOperator) {
8312 assert((MoveAssignOperator->isDefaulted() &&
8313 MoveAssignOperator->isOverloadedOperator() &&
8314 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8315 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8316 "DefineImplicitMoveAssignment called for wrong function");
8317
8318 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8319
8320 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8321 MoveAssignOperator->setInvalidDecl();
8322 return;
8323 }
8324
8325 MoveAssignOperator->setUsed();
8326
8327 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8328 DiagnosticErrorTrap Trap(Diags);
8329
8330 // C++0x [class.copy]p28:
8331 // The implicitly-defined or move assignment operator for a non-union class
8332 // X performs memberwise move assignment of its subobjects. The direct base
8333 // classes of X are assigned first, in the order of their declaration in the
8334 // base-specifier-list, and then the immediate non-static data members of X
8335 // are assigned, in the order in which they were declared in the class
8336 // definition.
8337
8338 // The statements that form the synthesized function body.
8339 ASTOwningVector<Stmt*> Statements(*this);
8340
8341 // The parameter for the "other" object, which we are move from.
8342 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8343 QualType OtherRefType = Other->getType()->
8344 getAs<RValueReferenceType>()->getPointeeType();
8345 assert(OtherRefType.getQualifiers() == 0 &&
8346 "Bad argument type of defaulted move assignment");
8347
8348 // Our location for everything implicitly-generated.
8349 SourceLocation Loc = MoveAssignOperator->getLocation();
8350
8351 // Construct a reference to the "other" object. We'll be using this
8352 // throughout the generated ASTs.
8353 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8354 assert(OtherRef && "Reference to parameter cannot fail!");
8355 // Cast to rvalue.
8356 OtherRef = CastForMoving(*this, OtherRef);
8357
8358 // Construct the "this" pointer. We'll be using this throughout the generated
8359 // ASTs.
8360 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8361 assert(This && "Reference to this cannot fail!");
8362
8363 // Assign base classes.
8364 bool Invalid = false;
8365 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8366 E = ClassDecl->bases_end(); Base != E; ++Base) {
8367 // Form the assignment:
8368 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8369 QualType BaseType = Base->getType().getUnqualifiedType();
8370 if (!BaseType->isRecordType()) {
8371 Invalid = true;
8372 continue;
8373 }
8374
8375 CXXCastPath BasePath;
8376 BasePath.push_back(Base);
8377
8378 // Construct the "from" expression, which is an implicit cast to the
8379 // appropriately-qualified base type.
8380 Expr *From = OtherRef;
8381 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008382 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008383
8384 // Dereference "this".
8385 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8386
8387 // Implicitly cast "this" to the appropriately-qualified base type.
8388 To = ImpCastExprToType(To.take(),
8389 Context.getCVRQualifiedType(BaseType,
8390 MoveAssignOperator->getTypeQualifiers()),
8391 CK_UncheckedDerivedToBase,
8392 VK_LValue, &BasePath);
8393
8394 // Build the move.
8395 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8396 To.get(), From,
8397 /*CopyingBaseSubobject=*/true,
8398 /*Copying=*/false);
8399 if (Move.isInvalid()) {
8400 Diag(CurrentLocation, diag::note_member_synthesized_at)
8401 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8402 MoveAssignOperator->setInvalidDecl();
8403 return;
8404 }
8405
8406 // Success! Record the move.
8407 Statements.push_back(Move.takeAs<Expr>());
8408 }
8409
8410 // \brief Reference to the __builtin_memcpy function.
8411 Expr *BuiltinMemCpyRef = 0;
8412 // \brief Reference to the __builtin_objc_memmove_collectable function.
8413 Expr *CollectableMemCpyRef = 0;
8414
8415 // Assign non-static members.
8416 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8417 FieldEnd = ClassDecl->field_end();
8418 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008419 if (Field->isUnnamedBitfield())
8420 continue;
8421
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008422 // Check for members of reference type; we can't move those.
8423 if (Field->getType()->isReferenceType()) {
8424 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8425 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8426 Diag(Field->getLocation(), diag::note_declared_at);
8427 Diag(CurrentLocation, diag::note_member_synthesized_at)
8428 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8429 Invalid = true;
8430 continue;
8431 }
8432
8433 // Check for members of const-qualified, non-class type.
8434 QualType BaseType = Context.getBaseElementType(Field->getType());
8435 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8436 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8437 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8438 Diag(Field->getLocation(), diag::note_declared_at);
8439 Diag(CurrentLocation, diag::note_member_synthesized_at)
8440 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8441 Invalid = true;
8442 continue;
8443 }
8444
8445 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008446 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8447 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008448
8449 QualType FieldType = Field->getType().getNonReferenceType();
8450 if (FieldType->isIncompleteArrayType()) {
8451 assert(ClassDecl->hasFlexibleArrayMember() &&
8452 "Incomplete array type is not valid");
8453 continue;
8454 }
8455
8456 // Build references to the field in the object we're copying from and to.
8457 CXXScopeSpec SS; // Intentionally empty
8458 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8459 LookupMemberName);
8460 MemberLookup.addDecl(*Field);
8461 MemberLookup.resolveKind();
8462 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8463 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008464 SS, SourceLocation(), 0,
8465 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008466 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8467 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008468 SS, SourceLocation(), 0,
8469 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008470 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8471 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8472
8473 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8474 "Member reference with rvalue base must be rvalue except for reference "
8475 "members, which aren't allowed for move assignment.");
8476
8477 // If the field should be copied with __builtin_memcpy rather than via
8478 // explicit assignments, do so. This optimization only applies for arrays
8479 // of scalars and arrays of class type with trivial move-assignment
8480 // operators.
8481 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8482 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8483 // Compute the size of the memory buffer to be copied.
8484 QualType SizeType = Context.getSizeType();
8485 llvm::APInt Size(Context.getTypeSize(SizeType),
8486 Context.getTypeSizeInChars(BaseType).getQuantity());
8487 for (const ConstantArrayType *Array
8488 = Context.getAsConstantArrayType(FieldType);
8489 Array;
8490 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8491 llvm::APInt ArraySize
8492 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8493 Size *= ArraySize;
8494 }
8495
Douglas Gregor45d3d712011-09-01 02:09:07 +00008496 // Take the address of the field references for "from" and "to". We
8497 // directly construct UnaryOperators here because semantic analysis
8498 // does not permit us to take the address of an xvalue.
8499 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8500 Context.getPointerType(From.get()->getType()),
8501 VK_RValue, OK_Ordinary, Loc);
8502 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8503 Context.getPointerType(To.get()->getType()),
8504 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008505
8506 bool NeedsCollectableMemCpy =
8507 (BaseType->isRecordType() &&
8508 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8509
8510 if (NeedsCollectableMemCpy) {
8511 if (!CollectableMemCpyRef) {
8512 // Create a reference to the __builtin_objc_memmove_collectable function.
8513 LookupResult R(*this,
8514 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8515 Loc, LookupOrdinaryName);
8516 LookupName(R, TUScope, true);
8517
8518 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8519 if (!CollectableMemCpy) {
8520 // Something went horribly wrong earlier, and we will have
8521 // complained about it.
8522 Invalid = true;
8523 continue;
8524 }
8525
8526 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8527 CollectableMemCpy->getType(),
8528 VK_LValue, Loc, 0).take();
8529 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8530 }
8531 }
8532 // Create a reference to the __builtin_memcpy builtin function.
8533 else if (!BuiltinMemCpyRef) {
8534 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8535 LookupOrdinaryName);
8536 LookupName(R, TUScope, true);
8537
8538 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8539 if (!BuiltinMemCpy) {
8540 // Something went horribly wrong earlier, and we will have complained
8541 // about it.
8542 Invalid = true;
8543 continue;
8544 }
8545
8546 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8547 BuiltinMemCpy->getType(),
8548 VK_LValue, Loc, 0).take();
8549 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8550 }
8551
8552 ASTOwningVector<Expr*> CallArgs(*this);
8553 CallArgs.push_back(To.takeAs<Expr>());
8554 CallArgs.push_back(From.takeAs<Expr>());
8555 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8556 ExprResult Call = ExprError();
8557 if (NeedsCollectableMemCpy)
8558 Call = ActOnCallExpr(/*Scope=*/0,
8559 CollectableMemCpyRef,
8560 Loc, move_arg(CallArgs),
8561 Loc);
8562 else
8563 Call = ActOnCallExpr(/*Scope=*/0,
8564 BuiltinMemCpyRef,
8565 Loc, move_arg(CallArgs),
8566 Loc);
8567
8568 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8569 Statements.push_back(Call.takeAs<Expr>());
8570 continue;
8571 }
8572
8573 // Build the move of this field.
8574 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8575 To.get(), From.get(),
8576 /*CopyingBaseSubobject=*/false,
8577 /*Copying=*/false);
8578 if (Move.isInvalid()) {
8579 Diag(CurrentLocation, diag::note_member_synthesized_at)
8580 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8581 MoveAssignOperator->setInvalidDecl();
8582 return;
8583 }
8584
8585 // Success! Record the copy.
8586 Statements.push_back(Move.takeAs<Stmt>());
8587 }
8588
8589 if (!Invalid) {
8590 // Add a "return *this;"
8591 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8592
8593 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8594 if (Return.isInvalid())
8595 Invalid = true;
8596 else {
8597 Statements.push_back(Return.takeAs<Stmt>());
8598
8599 if (Trap.hasErrorOccurred()) {
8600 Diag(CurrentLocation, diag::note_member_synthesized_at)
8601 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8602 Invalid = true;
8603 }
8604 }
8605 }
8606
8607 if (Invalid) {
8608 MoveAssignOperator->setInvalidDecl();
8609 return;
8610 }
8611
8612 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8613 /*isStmtExpr=*/false);
8614 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8615 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8616
8617 if (ASTMutationListener *L = getASTMutationListener()) {
8618 L->CompletedImplicitDefinition(MoveAssignOperator);
8619 }
8620}
8621
Sean Hunt49634cf2011-05-13 06:10:58 +00008622std::pair<Sema::ImplicitExceptionSpecification, bool>
8623Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008624 if (ClassDecl->isInvalidDecl())
8625 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8626
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008627 // C++ [class.copy]p5:
8628 // The implicitly-declared copy constructor for a class X will
8629 // have the form
8630 //
8631 // X::X(const X&)
8632 //
8633 // if
Sean Huntc530d172011-06-10 04:44:37 +00008634 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008635 bool HasConstCopyConstructor = true;
8636
8637 // -- each direct or virtual base class B of X has a copy
8638 // constructor whose first parameter is of type const B& or
8639 // const volatile B&, and
8640 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8641 BaseEnd = ClassDecl->bases_end();
8642 HasConstCopyConstructor && Base != BaseEnd;
8643 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008644 // Virtual bases are handled below.
8645 if (Base->isVirtual())
8646 continue;
8647
Douglas Gregor22584312010-07-02 23:41:54 +00008648 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008649 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008650 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8651 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008652 }
8653
8654 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8655 BaseEnd = ClassDecl->vbases_end();
8656 HasConstCopyConstructor && Base != BaseEnd;
8657 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008658 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008659 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008660 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8661 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008662 }
8663
8664 // -- for all the nonstatic data members of X that are of a
8665 // class type M (or array thereof), each such class type
8666 // has a copy constructor whose first parameter is of type
8667 // const M& or const volatile M&.
8668 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8669 FieldEnd = ClassDecl->field_end();
8670 HasConstCopyConstructor && Field != FieldEnd;
8671 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008672 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008673 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008674 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8675 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008676 }
8677 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008678 // Otherwise, the implicitly declared copy constructor will have
8679 // the form
8680 //
8681 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008682
Douglas Gregor0d405db2010-07-01 20:59:04 +00008683 // C++ [except.spec]p14:
8684 // An implicitly declared special member function (Clause 12) shall have an
8685 // exception-specification. [...]
8686 ImplicitExceptionSpecification ExceptSpec(Context);
8687 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8688 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8689 BaseEnd = ClassDecl->bases_end();
8690 Base != BaseEnd;
8691 ++Base) {
8692 // Virtual bases are handled below.
8693 if (Base->isVirtual())
8694 continue;
8695
Douglas Gregor22584312010-07-02 23:41:54 +00008696 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008697 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008698 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008699 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008700 ExceptSpec.CalledDecl(CopyConstructor);
8701 }
8702 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8703 BaseEnd = ClassDecl->vbases_end();
8704 Base != BaseEnd;
8705 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008706 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008707 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008708 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008709 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008710 ExceptSpec.CalledDecl(CopyConstructor);
8711 }
8712 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8713 FieldEnd = ClassDecl->field_end();
8714 Field != FieldEnd;
8715 ++Field) {
8716 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008717 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8718 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008719 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008720 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008721 }
8722 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008723
Sean Hunt49634cf2011-05-13 06:10:58 +00008724 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8725}
8726
8727CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8728 CXXRecordDecl *ClassDecl) {
8729 // C++ [class.copy]p4:
8730 // If the class definition does not explicitly declare a copy
8731 // constructor, one is declared implicitly.
8732
8733 ImplicitExceptionSpecification Spec(Context);
8734 bool Const;
8735 llvm::tie(Spec, Const) =
8736 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8737
8738 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8739 QualType ArgType = ClassType;
8740 if (Const)
8741 ArgType = ArgType.withConst();
8742 ArgType = Context.getLValueReferenceType(ArgType);
8743
8744 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8745
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008746 DeclarationName Name
8747 = Context.DeclarationNames.getCXXConstructorName(
8748 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008749 SourceLocation ClassLoc = ClassDecl->getLocation();
8750 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008751
8752 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008753 // member of its class.
8754 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8755 Context, ClassDecl, ClassLoc, NameInfo,
8756 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8757 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8758 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8759 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008760 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008761 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008762 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008763
Douglas Gregor22584312010-07-02 23:41:54 +00008764 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008765 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8766
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008767 // Add the parameter to the constructor.
8768 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008769 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008770 /*IdentifierInfo=*/0,
8771 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008772 SC_None,
8773 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008774 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008775
Douglas Gregor23c94db2010-07-02 17:43:08 +00008776 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008777 PushOnScopeChains(CopyConstructor, S, false);
8778 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008779
Nico Weberafcc96a2012-01-23 03:19:29 +00008780 // C++11 [class.copy]p8:
8781 // ... If the class definition does not explicitly declare a copy
8782 // constructor, there is no user-declared move constructor, and there is no
8783 // user-declared move assignment operator, a copy constructor is implicitly
8784 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008785 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008786 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008787 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008788 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008789 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008790
8791 return CopyConstructor;
8792}
8793
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008794void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008795 CXXConstructorDecl *CopyConstructor) {
8796 assert((CopyConstructor->isDefaulted() &&
8797 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008798 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008799 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008800
Anders Carlsson63010a72010-04-23 16:24:12 +00008801 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008802 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008803
Douglas Gregor39957dc2010-05-01 15:04:51 +00008804 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008805 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008806
Sean Huntcbb67482011-01-08 20:30:50 +00008807 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008808 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008809 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008810 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008811 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008812 } else {
8813 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8814 CopyConstructor->getLocation(),
8815 MultiStmtArg(*this, 0, 0),
8816 /*isStmtExpr=*/false)
8817 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008818 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008819 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008820
8821 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008822 if (ASTMutationListener *L = getASTMutationListener()) {
8823 L->CompletedImplicitDefinition(CopyConstructor);
8824 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008825}
8826
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008827Sema::ImplicitExceptionSpecification
8828Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8829 // C++ [except.spec]p14:
8830 // An implicitly declared special member function (Clause 12) shall have an
8831 // exception-specification. [...]
8832 ImplicitExceptionSpecification ExceptSpec(Context);
8833 if (ClassDecl->isInvalidDecl())
8834 return ExceptSpec;
8835
8836 // Direct base-class constructors.
8837 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8838 BEnd = ClassDecl->bases_end();
8839 B != BEnd; ++B) {
8840 if (B->isVirtual()) // Handled below.
8841 continue;
8842
8843 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8844 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8845 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8846 // If this is a deleted function, add it anyway. This might be conformant
8847 // with the standard. This might not. I'm not sure. It might not matter.
8848 if (Constructor)
8849 ExceptSpec.CalledDecl(Constructor);
8850 }
8851 }
8852
8853 // Virtual base-class constructors.
8854 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8855 BEnd = ClassDecl->vbases_end();
8856 B != BEnd; ++B) {
8857 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8858 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8859 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8860 // If this is a deleted function, add it anyway. This might be conformant
8861 // with the standard. This might not. I'm not sure. It might not matter.
8862 if (Constructor)
8863 ExceptSpec.CalledDecl(Constructor);
8864 }
8865 }
8866
8867 // Field constructors.
8868 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8869 FEnd = ClassDecl->field_end();
8870 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008871 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008872 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8873 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8874 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8875 // If this is a deleted function, add it anyway. This might be conformant
8876 // with the standard. This might not. I'm not sure. It might not matter.
8877 // In particular, the problem is that this function never gets called. It
8878 // might just be ill-formed because this function attempts to refer to
8879 // a deleted function here.
8880 if (Constructor)
8881 ExceptSpec.CalledDecl(Constructor);
8882 }
8883 }
8884
8885 return ExceptSpec;
8886}
8887
8888CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8889 CXXRecordDecl *ClassDecl) {
8890 ImplicitExceptionSpecification Spec(
8891 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8892
8893 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8894 QualType ArgType = Context.getRValueReferenceType(ClassType);
8895
8896 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8897
8898 DeclarationName Name
8899 = Context.DeclarationNames.getCXXConstructorName(
8900 Context.getCanonicalType(ClassType));
8901 SourceLocation ClassLoc = ClassDecl->getLocation();
8902 DeclarationNameInfo NameInfo(Name, ClassLoc);
8903
8904 // C++0x [class.copy]p11:
8905 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008906 // member of its class.
8907 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8908 Context, ClassDecl, ClassLoc, NameInfo,
8909 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8910 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8911 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8912 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008913 MoveConstructor->setAccess(AS_public);
8914 MoveConstructor->setDefaulted();
8915 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008916
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008917 // Add the parameter to the constructor.
8918 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8919 ClassLoc, ClassLoc,
8920 /*IdentifierInfo=*/0,
8921 ArgType, /*TInfo=*/0,
8922 SC_None,
8923 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008924 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008925
8926 // C++0x [class.copy]p9:
8927 // If the definition of a class X does not explicitly declare a move
8928 // constructor, one will be implicitly declared as defaulted if and only if:
8929 // [...]
8930 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008931 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008932 // Cache this result so that we don't try to generate this over and over
8933 // on every lookup, leaking memory and wasting time.
8934 ClassDecl->setFailedImplicitMoveConstructor();
8935 return 0;
8936 }
8937
8938 // Note that we have declared this constructor.
8939 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8940
8941 if (Scope *S = getScopeForContext(ClassDecl))
8942 PushOnScopeChains(MoveConstructor, S, false);
8943 ClassDecl->addDecl(MoveConstructor);
8944
8945 return MoveConstructor;
8946}
8947
8948void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8949 CXXConstructorDecl *MoveConstructor) {
8950 assert((MoveConstructor->isDefaulted() &&
8951 MoveConstructor->isMoveConstructor() &&
8952 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8953 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8954
8955 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8956 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8957
8958 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8959 DiagnosticErrorTrap Trap(Diags);
8960
8961 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8962 Trap.hasErrorOccurred()) {
8963 Diag(CurrentLocation, diag::note_member_synthesized_at)
8964 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8965 MoveConstructor->setInvalidDecl();
8966 } else {
8967 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8968 MoveConstructor->getLocation(),
8969 MultiStmtArg(*this, 0, 0),
8970 /*isStmtExpr=*/false)
8971 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008972 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008973 }
8974
8975 MoveConstructor->setUsed();
8976
8977 if (ASTMutationListener *L = getASTMutationListener()) {
8978 L->CompletedImplicitDefinition(MoveConstructor);
8979 }
8980}
8981
John McCall60d7b3a2010-08-24 06:29:42 +00008982ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008983Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008984 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008985 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008986 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008987 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008988 unsigned ConstructKind,
8989 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008990 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008991
Douglas Gregor2f599792010-04-02 18:24:57 +00008992 // C++0x [class.copy]p34:
8993 // When certain criteria are met, an implementation is allowed to
8994 // omit the copy/move construction of a class object, even if the
8995 // copy/move constructor and/or destructor for the object have
8996 // side effects. [...]
8997 // - when a temporary class object that has not been bound to a
8998 // reference (12.2) would be copied/moved to a class object
8999 // with the same cv-unqualified type, the copy/move operation
9000 // can be omitted by constructing the temporary object
9001 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009002 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009003 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009004 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009005 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009006 }
Mike Stump1eb44332009-09-09 15:08:12 +00009007
9008 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009009 Elidable, move(ExprArgs), HadMultipleCandidates,
9010 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009011}
9012
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009013/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9014/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009015ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009016Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9017 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009018 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009019 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009020 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009021 unsigned ConstructKind,
9022 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009023 unsigned NumExprs = ExprArgs.size();
9024 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009025
Nick Lewycky909a70d2011-03-25 01:44:32 +00009026 for (specific_attr_iterator<NonNullAttr>
9027 i = Constructor->specific_attr_begin<NonNullAttr>(),
9028 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9029 const NonNullAttr *NonNull = *i;
9030 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9031 }
9032
Douglas Gregor7edfb692009-11-23 12:27:39 +00009033 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009034 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009035 Constructor, Elidable, Exprs, NumExprs,
9036 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009037 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9038 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009039}
9040
Mike Stump1eb44332009-09-09 15:08:12 +00009041bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009042 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009043 MultiExprArg Exprs,
9044 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009045 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009046 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009047 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009048 move(Exprs), HadMultipleCandidates, false,
9049 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009050 if (TempResult.isInvalid())
9051 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009052
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009053 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009054 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009055 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009056 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009057 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009058
Anders Carlssonfe2de492009-08-25 05:18:00 +00009059 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009060}
9061
John McCall68c6c9a2010-02-02 09:10:11 +00009062void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009063 if (VD->isInvalidDecl()) return;
9064
John McCall68c6c9a2010-02-02 09:10:11 +00009065 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009066 if (ClassDecl->isInvalidDecl()) return;
9067 if (ClassDecl->hasTrivialDestructor()) return;
9068 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009069
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009070 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9071 MarkDeclarationReferenced(VD->getLocation(), Destructor);
9072 CheckDestructorAccess(VD->getLocation(), Destructor,
9073 PDiag(diag::err_access_dtor_var)
9074 << VD->getDeclName()
9075 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009076
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009077 if (!VD->hasGlobalStorage()) return;
9078
9079 // Emit warning for non-trivial dtor in global scope (a real global,
9080 // class-static, function-static).
9081 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9082
9083 // TODO: this should be re-enabled for static locals by !CXAAtExit
9084 if (!VD->isStaticLocal())
9085 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009086}
9087
Mike Stump1eb44332009-09-09 15:08:12 +00009088/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009089/// ActOnDeclarator, when a C++ direct initializer is present.
9090/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00009091void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00009092 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009093 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00009094 SourceLocation RParenLoc,
9095 bool TypeMayContainAuto) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009096 // If there is no declaration, there was an error parsing it. Just ignore
9097 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00009098 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009099 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009100
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009101 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9102 if (!VDecl) {
9103 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9104 RealDecl->setInvalidDecl();
9105 return;
9106 }
9107
Eli Friedman6aeaa602012-01-05 22:34:08 +00009108 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00009109 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedman6aeaa602012-01-05 22:34:08 +00009110 if (Exprs.size() == 0) {
9111 // It isn't possible to write this directly, but it is possible to
9112 // end up in this situation with "auto x(some_pack...);"
9113 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9114 << VDecl->getDeclName() << VDecl->getType()
9115 << VDecl->getSourceRange();
9116 RealDecl->setInvalidDecl();
9117 return;
9118 }
9119
Richard Smith34b41d92011-02-20 03:19:35 +00009120 if (Exprs.size() > 1) {
9121 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9122 diag::err_auto_var_init_multiple_expressions)
9123 << VDecl->getDeclName() << VDecl->getType()
9124 << VDecl->getSourceRange();
9125 RealDecl->setInvalidDecl();
9126 return;
9127 }
9128
9129 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00009130 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00009131 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9132 DAR_Failed)
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00009133 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smitha085da82011-03-17 16:11:59 +00009134 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00009135 RealDecl->setInvalidDecl();
9136 return;
9137 }
Richard Smitha085da82011-03-17 16:11:59 +00009138 VDecl->setTypeSourceInfo(DeducedType);
9139 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00009140
John McCallf85e1932011-06-15 23:02:42 +00009141 // In ARC, infer lifetime.
9142 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9143 VDecl->setInvalidDecl();
9144
Richard Smith34b41d92011-02-20 03:19:35 +00009145 // If this is a redeclaration, check that the type we just deduced matches
9146 // the previously declared type.
Douglas Gregoref96ee02012-01-14 16:38:05 +00009147 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith34b41d92011-02-20 03:19:35 +00009148 MergeVarDeclTypes(VDecl, Old);
9149 }
9150
Douglas Gregor83ddad32009-08-26 21:14:46 +00009151 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009152 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009153 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9154 //
9155 // Clients that want to distinguish between the two forms, can check for
9156 // direct initializer using VarDecl::hasCXXDirectInitializer().
9157 // A major benefit is that clients that don't particularly care about which
9158 // exactly form was it (like the CodeGen) can handle both cases without
9159 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009160
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009161 // C++ 8.5p11:
9162 // The form of initialization (using parentheses or '=') is generally
9163 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009164 // class type.
9165
Douglas Gregor4dffad62010-02-11 22:55:30 +00009166 if (!VDecl->getType()->isDependentType() &&
Douglas Gregord24c3062011-10-10 16:05:18 +00009167 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor4dffad62010-02-11 22:55:30 +00009168 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00009169 diag::err_typecheck_decl_incomplete_type)) {
9170 VDecl->setInvalidDecl();
9171 return;
9172 }
9173
Douglas Gregor90f93822009-12-22 22:17:25 +00009174 // The variable can not have an abstract class type.
9175 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9176 diag::err_abstract_type_in_decl,
9177 AbstractVariableType))
9178 VDecl->setInvalidDecl();
9179
Sebastian Redl31310a22010-02-01 20:16:42 +00009180 const VarDecl *Def;
9181 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009182 Diag(VDecl->getLocation(), diag::err_redefinition)
9183 << VDecl->getDeclName();
9184 Diag(Def->getLocation(), diag::note_previous_definition);
9185 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009186 return;
9187 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009188
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009189 // C++ [class.static.data]p4
9190 // If a static data member is of const integral or const
9191 // enumeration type, its declaration in the class definition can
9192 // specify a constant-initializer which shall be an integral
9193 // constant expression (5.19). In that case, the member can appear
9194 // in integral constant expressions. The member shall still be
9195 // defined in a namespace scope if it is used in the program and the
9196 // namespace scope definition shall not contain an initializer.
9197 //
9198 // We already performed a redefinition check above, but for static
9199 // data members we also need to check whether there was an in-class
9200 // declaration with an initializer.
9201 const VarDecl* PrevInit = 0;
9202 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9203 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9204 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9205 return;
9206 }
9207
Douglas Gregora31040f2010-12-16 01:31:22 +00009208 bool IsDependent = false;
9209 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9210 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9211 VDecl->setInvalidDecl();
9212 return;
9213 }
9214
9215 if (Exprs.get()[I]->isTypeDependent())
9216 IsDependent = true;
9217 }
9218
Douglas Gregor4dffad62010-02-11 22:55:30 +00009219 // If either the declaration has a dependent type or if any of the
9220 // expressions is type-dependent, we represent the initialization
9221 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009222 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009223 // Let clients know that initialization was done with a direct initializer.
9224 VDecl->setCXXDirectInitializer(true);
9225
9226 // Store the initialization expressions as a ParenListExpr.
9227 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009228 VDecl->setInit(new (Context) ParenListExpr(
9229 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9230 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009231 return;
9232 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009233
9234 // Capture the variable that is being initialized and the style of
9235 // initialization.
9236 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9237
9238 // FIXME: Poor source location information.
9239 InitializationKind Kind
9240 = InitializationKind::CreateDirect(VDecl->getLocation(),
9241 LParenLoc, RParenLoc);
9242
Douglas Gregord24c3062011-10-10 16:05:18 +00009243 QualType T = VDecl->getType();
Douglas Gregor90f93822009-12-22 22:17:25 +00009244 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009245 Exprs.get(), Exprs.size());
Douglas Gregord24c3062011-10-10 16:05:18 +00009246 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregor90f93822009-12-22 22:17:25 +00009247 if (Result.isInvalid()) {
9248 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009249 return;
Douglas Gregord24c3062011-10-10 16:05:18 +00009250 } else if (T != VDecl->getType()) {
9251 VDecl->setType(T);
9252 Result.get()->setType(T);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009253 }
John McCallb4eb64d2010-10-08 02:01:28 +00009254
Douglas Gregord24c3062011-10-10 16:05:18 +00009255
Richard Smithc6d990a2011-09-29 19:11:37 +00009256 Expr *Init = Result.get();
9257 CheckImplicitConversions(Init, LParenLoc);
Richard Smithc6d990a2011-09-29 19:11:37 +00009258
9259 Init = MaybeCreateExprWithCleanups(Init);
9260 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009261 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009262
John McCall2998d6b2011-01-19 11:48:09 +00009263 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009264}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009265
Douglas Gregor39da0b82009-09-09 23:08:42 +00009266/// \brief Given a constructor and the set of arguments provided for the
9267/// constructor, convert the arguments and add any required default arguments
9268/// to form a proper call to this constructor.
9269///
9270/// \returns true if an error occurred, false otherwise.
9271bool
9272Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9273 MultiExprArg ArgsPtr,
9274 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009275 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009276 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9277 unsigned NumArgs = ArgsPtr.size();
9278 Expr **Args = (Expr **)ArgsPtr.get();
9279
9280 const FunctionProtoType *Proto
9281 = Constructor->getType()->getAs<FunctionProtoType>();
9282 assert(Proto && "Constructor without a prototype?");
9283 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009284
9285 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009286 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009287 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009288 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009289 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009290
9291 VariadicCallType CallType =
9292 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009293 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009294 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9295 Proto, 0, Args, NumArgs, AllArgs,
9296 CallType);
9297 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9298 ConvertedArgs.push_back(AllArgs[i]);
9299 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009300}
9301
Anders Carlsson20d45d22009-12-12 00:32:00 +00009302static inline bool
9303CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9304 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009305 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009306 if (isa<NamespaceDecl>(DC)) {
9307 return SemaRef.Diag(FnDecl->getLocation(),
9308 diag::err_operator_new_delete_declared_in_namespace)
9309 << FnDecl->getDeclName();
9310 }
9311
9312 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009313 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009314 return SemaRef.Diag(FnDecl->getLocation(),
9315 diag::err_operator_new_delete_declared_static)
9316 << FnDecl->getDeclName();
9317 }
9318
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009319 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009320}
9321
Anders Carlsson156c78e2009-12-13 17:53:43 +00009322static inline bool
9323CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9324 CanQualType ExpectedResultType,
9325 CanQualType ExpectedFirstParamType,
9326 unsigned DependentParamTypeDiag,
9327 unsigned InvalidParamTypeDiag) {
9328 QualType ResultType =
9329 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9330
9331 // Check that the result type is not dependent.
9332 if (ResultType->isDependentType())
9333 return SemaRef.Diag(FnDecl->getLocation(),
9334 diag::err_operator_new_delete_dependent_result_type)
9335 << FnDecl->getDeclName() << ExpectedResultType;
9336
9337 // Check that the result type is what we expect.
9338 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9339 return SemaRef.Diag(FnDecl->getLocation(),
9340 diag::err_operator_new_delete_invalid_result_type)
9341 << FnDecl->getDeclName() << ExpectedResultType;
9342
9343 // A function template must have at least 2 parameters.
9344 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9345 return SemaRef.Diag(FnDecl->getLocation(),
9346 diag::err_operator_new_delete_template_too_few_parameters)
9347 << FnDecl->getDeclName();
9348
9349 // The function decl must have at least 1 parameter.
9350 if (FnDecl->getNumParams() == 0)
9351 return SemaRef.Diag(FnDecl->getLocation(),
9352 diag::err_operator_new_delete_too_few_parameters)
9353 << FnDecl->getDeclName();
9354
9355 // Check the the first parameter type is not dependent.
9356 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9357 if (FirstParamType->isDependentType())
9358 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9359 << FnDecl->getDeclName() << ExpectedFirstParamType;
9360
9361 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009362 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009363 ExpectedFirstParamType)
9364 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9365 << FnDecl->getDeclName() << ExpectedFirstParamType;
9366
9367 return false;
9368}
9369
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009370static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009371CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009372 // C++ [basic.stc.dynamic.allocation]p1:
9373 // A program is ill-formed if an allocation function is declared in a
9374 // namespace scope other than global scope or declared static in global
9375 // scope.
9376 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9377 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009378
9379 CanQualType SizeTy =
9380 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9381
9382 // C++ [basic.stc.dynamic.allocation]p1:
9383 // The return type shall be void*. The first parameter shall have type
9384 // std::size_t.
9385 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9386 SizeTy,
9387 diag::err_operator_new_dependent_param_type,
9388 diag::err_operator_new_param_type))
9389 return true;
9390
9391 // C++ [basic.stc.dynamic.allocation]p1:
9392 // The first parameter shall not have an associated default argument.
9393 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009394 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009395 diag::err_operator_new_default_arg)
9396 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9397
9398 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009399}
9400
9401static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009402CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9403 // C++ [basic.stc.dynamic.deallocation]p1:
9404 // A program is ill-formed if deallocation functions are declared in a
9405 // namespace scope other than global scope or declared static in global
9406 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009407 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9408 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009409
9410 // C++ [basic.stc.dynamic.deallocation]p2:
9411 // Each deallocation function shall return void and its first parameter
9412 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009413 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9414 SemaRef.Context.VoidPtrTy,
9415 diag::err_operator_delete_dependent_param_type,
9416 diag::err_operator_delete_param_type))
9417 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009418
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009419 return false;
9420}
9421
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009422/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9423/// of this overloaded operator is well-formed. If so, returns false;
9424/// otherwise, emits appropriate diagnostics and returns true.
9425bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009426 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009427 "Expected an overloaded operator declaration");
9428
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009429 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9430
Mike Stump1eb44332009-09-09 15:08:12 +00009431 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009432 // The allocation and deallocation functions, operator new,
9433 // operator new[], operator delete and operator delete[], are
9434 // described completely in 3.7.3. The attributes and restrictions
9435 // found in the rest of this subclause do not apply to them unless
9436 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009437 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009438 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009439
Anders Carlssona3ccda52009-12-12 00:26:23 +00009440 if (Op == OO_New || Op == OO_Array_New)
9441 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009442
9443 // C++ [over.oper]p6:
9444 // An operator function shall either be a non-static member
9445 // function or be a non-member function and have at least one
9446 // parameter whose type is a class, a reference to a class, an
9447 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009448 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9449 if (MethodDecl->isStatic())
9450 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009451 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009452 } else {
9453 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009454 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9455 ParamEnd = FnDecl->param_end();
9456 Param != ParamEnd; ++Param) {
9457 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009458 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9459 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009460 ClassOrEnumParam = true;
9461 break;
9462 }
9463 }
9464
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009465 if (!ClassOrEnumParam)
9466 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009467 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009468 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009469 }
9470
9471 // C++ [over.oper]p8:
9472 // An operator function cannot have default arguments (8.3.6),
9473 // except where explicitly stated below.
9474 //
Mike Stump1eb44332009-09-09 15:08:12 +00009475 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009476 // (C++ [over.call]p1).
9477 if (Op != OO_Call) {
9478 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9479 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009480 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009481 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009482 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009483 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009484 }
9485 }
9486
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009487 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9488 { false, false, false }
9489#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9490 , { Unary, Binary, MemberOnly }
9491#include "clang/Basic/OperatorKinds.def"
9492 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009493
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009494 bool CanBeUnaryOperator = OperatorUses[Op][0];
9495 bool CanBeBinaryOperator = OperatorUses[Op][1];
9496 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009497
9498 // C++ [over.oper]p8:
9499 // [...] Operator functions cannot have more or fewer parameters
9500 // than the number required for the corresponding operator, as
9501 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009502 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009503 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009504 if (Op != OO_Call &&
9505 ((NumParams == 1 && !CanBeUnaryOperator) ||
9506 (NumParams == 2 && !CanBeBinaryOperator) ||
9507 (NumParams < 1) || (NumParams > 2))) {
9508 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009509 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009510 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009511 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009512 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009513 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009514 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009515 assert(CanBeBinaryOperator &&
9516 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009517 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009518 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009519
Chris Lattner416e46f2008-11-21 07:57:12 +00009520 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009521 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009522 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009523
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009524 // Overloaded operators other than operator() cannot be variadic.
9525 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009526 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009527 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009528 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009529 }
9530
9531 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009532 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9533 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009534 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009535 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009536 }
9537
9538 // C++ [over.inc]p1:
9539 // The user-defined function called operator++ implements the
9540 // prefix and postfix ++ operator. If this function is a member
9541 // function with no parameters, or a non-member function with one
9542 // parameter of class or enumeration type, it defines the prefix
9543 // increment operator ++ for objects of that type. If the function
9544 // is a member function with one parameter (which shall be of type
9545 // int) or a non-member function with two parameters (the second
9546 // of which shall be of type int), it defines the postfix
9547 // increment operator ++ for objects of that type.
9548 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9549 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9550 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009551 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009552 ParamIsInt = BT->getKind() == BuiltinType::Int;
9553
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009554 if (!ParamIsInt)
9555 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009556 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009557 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009558 }
9559
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009560 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009561}
Chris Lattner5a003a42008-12-17 07:09:26 +00009562
Sean Hunta6c058d2010-01-13 09:01:02 +00009563/// CheckLiteralOperatorDeclaration - Check whether the declaration
9564/// of this literal operator function is well-formed. If so, returns
9565/// false; otherwise, emits appropriate diagnostics and returns true.
9566bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9567 DeclContext *DC = FnDecl->getDeclContext();
9568 Decl::Kind Kind = DC->getDeclKind();
9569 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9570 Kind != Decl::LinkageSpec) {
9571 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9572 << FnDecl->getDeclName();
9573 return true;
9574 }
9575
9576 bool Valid = false;
9577
Sean Hunt216c2782010-04-07 23:11:06 +00009578 // template <char...> type operator "" name() is the only valid template
9579 // signature, and the only valid signature with no parameters.
9580 if (FnDecl->param_size() == 0) {
9581 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9582 // Must have only one template parameter
9583 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9584 if (Params->size() == 1) {
9585 NonTypeTemplateParmDecl *PmDecl =
9586 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009587
Sean Hunt216c2782010-04-07 23:11:06 +00009588 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009589 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9590 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9591 Valid = true;
9592 }
9593 }
9594 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009595 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009596 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9597
Sean Hunta6c058d2010-01-13 09:01:02 +00009598 QualType T = (*Param)->getType();
9599
Sean Hunt30019c02010-04-07 22:57:35 +00009600 // unsigned long long int, long double, and any character type are allowed
9601 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009602 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9603 Context.hasSameType(T, Context.LongDoubleTy) ||
9604 Context.hasSameType(T, Context.CharTy) ||
9605 Context.hasSameType(T, Context.WCharTy) ||
9606 Context.hasSameType(T, Context.Char16Ty) ||
9607 Context.hasSameType(T, Context.Char32Ty)) {
9608 if (++Param == FnDecl->param_end())
9609 Valid = true;
9610 goto FinishedParams;
9611 }
9612
Sean Hunt30019c02010-04-07 22:57:35 +00009613 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009614 const PointerType *PT = T->getAs<PointerType>();
9615 if (!PT)
9616 goto FinishedParams;
9617 T = PT->getPointeeType();
9618 if (!T.isConstQualified())
9619 goto FinishedParams;
9620 T = T.getUnqualifiedType();
9621
9622 // Move on to the second parameter;
9623 ++Param;
9624
9625 // If there is no second parameter, the first must be a const char *
9626 if (Param == FnDecl->param_end()) {
9627 if (Context.hasSameType(T, Context.CharTy))
9628 Valid = true;
9629 goto FinishedParams;
9630 }
9631
9632 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9633 // are allowed as the first parameter to a two-parameter function
9634 if (!(Context.hasSameType(T, Context.CharTy) ||
9635 Context.hasSameType(T, Context.WCharTy) ||
9636 Context.hasSameType(T, Context.Char16Ty) ||
9637 Context.hasSameType(T, Context.Char32Ty)))
9638 goto FinishedParams;
9639
9640 // The second and final parameter must be an std::size_t
9641 T = (*Param)->getType().getUnqualifiedType();
9642 if (Context.hasSameType(T, Context.getSizeType()) &&
9643 ++Param == FnDecl->param_end())
9644 Valid = true;
9645 }
9646
9647 // FIXME: This diagnostic is absolutely terrible.
9648FinishedParams:
9649 if (!Valid) {
9650 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9651 << FnDecl->getDeclName();
9652 return true;
9653 }
9654
Douglas Gregor1155c422011-08-30 22:40:35 +00009655 StringRef LiteralName
9656 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9657 if (LiteralName[0] != '_') {
9658 // C++0x [usrlit.suffix]p1:
9659 // Literal suffix identifiers that do not start with an underscore are
9660 // reserved for future standardization.
9661 bool IsHexFloat = true;
9662 if (LiteralName.size() > 1 &&
9663 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9664 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9665 if (!isdigit(LiteralName[I])) {
9666 IsHexFloat = false;
9667 break;
9668 }
9669 }
9670 }
9671
9672 if (IsHexFloat)
9673 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9674 << LiteralName;
9675 else
9676 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9677 }
9678
Sean Hunta6c058d2010-01-13 09:01:02 +00009679 return false;
9680}
9681
Douglas Gregor074149e2009-01-05 19:45:36 +00009682/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9683/// linkage specification, including the language and (if present)
9684/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9685/// the location of the language string literal, which is provided
9686/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9687/// the '{' brace. Otherwise, this linkage specification does not
9688/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009689Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9690 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009691 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009692 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009693 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009694 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009695 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009696 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009697 Language = LinkageSpecDecl::lang_cxx;
9698 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009699 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009700 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009701 }
Mike Stump1eb44332009-09-09 15:08:12 +00009702
Chris Lattnercc98eac2008-12-17 07:13:27 +00009703 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009704
Douglas Gregor074149e2009-01-05 19:45:36 +00009705 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009706 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009707 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009708 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009709 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009710}
9711
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009712/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009713/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9714/// valid, it's the position of the closing '}' brace in a linkage
9715/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009716Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009717 Decl *LinkageSpec,
9718 SourceLocation RBraceLoc) {
9719 if (LinkageSpec) {
9720 if (RBraceLoc.isValid()) {
9721 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9722 LSDecl->setRBraceLoc(RBraceLoc);
9723 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009724 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009725 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009726 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009727}
9728
Douglas Gregord308e622009-05-18 20:51:54 +00009729/// \brief Perform semantic analysis for the variable declaration that
9730/// occurs within a C++ catch clause, returning the newly-created
9731/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009732VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009733 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009734 SourceLocation StartLoc,
9735 SourceLocation Loc,
9736 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009737 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009738 QualType ExDeclType = TInfo->getType();
9739
Sebastian Redl4b07b292008-12-22 19:15:10 +00009740 // Arrays and functions decay.
9741 if (ExDeclType->isArrayType())
9742 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9743 else if (ExDeclType->isFunctionType())
9744 ExDeclType = Context.getPointerType(ExDeclType);
9745
9746 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9747 // The exception-declaration shall not denote a pointer or reference to an
9748 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009749 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009750 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009751 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009752 Invalid = true;
9753 }
Douglas Gregord308e622009-05-18 20:51:54 +00009754
Sebastian Redl4b07b292008-12-22 19:15:10 +00009755 QualType BaseType = ExDeclType;
9756 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009757 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009758 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009759 BaseType = Ptr->getPointeeType();
9760 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009761 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009762 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009763 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009764 BaseType = Ref->getPointeeType();
9765 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009766 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009767 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009768 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009769 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009770 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009771
Mike Stump1eb44332009-09-09 15:08:12 +00009772 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009773 RequireNonAbstractType(Loc, ExDeclType,
9774 diag::err_abstract_type_in_decl,
9775 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009776 Invalid = true;
9777
John McCall5a180392010-07-24 00:37:23 +00009778 // Only the non-fragile NeXT runtime currently supports C++ catches
9779 // of ObjC types, and no runtime supports catching ObjC types by value.
9780 if (!Invalid && getLangOptions().ObjC1) {
9781 QualType T = ExDeclType;
9782 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9783 T = RT->getPointeeType();
9784
9785 if (T->isObjCObjectType()) {
9786 Diag(Loc, diag::err_objc_object_catch);
9787 Invalid = true;
9788 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009789 if (!getLangOptions().ObjCNonFragileABI)
9790 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009791 }
9792 }
9793
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009794 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9795 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009796 ExDecl->setExceptionVariable(true);
9797
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009798 // In ARC, infer 'retaining' for variables of retainable type.
9799 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9800 Invalid = true;
9801
Douglas Gregorc41b8782011-07-06 18:14:43 +00009802 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009803 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009804 // C++ [except.handle]p16:
9805 // The object declared in an exception-declaration or, if the
9806 // exception-declaration does not specify a name, a temporary (12.2) is
9807 // copy-initialized (8.5) from the exception object. [...]
9808 // The object is destroyed when the handler exits, after the destruction
9809 // of any automatic objects initialized within the handler.
9810 //
9811 // We just pretend to initialize the object with itself, then make sure
9812 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009813 QualType initType = ExDeclType;
9814
9815 InitializedEntity entity =
9816 InitializedEntity::InitializeVariable(ExDecl);
9817 InitializationKind initKind =
9818 InitializationKind::CreateCopy(Loc, SourceLocation());
9819
9820 Expr *opaqueValue =
9821 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9822 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9823 ExprResult result = sequence.Perform(*this, entity, initKind,
9824 MultiExprArg(&opaqueValue, 1));
9825 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009826 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009827 else {
9828 // If the constructor used was non-trivial, set this as the
9829 // "initializer".
9830 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9831 if (!construct->getConstructor()->isTrivial()) {
9832 Expr *init = MaybeCreateExprWithCleanups(construct);
9833 ExDecl->setInit(init);
9834 }
9835
9836 // And make sure it's destructable.
9837 FinalizeVarWithDestructor(ExDecl, recordType);
9838 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009839 }
9840 }
9841
Douglas Gregord308e622009-05-18 20:51:54 +00009842 if (Invalid)
9843 ExDecl->setInvalidDecl();
9844
9845 return ExDecl;
9846}
9847
9848/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9849/// handler.
John McCalld226f652010-08-21 09:40:31 +00009850Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009852 bool Invalid = D.isInvalidType();
9853
9854 // Check for unexpanded parameter packs.
9855 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9856 UPPC_ExceptionType)) {
9857 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9858 D.getIdentifierLoc());
9859 Invalid = true;
9860 }
9861
Sebastian Redl4b07b292008-12-22 19:15:10 +00009862 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009863 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009864 LookupOrdinaryName,
9865 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009866 // The scope should be freshly made just for us. There is just no way
9867 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009868 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009869 if (PrevDecl->isTemplateParameter()) {
9870 // Maybe we will complain about the shadowed template parameter.
9871 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009872 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009873 }
9874 }
9875
Chris Lattnereaaebc72009-04-25 08:06:05 +00009876 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009877 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9878 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009879 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009880 }
9881
Douglas Gregor83cb9422010-09-09 17:09:21 +00009882 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009883 D.getSourceRange().getBegin(),
9884 D.getIdentifierLoc(),
9885 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009886 if (Invalid)
9887 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009888
Sebastian Redl4b07b292008-12-22 19:15:10 +00009889 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009890 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009891 PushOnScopeChains(ExDecl, S);
9892 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009893 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009894
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009895 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009896 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009897}
Anders Carlssonfb311762009-03-14 00:25:26 +00009898
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009899Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009900 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009901 Expr *AssertMessageExpr_,
9902 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009903 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009904
Anders Carlssonc3082412009-03-14 00:33:21 +00009905 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smithdaaefc52011-12-14 23:32:26 +00009906 llvm::APSInt Cond;
9907 if (VerifyIntegerConstantExpression(AssertExpr, &Cond,
9908 diag::err_static_assert_expression_is_not_constant,
9909 /*AllowFold=*/false))
John McCalld226f652010-08-21 09:40:31 +00009910 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009911
Richard Smithdaaefc52011-12-14 23:32:26 +00009912 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009913 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009914 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009915 }
Mike Stump1eb44332009-09-09 15:08:12 +00009916
Douglas Gregor399ad972010-12-15 23:55:21 +00009917 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9918 return 0;
9919
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009920 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9921 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009922
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009923 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009924 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009925}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009926
Douglas Gregor1d869352010-04-07 16:53:43 +00009927/// \brief Perform semantic analysis of the given friend type declaration.
9928///
9929/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009930FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9931 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009932 TypeSourceInfo *TSInfo) {
9933 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9934
9935 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009936 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009937
Richard Smith6b130222011-10-18 21:39:00 +00009938 // C++03 [class.friend]p2:
9939 // An elaborated-type-specifier shall be used in a friend declaration
9940 // for a class.*
9941 //
9942 // * The class-key of the elaborated-type-specifier is required.
9943 if (!ActiveTemplateInstantiations.empty()) {
9944 // Do not complain about the form of friend template types during
9945 // template instantiation; we will already have complained when the
9946 // template was declared.
9947 } else if (!T->isElaboratedTypeSpecifier()) {
9948 // If we evaluated the type to a record type, suggest putting
9949 // a tag in front.
9950 if (const RecordType *RT = T->getAs<RecordType>()) {
9951 RecordDecl *RD = RT->getDecl();
9952
9953 std::string InsertionText = std::string(" ") + RD->getKindName();
9954
9955 Diag(TypeRange.getBegin(),
9956 getLangOptions().CPlusPlus0x ?
9957 diag::warn_cxx98_compat_unelaborated_friend_type :
9958 diag::ext_unelaborated_friend_type)
9959 << (unsigned) RD->getTagKind()
9960 << T
9961 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9962 InsertionText);
9963 } else {
9964 Diag(FriendLoc,
9965 getLangOptions().CPlusPlus0x ?
9966 diag::warn_cxx98_compat_nonclass_type_friend :
9967 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009968 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009969 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009970 }
Richard Smith6b130222011-10-18 21:39:00 +00009971 } else if (T->getAs<EnumType>()) {
9972 Diag(FriendLoc,
9973 getLangOptions().CPlusPlus0x ?
9974 diag::warn_cxx98_compat_enum_friend :
9975 diag::ext_enum_friend)
9976 << T
9977 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009978 }
9979
Douglas Gregor06245bf2010-04-07 17:57:12 +00009980 // C++0x [class.friend]p3:
9981 // If the type specifier in a friend declaration designates a (possibly
9982 // cv-qualified) class type, that class is declared as a friend; otherwise,
9983 // the friend declaration is ignored.
9984
9985 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9986 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009987
Abramo Bagnara0216df82011-10-29 20:52:52 +00009988 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009989}
9990
John McCall9a34edb2010-10-19 01:40:49 +00009991/// Handle a friend tag declaration where the scope specifier was
9992/// templated.
9993Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9994 unsigned TagSpec, SourceLocation TagLoc,
9995 CXXScopeSpec &SS,
9996 IdentifierInfo *Name, SourceLocation NameLoc,
9997 AttributeList *Attr,
9998 MultiTemplateParamsArg TempParamLists) {
9999 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10000
10001 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010002 bool Invalid = false;
10003
10004 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010005 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +000010006 TempParamLists.get(),
10007 TempParamLists.size(),
10008 /*friend*/ true,
10009 isExplicitSpecialization,
10010 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010011 if (TemplateParams->size() > 0) {
10012 // This is a declaration of a class template.
10013 if (Invalid)
10014 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010015
Eric Christopher4110e132011-07-21 05:34:24 +000010016 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10017 SS, Name, NameLoc, Attr,
10018 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010019 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010020 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010021 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010022 } else {
10023 // The "template<>" header is extraneous.
10024 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10025 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10026 isExplicitSpecialization = true;
10027 }
10028 }
10029
10030 if (Invalid) return 0;
10031
John McCall9a34edb2010-10-19 01:40:49 +000010032 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010033 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +000010034 if (TempParamLists.get()[I]->size()) {
10035 isAllExplicitSpecializations = false;
10036 break;
10037 }
10038 }
10039
10040 // FIXME: don't ignore attributes.
10041
10042 // If it's explicit specializations all the way down, just forget
10043 // about the template header and build an appropriate non-templated
10044 // friend. TODO: for source fidelity, remember the headers.
10045 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010046 if (SS.isEmpty()) {
10047 bool Owned = false;
10048 bool IsDependent = false;
10049 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10050 Attr, AS_public,
10051 /*ModulePrivateLoc=*/SourceLocation(),
10052 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010053 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010054 /*ScopedEnumUsesClassTag=*/false,
10055 /*UnderlyingType=*/TypeResult());
10056 }
10057
Douglas Gregor2494dd02011-03-01 01:34:45 +000010058 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010059 ElaboratedTypeKeyword Keyword
10060 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010061 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010062 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010063 if (T.isNull())
10064 return 0;
10065
10066 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10067 if (isa<DependentNameType>(T)) {
10068 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10069 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010070 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010071 TL.setNameLoc(NameLoc);
10072 } else {
10073 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
10074 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010075 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010076 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10077 }
10078
10079 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10080 TSI, FriendLoc);
10081 Friend->setAccess(AS_public);
10082 CurContext->addDecl(Friend);
10083 return Friend;
10084 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010085
10086 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10087
10088
John McCall9a34edb2010-10-19 01:40:49 +000010089
10090 // Handle the case of a templated-scope friend class. e.g.
10091 // template <class T> class A<T>::B;
10092 // FIXME: we don't support these right now.
10093 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10094 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10095 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10096 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10097 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010098 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010099 TL.setNameLoc(NameLoc);
10100
10101 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10102 TSI, FriendLoc);
10103 Friend->setAccess(AS_public);
10104 Friend->setUnsupportedFriend(true);
10105 CurContext->addDecl(Friend);
10106 return Friend;
10107}
10108
10109
John McCalldd4a3b02009-09-16 22:47:08 +000010110/// Handle a friend type declaration. This works in tandem with
10111/// ActOnTag.
10112///
10113/// Notes on friend class templates:
10114///
10115/// We generally treat friend class declarations as if they were
10116/// declaring a class. So, for example, the elaborated type specifier
10117/// in a friend declaration is required to obey the restrictions of a
10118/// class-head (i.e. no typedefs in the scope chain), template
10119/// parameters are required to match up with simple template-ids, &c.
10120/// However, unlike when declaring a template specialization, it's
10121/// okay to refer to a template specialization without an empty
10122/// template parameter declaration, e.g.
10123/// friend class A<T>::B<unsigned>;
10124/// We permit this as a special case; if there are any template
10125/// parameters present at all, require proper matching, i.e.
10126/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010127Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010128 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010129 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010130
10131 assert(DS.isFriendSpecified());
10132 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10133
John McCalldd4a3b02009-09-16 22:47:08 +000010134 // Try to convert the decl specifier to a type. This works for
10135 // friend templates because ActOnTag never produces a ClassTemplateDecl
10136 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010137 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010138 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10139 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010140 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010141 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010142
Douglas Gregor6ccab972010-12-16 01:14:37 +000010143 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10144 return 0;
10145
John McCalldd4a3b02009-09-16 22:47:08 +000010146 // This is definitely an error in C++98. It's probably meant to
10147 // be forbidden in C++0x, too, but the specification is just
10148 // poorly written.
10149 //
10150 // The problem is with declarations like the following:
10151 // template <T> friend A<T>::foo;
10152 // where deciding whether a class C is a friend or not now hinges
10153 // on whether there exists an instantiation of A that causes
10154 // 'foo' to equal C. There are restrictions on class-heads
10155 // (which we declare (by fiat) elaborated friend declarations to
10156 // be) that makes this tractable.
10157 //
10158 // FIXME: handle "template <> friend class A<T>;", which
10159 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010160 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010161 Diag(Loc, diag::err_tagless_friend_type_template)
10162 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010163 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010164 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010165
John McCall02cace72009-08-28 07:59:38 +000010166 // C++98 [class.friend]p1: A friend of a class is a function
10167 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010168 // This is fixed in DR77, which just barely didn't make the C++03
10169 // deadline. It's also a very silly restriction that seriously
10170 // affects inner classes and which nobody else seems to implement;
10171 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010172 //
10173 // But note that we could warn about it: it's always useless to
10174 // friend one of your own members (it's not, however, worthless to
10175 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010176
John McCalldd4a3b02009-09-16 22:47:08 +000010177 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010178 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010179 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010180 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010181 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010182 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010183 DS.getFriendSpecLoc());
10184 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010185 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010186
10187 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010188 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010189
John McCalldd4a3b02009-09-16 22:47:08 +000010190 D->setAccess(AS_public);
10191 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010192
John McCalld226f652010-08-21 09:40:31 +000010193 return D;
John McCall02cace72009-08-28 07:59:38 +000010194}
10195
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010196Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010197 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010198 const DeclSpec &DS = D.getDeclSpec();
10199
10200 assert(DS.isFriendSpecified());
10201 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10202
10203 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010204 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010205
10206 // C++ [class.friend]p1
10207 // A friend of a class is a function or class....
10208 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010209 // It *doesn't* see through dependent types, which is correct
10210 // according to [temp.arg.type]p3:
10211 // If a declaration acquires a function type through a
10212 // type dependent on a template-parameter and this causes
10213 // a declaration that does not use the syntactic form of a
10214 // function declarator to have a function type, the program
10215 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010216 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010217 Diag(Loc, diag::err_unexpected_friend);
10218
10219 // It might be worthwhile to try to recover by creating an
10220 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010221 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010222 }
10223
10224 // C++ [namespace.memdef]p3
10225 // - If a friend declaration in a non-local class first declares a
10226 // class or function, the friend class or function is a member
10227 // of the innermost enclosing namespace.
10228 // - The name of the friend is not found by simple name lookup
10229 // until a matching declaration is provided in that namespace
10230 // scope (either before or after the class declaration granting
10231 // friendship).
10232 // - If a friend function is called, its name may be found by the
10233 // name lookup that considers functions from namespaces and
10234 // classes associated with the types of the function arguments.
10235 // - When looking for a prior declaration of a class or a function
10236 // declared as a friend, scopes outside the innermost enclosing
10237 // namespace scope are not considered.
10238
John McCall337ec3d2010-10-12 23:13:28 +000010239 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010240 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10241 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010242 assert(Name);
10243
Douglas Gregor6ccab972010-12-16 01:14:37 +000010244 // Check for unexpanded parameter packs.
10245 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10246 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10247 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10248 return 0;
10249
John McCall67d1a672009-08-06 02:15:43 +000010250 // The context we found the declaration in, or in which we should
10251 // create the declaration.
10252 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010253 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010254 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010255 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010256
John McCall337ec3d2010-10-12 23:13:28 +000010257 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010258
John McCall337ec3d2010-10-12 23:13:28 +000010259 // There are four cases here.
10260 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010261 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010262 // there as appropriate.
10263 // Recover from invalid scope qualifiers as if they just weren't there.
10264 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010265 // C++0x [namespace.memdef]p3:
10266 // If the name in a friend declaration is neither qualified nor
10267 // a template-id and the declaration is a function or an
10268 // elaborated-type-specifier, the lookup to determine whether
10269 // the entity has been previously declared shall not consider
10270 // any scopes outside the innermost enclosing namespace.
10271 // C++0x [class.friend]p11:
10272 // If a friend declaration appears in a local class and the name
10273 // specified is an unqualified name, a prior declaration is
10274 // looked up without considering scopes that are outside the
10275 // innermost enclosing non-class scope. For a friend function
10276 // declaration, if there is no prior declaration, the program is
10277 // ill-formed.
10278 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010279 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010280
John McCall29ae6e52010-10-13 05:45:15 +000010281 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010282 DC = CurContext;
10283 while (true) {
10284 // Skip class contexts. If someone can cite chapter and verse
10285 // for this behavior, that would be nice --- it's what GCC and
10286 // EDG do, and it seems like a reasonable intent, but the spec
10287 // really only says that checks for unqualified existing
10288 // declarations should stop at the nearest enclosing namespace,
10289 // not that they should only consider the nearest enclosing
10290 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010291 while (DC->isRecord())
10292 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010293
John McCall68263142009-11-18 22:49:29 +000010294 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010295
10296 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010297 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010298 break;
John McCall29ae6e52010-10-13 05:45:15 +000010299
John McCall8a407372010-10-14 22:22:28 +000010300 if (isTemplateId) {
10301 if (isa<TranslationUnitDecl>(DC)) break;
10302 } else {
10303 if (DC->isFileContext()) break;
10304 }
John McCall67d1a672009-08-06 02:15:43 +000010305 DC = DC->getParent();
10306 }
10307
10308 // C++ [class.friend]p1: A friend of a class is a function or
10309 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010310 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010311 // Most C++ 98 compilers do seem to give an error here, so
10312 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010313 if (!Previous.empty() && DC->Equals(CurContext))
10314 Diag(DS.getFriendSpecLoc(),
10315 getLangOptions().CPlusPlus0x ?
10316 diag::warn_cxx98_compat_friend_is_member :
10317 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010318
John McCall380aaa42010-10-13 06:22:15 +000010319 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010320
Douglas Gregor883af832011-10-10 01:11:59 +000010321 // C++ [class.friend]p6:
10322 // A function can be defined in a friend declaration of a class if and
10323 // only if the class is a non-local class (9.8), the function name is
10324 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010325 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010326 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10327 }
10328
John McCall337ec3d2010-10-12 23:13:28 +000010329 // - There's a non-dependent scope specifier, in which case we
10330 // compute it and do a previous lookup there for a function
10331 // or function template.
10332 } else if (!SS.getScopeRep()->isDependent()) {
10333 DC = computeDeclContext(SS);
10334 if (!DC) return 0;
10335
10336 if (RequireCompleteDeclContext(SS, DC)) return 0;
10337
10338 LookupQualifiedName(Previous, DC);
10339
10340 // Ignore things found implicitly in the wrong scope.
10341 // TODO: better diagnostics for this case. Suggesting the right
10342 // qualified scope would be nice...
10343 LookupResult::Filter F = Previous.makeFilter();
10344 while (F.hasNext()) {
10345 NamedDecl *D = F.next();
10346 if (!DC->InEnclosingNamespaceSetOf(
10347 D->getDeclContext()->getRedeclContext()))
10348 F.erase();
10349 }
10350 F.done();
10351
10352 if (Previous.empty()) {
10353 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010354 Diag(Loc, diag::err_qualified_friend_not_found)
10355 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010356 return 0;
10357 }
10358
10359 // C++ [class.friend]p1: A friend of a class is a function or
10360 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010361 if (DC->Equals(CurContext))
10362 Diag(DS.getFriendSpecLoc(),
10363 getLangOptions().CPlusPlus0x ?
10364 diag::warn_cxx98_compat_friend_is_member :
10365 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010366
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010367 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010368 // C++ [class.friend]p6:
10369 // A function can be defined in a friend declaration of a class if and
10370 // only if the class is a non-local class (9.8), the function name is
10371 // unqualified, and the function has namespace scope.
10372 SemaDiagnosticBuilder DB
10373 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10374
10375 DB << SS.getScopeRep();
10376 if (DC->isFileContext())
10377 DB << FixItHint::CreateRemoval(SS.getRange());
10378 SS.clear();
10379 }
John McCall337ec3d2010-10-12 23:13:28 +000010380
10381 // - There's a scope specifier that does not match any template
10382 // parameter lists, in which case we use some arbitrary context,
10383 // create a method or method template, and wait for instantiation.
10384 // - There's a scope specifier that does match some template
10385 // parameter lists, which we don't handle right now.
10386 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010387 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010388 // C++ [class.friend]p6:
10389 // A function can be defined in a friend declaration of a class if and
10390 // only if the class is a non-local class (9.8), the function name is
10391 // unqualified, and the function has namespace scope.
10392 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10393 << SS.getScopeRep();
10394 }
10395
John McCall337ec3d2010-10-12 23:13:28 +000010396 DC = CurContext;
10397 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010398 }
Douglas Gregor883af832011-10-10 01:11:59 +000010399
John McCall29ae6e52010-10-13 05:45:15 +000010400 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010401 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010402 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10403 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10404 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010405 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010406 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10407 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010408 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010409 }
John McCall67d1a672009-08-06 02:15:43 +000010410 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010411
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010412 // FIXME: This is an egregious hack to cope with cases where the scope stack
10413 // does not contain the declaration context, i.e., in an out-of-line
10414 // definition of a class.
10415 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10416 if (!DCScope) {
10417 FakeDCScope.setEntity(DC);
10418 DCScope = &FakeDCScope;
10419 }
10420
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010421 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010422 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10423 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010424 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010425
Douglas Gregor182ddf02009-09-28 00:08:27 +000010426 assert(ND->getDeclContext() == DC);
10427 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010428
John McCallab88d972009-08-31 22:39:49 +000010429 // Add the function declaration to the appropriate lookup tables,
10430 // adjusting the redeclarations list as necessary. We don't
10431 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010432 //
John McCallab88d972009-08-31 22:39:49 +000010433 // Also update the scope-based lookup if the target context's
10434 // lookup context is in lexical scope.
10435 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010436 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010437 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010438 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010439 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010440 }
John McCall02cace72009-08-28 07:59:38 +000010441
10442 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010443 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010444 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010445 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010446 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010447
John McCall337ec3d2010-10-12 23:13:28 +000010448 if (ND->isInvalidDecl())
10449 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010450 else {
10451 FunctionDecl *FD;
10452 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10453 FD = FTD->getTemplatedDecl();
10454 else
10455 FD = cast<FunctionDecl>(ND);
10456
10457 // Mark templated-scope function declarations as unsupported.
10458 if (FD->getNumTemplateParameterLists())
10459 FrD->setUnsupportedFriend(true);
10460 }
John McCall337ec3d2010-10-12 23:13:28 +000010461
John McCalld226f652010-08-21 09:40:31 +000010462 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010463}
10464
John McCalld226f652010-08-21 09:40:31 +000010465void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10466 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010467
Sebastian Redl50de12f2009-03-24 22:27:57 +000010468 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10469 if (!Fn) {
10470 Diag(DelLoc, diag::err_deleted_non_function);
10471 return;
10472 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010473 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010474 Diag(DelLoc, diag::err_deleted_decl_not_first);
10475 Diag(Prev->getLocation(), diag::note_previous_declaration);
10476 // If the declaration wasn't the first, we delete the function anyway for
10477 // recovery.
10478 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010479 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010480}
Sebastian Redl13e88542009-04-27 21:33:24 +000010481
Sean Hunte4246a62011-05-12 06:15:49 +000010482void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10483 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10484
10485 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010486 if (MD->getParent()->isDependentType()) {
10487 MD->setDefaulted();
10488 MD->setExplicitlyDefaulted();
10489 return;
10490 }
10491
Sean Hunte4246a62011-05-12 06:15:49 +000010492 CXXSpecialMember Member = getSpecialMember(MD);
10493 if (Member == CXXInvalid) {
10494 Diag(DefaultLoc, diag::err_default_special_members);
10495 return;
10496 }
10497
10498 MD->setDefaulted();
10499 MD->setExplicitlyDefaulted();
10500
Sean Huntcd10dec2011-05-23 23:14:04 +000010501 // If this definition appears within the record, do the checking when
10502 // the record is complete.
10503 const FunctionDecl *Primary = MD;
10504 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10505 // Find the uninstantiated declaration that actually had the '= default'
10506 // on it.
10507 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10508
10509 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010510 return;
10511
10512 switch (Member) {
10513 case CXXDefaultConstructor: {
10514 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10515 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010516 if (!CD->isInvalidDecl())
10517 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10518 break;
10519 }
10520
10521 case CXXCopyConstructor: {
10522 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10523 CheckExplicitlyDefaultedCopyConstructor(CD);
10524 if (!CD->isInvalidDecl())
10525 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010526 break;
10527 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010528
Sean Hunt2b188082011-05-14 05:23:28 +000010529 case CXXCopyAssignment: {
10530 CheckExplicitlyDefaultedCopyAssignment(MD);
10531 if (!MD->isInvalidDecl())
10532 DefineImplicitCopyAssignment(DefaultLoc, MD);
10533 break;
10534 }
10535
Sean Huntcb45a0f2011-05-12 22:46:25 +000010536 case CXXDestructor: {
10537 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10538 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010539 if (!DD->isInvalidDecl())
10540 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010541 break;
10542 }
10543
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010544 case CXXMoveConstructor: {
10545 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10546 CheckExplicitlyDefaultedMoveConstructor(CD);
10547 if (!CD->isInvalidDecl())
10548 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010549 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010550 }
Sean Hunt82713172011-05-25 23:16:36 +000010551
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010552 case CXXMoveAssignment: {
10553 CheckExplicitlyDefaultedMoveAssignment(MD);
10554 if (!MD->isInvalidDecl())
10555 DefineImplicitMoveAssignment(DefaultLoc, MD);
10556 break;
10557 }
10558
10559 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010560 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010561 }
10562 } else {
10563 Diag(DefaultLoc, diag::err_default_special_members);
10564 }
10565}
10566
Sebastian Redl13e88542009-04-27 21:33:24 +000010567static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010568 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010569 Stmt *SubStmt = *CI;
10570 if (!SubStmt)
10571 continue;
10572 if (isa<ReturnStmt>(SubStmt))
10573 Self.Diag(SubStmt->getSourceRange().getBegin(),
10574 diag::err_return_in_constructor_handler);
10575 if (!isa<Expr>(SubStmt))
10576 SearchForReturnInStmt(Self, SubStmt);
10577 }
10578}
10579
10580void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10581 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10582 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10583 SearchForReturnInStmt(*this, Handler);
10584 }
10585}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010586
Mike Stump1eb44332009-09-09 15:08:12 +000010587bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010588 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010589 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10590 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010591
Chandler Carruth73857792010-02-15 11:53:20 +000010592 if (Context.hasSameType(NewTy, OldTy) ||
10593 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010594 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010595
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010596 // Check if the return types are covariant
10597 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010598
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010599 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010600 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10601 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010602 NewClassTy = NewPT->getPointeeType();
10603 OldClassTy = OldPT->getPointeeType();
10604 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010605 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10606 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10607 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10608 NewClassTy = NewRT->getPointeeType();
10609 OldClassTy = OldRT->getPointeeType();
10610 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010611 }
10612 }
Mike Stump1eb44332009-09-09 15:08:12 +000010613
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010614 // The return types aren't either both pointers or references to a class type.
10615 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010616 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010617 diag::err_different_return_type_for_overriding_virtual_function)
10618 << New->getDeclName() << NewTy << OldTy;
10619 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010620
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010621 return true;
10622 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010623
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010624 // C++ [class.virtual]p6:
10625 // If the return type of D::f differs from the return type of B::f, the
10626 // class type in the return type of D::f shall be complete at the point of
10627 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010628 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10629 if (!RT->isBeingDefined() &&
10630 RequireCompleteType(New->getLocation(), NewClassTy,
10631 PDiag(diag::err_covariant_return_incomplete)
10632 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010633 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010634 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010635
Douglas Gregora4923eb2009-11-16 21:35:15 +000010636 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010637 // Check if the new class derives from the old class.
10638 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10639 Diag(New->getLocation(),
10640 diag::err_covariant_return_not_derived)
10641 << New->getDeclName() << NewTy << OldTy;
10642 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10643 return true;
10644 }
Mike Stump1eb44332009-09-09 15:08:12 +000010645
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010646 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010647 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010648 diag::err_covariant_return_inaccessible_base,
10649 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10650 // FIXME: Should this point to the return type?
10651 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010652 // FIXME: this note won't trigger for delayed access control
10653 // diagnostics, and it's impossible to get an undelayed error
10654 // here from access control during the original parse because
10655 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010656 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10657 return true;
10658 }
10659 }
Mike Stump1eb44332009-09-09 15:08:12 +000010660
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010661 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010662 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010663 Diag(New->getLocation(),
10664 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010665 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010666 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10667 return true;
10668 };
Mike Stump1eb44332009-09-09 15:08:12 +000010669
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010670
10671 // The new class type must have the same or less qualifiers as the old type.
10672 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10673 Diag(New->getLocation(),
10674 diag::err_covariant_return_type_class_type_more_qualified)
10675 << New->getDeclName() << NewTy << OldTy;
10676 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10677 return true;
10678 };
Mike Stump1eb44332009-09-09 15:08:12 +000010679
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010680 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010681}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010682
Douglas Gregor4ba31362009-12-01 17:24:26 +000010683/// \brief Mark the given method pure.
10684///
10685/// \param Method the method to be marked pure.
10686///
10687/// \param InitRange the source range that covers the "0" initializer.
10688bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010689 SourceLocation EndLoc = InitRange.getEnd();
10690 if (EndLoc.isValid())
10691 Method->setRangeEnd(EndLoc);
10692
Douglas Gregor4ba31362009-12-01 17:24:26 +000010693 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10694 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010695 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010696 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010697
10698 if (!Method->isInvalidDecl())
10699 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10700 << Method->getDeclName() << InitRange;
10701 return true;
10702}
10703
John McCall731ad842009-12-19 09:28:58 +000010704/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10705/// an initializer for the out-of-line declaration 'Dcl'. The scope
10706/// is a fresh scope pushed for just this purpose.
10707///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010708/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10709/// static data member of class X, names should be looked up in the scope of
10710/// class X.
John McCalld226f652010-08-21 09:40:31 +000010711void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010712 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010713 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010714
John McCall731ad842009-12-19 09:28:58 +000010715 // We should only get called for declarations with scope specifiers, like:
10716 // int foo::bar;
10717 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010718 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010719}
10720
10721/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010722/// initializer for the out-of-line declaration 'D'.
10723void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010724 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010725 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010726
John McCall731ad842009-12-19 09:28:58 +000010727 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010728 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010729}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010730
10731/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10732/// C++ if/switch/while/for statement.
10733/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010734DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010735 // C++ 6.4p2:
10736 // The declarator shall not specify a function or an array.
10737 // The type-specifier-seq shall not contain typedef and shall not declare a
10738 // new class or enumeration.
10739 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10740 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010741
10742 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010743 if (!Dcl)
10744 return true;
10745
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010746 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10747 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010748 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010749 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010750 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010751
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010752 return Dcl;
10753}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010754
Douglas Gregordfe65432011-07-28 19:11:31 +000010755void Sema::LoadExternalVTableUses() {
10756 if (!ExternalSource)
10757 return;
10758
10759 SmallVector<ExternalVTableUse, 4> VTables;
10760 ExternalSource->ReadUsedVTables(VTables);
10761 SmallVector<VTableUse, 4> NewUses;
10762 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10763 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10764 = VTablesUsed.find(VTables[I].Record);
10765 // Even if a definition wasn't required before, it may be required now.
10766 if (Pos != VTablesUsed.end()) {
10767 if (!Pos->second && VTables[I].DefinitionRequired)
10768 Pos->second = true;
10769 continue;
10770 }
10771
10772 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10773 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10774 }
10775
10776 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10777}
10778
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010779void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10780 bool DefinitionRequired) {
10781 // Ignore any vtable uses in unevaluated operands or for classes that do
10782 // not have a vtable.
10783 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10784 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010785 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010786 return;
10787
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010788 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010789 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010790 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10791 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10792 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10793 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010794 // If we already had an entry, check to see if we are promoting this vtable
10795 // to required a definition. If so, we need to reappend to the VTableUses
10796 // list, since we may have already processed the first entry.
10797 if (DefinitionRequired && !Pos.first->second) {
10798 Pos.first->second = true;
10799 } else {
10800 // Otherwise, we can early exit.
10801 return;
10802 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010803 }
10804
10805 // Local classes need to have their virtual members marked
10806 // immediately. For all other classes, we mark their virtual members
10807 // at the end of the translation unit.
10808 if (Class->isLocalClass())
10809 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010810 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010811 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010812}
10813
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010814bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010815 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010816 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010817 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010818
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010819 // Note: The VTableUses vector could grow as a result of marking
10820 // the members of a class as "used", so we check the size each
10821 // time through the loop and prefer indices (with are stable) to
10822 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010823 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010824 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010825 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010826 if (!Class)
10827 continue;
10828
10829 SourceLocation Loc = VTableUses[I].second;
10830
10831 // If this class has a key function, but that key function is
10832 // defined in another translation unit, we don't need to emit the
10833 // vtable even though we're using it.
10834 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010835 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010836 switch (KeyFunction->getTemplateSpecializationKind()) {
10837 case TSK_Undeclared:
10838 case TSK_ExplicitSpecialization:
10839 case TSK_ExplicitInstantiationDeclaration:
10840 // The key function is in another translation unit.
10841 continue;
10842
10843 case TSK_ExplicitInstantiationDefinition:
10844 case TSK_ImplicitInstantiation:
10845 // We will be instantiating the key function.
10846 break;
10847 }
10848 } else if (!KeyFunction) {
10849 // If we have a class with no key function that is the subject
10850 // of an explicit instantiation declaration, suppress the
10851 // vtable; it will live with the explicit instantiation
10852 // definition.
10853 bool IsExplicitInstantiationDeclaration
10854 = Class->getTemplateSpecializationKind()
10855 == TSK_ExplicitInstantiationDeclaration;
10856 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10857 REnd = Class->redecls_end();
10858 R != REnd; ++R) {
10859 TemplateSpecializationKind TSK
10860 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10861 if (TSK == TSK_ExplicitInstantiationDeclaration)
10862 IsExplicitInstantiationDeclaration = true;
10863 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10864 IsExplicitInstantiationDeclaration = false;
10865 break;
10866 }
10867 }
10868
10869 if (IsExplicitInstantiationDeclaration)
10870 continue;
10871 }
10872
10873 // Mark all of the virtual members of this class as referenced, so
10874 // that we can build a vtable. Then, tell the AST consumer that a
10875 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010876 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010877 MarkVirtualMembersReferenced(Loc, Class);
10878 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10879 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10880
10881 // Optionally warn if we're emitting a weak vtable.
10882 if (Class->getLinkage() == ExternalLinkage &&
10883 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010884 const FunctionDecl *KeyFunctionDef = 0;
10885 if (!KeyFunction ||
10886 (KeyFunction->hasBody(KeyFunctionDef) &&
10887 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010888 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10889 TSK_ExplicitInstantiationDefinition
10890 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10891 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010892 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010893 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010894 VTableUses.clear();
10895
Douglas Gregor78844032011-04-22 22:25:37 +000010896 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010897}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010898
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010899void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10900 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010901 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10902 e = RD->method_end(); i != e; ++i) {
10903 CXXMethodDecl *MD = *i;
10904
10905 // C++ [basic.def.odr]p2:
10906 // [...] A virtual member function is used if it is not pure. [...]
10907 if (MD->isVirtual() && !MD->isPure())
10908 MarkDeclarationReferenced(Loc, MD);
10909 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010910
10911 // Only classes that have virtual bases need a VTT.
10912 if (RD->getNumVBases() == 0)
10913 return;
10914
10915 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10916 e = RD->bases_end(); i != e; ++i) {
10917 const CXXRecordDecl *Base =
10918 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010919 if (Base->getNumVBases() == 0)
10920 continue;
10921 MarkVirtualMembersReferenced(Loc, Base);
10922 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010923}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010924
10925/// SetIvarInitializers - This routine builds initialization ASTs for the
10926/// Objective-C implementation whose ivars need be initialized.
10927void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10928 if (!getLangOptions().CPlusPlus)
10929 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010930 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010931 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010932 CollectIvarsToConstructOrDestruct(OID, ivars);
10933 if (ivars.empty())
10934 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010935 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010936 for (unsigned i = 0; i < ivars.size(); i++) {
10937 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010938 if (Field->isInvalidDecl())
10939 continue;
10940
Sean Huntcbb67482011-01-08 20:30:50 +000010941 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010942 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10943 InitializationKind InitKind =
10944 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10945
10946 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010947 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010948 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010949 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010950 // Note, MemberInit could actually come back empty if no initialization
10951 // is required (e.g., because it would call a trivial default constructor)
10952 if (!MemberInit.get() || MemberInit.isInvalid())
10953 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010954
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010955 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010956 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10957 SourceLocation(),
10958 MemberInit.takeAs<Expr>(),
10959 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010960 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010961
10962 // Be sure that the destructor is accessible and is marked as referenced.
10963 if (const RecordType *RecordTy
10964 = Context.getBaseElementType(Field->getType())
10965 ->getAs<RecordType>()) {
10966 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010967 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010968 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10969 CheckDestructorAccess(Field->getLocation(), Destructor,
10970 PDiag(diag::err_access_dtor_ivar)
10971 << Context.getBaseElementType(Field->getType()));
10972 }
10973 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010974 }
10975 ObjCImplementation->setIvarInitializers(Context,
10976 AllToInit.data(), AllToInit.size());
10977 }
10978}
Sean Huntfe57eef2011-05-04 05:57:24 +000010979
Sean Huntebcbe1d2011-05-04 23:29:54 +000010980static
10981void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10982 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10983 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10984 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10985 Sema &S) {
10986 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10987 CE = Current.end();
10988 if (Ctor->isInvalidDecl())
10989 return;
10990
10991 const FunctionDecl *FNTarget = 0;
10992 CXXConstructorDecl *Target;
10993
10994 // We ignore the result here since if we don't have a body, Target will be
10995 // null below.
10996 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10997 Target
10998= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10999
11000 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11001 // Avoid dereferencing a null pointer here.
11002 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11003
11004 if (!Current.insert(Canonical))
11005 return;
11006
11007 // We know that beyond here, we aren't chaining into a cycle.
11008 if (!Target || !Target->isDelegatingConstructor() ||
11009 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11010 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11011 Valid.insert(*CI);
11012 Current.clear();
11013 // We've hit a cycle.
11014 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11015 Current.count(TCanonical)) {
11016 // If we haven't diagnosed this cycle yet, do so now.
11017 if (!Invalid.count(TCanonical)) {
11018 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011019 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011020 << Ctor;
11021
11022 // Don't add a note for a function delegating directo to itself.
11023 if (TCanonical != Canonical)
11024 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11025
11026 CXXConstructorDecl *C = Target;
11027 while (C->getCanonicalDecl() != Canonical) {
11028 (void)C->getTargetConstructor()->hasBody(FNTarget);
11029 assert(FNTarget && "Ctor cycle through bodiless function");
11030
11031 C
11032 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11033 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11034 }
11035 }
11036
11037 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11038 Invalid.insert(*CI);
11039 Current.clear();
11040 } else {
11041 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11042 }
11043}
11044
11045
Sean Huntfe57eef2011-05-04 05:57:24 +000011046void Sema::CheckDelegatingCtorCycles() {
11047 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11048
Sean Huntebcbe1d2011-05-04 23:29:54 +000011049 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11050 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011051
Douglas Gregor0129b562011-07-27 21:57:17 +000011052 for (DelegatingCtorDeclsType::iterator
11053 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011054 E = DelegatingCtorDecls.end();
11055 I != E; ++I) {
11056 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011057 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011058
11059 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11060 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011061}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011062
11063/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11064Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11065 // Implicitly declared functions (e.g. copy constructors) are
11066 // __host__ __device__
11067 if (D->isImplicit())
11068 return CFT_HostDevice;
11069
11070 if (D->hasAttr<CUDAGlobalAttr>())
11071 return CFT_Global;
11072
11073 if (D->hasAttr<CUDADeviceAttr>()) {
11074 if (D->hasAttr<CUDAHostAttr>())
11075 return CFT_HostDevice;
11076 else
11077 return CFT_Device;
11078 }
11079
11080 return CFT_Host;
11081}
11082
11083bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11084 CUDAFunctionTarget CalleeTarget) {
11085 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11086 // Callable from the device only."
11087 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11088 return true;
11089
11090 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11091 // Callable from the host only."
11092 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11093 // Callable from the host only."
11094 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11095 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11096 return true;
11097
11098 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11099 return true;
11100
11101 return false;
11102}