blob: cce6a532fdd1faf3ec49d74d693a93082697d49f [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Sean Hunt001cad92011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000118 return;
119
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
122
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith7a614d82011-06-11 17:19:42 +0000132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
134
Sean Hunt001cad92011-05-10 00:49:42 +0000135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
137 return;
138
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
141 return;
142
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
148 return;
149 }
150
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
159
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
162 ClearExceptions();
163 ComputedEST = EST_None;
164 }
165 // noexcept(true) won't change anything either.
166 return;
167 }
168
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
176 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith7a614d82011-06-11 17:19:42 +0000181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders Carlssoned961f92009-08-25 02:29:20 +0000210bool
John McCall9ae2f072010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
216 return true;
217 }
218
Anders Carlssoned961f92009-08-25 02:29:20 +0000219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000233 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000235
John McCallb4eb64d2010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
252 }
253
Anders Carlsson9351c172009-08-25 03:18:48 +0000254 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000255}
256
Chris Lattner8123a952008-04-10 02:22:51 +0000257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260void
John McCalld226f652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000264 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
John McCalld226f652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6f526752010-12-16 08:48:57 +0000277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
280 return;
281 }
282
Anders Carlsson66e30672009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289
John McCall9ae2f072010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000291}
292
Douglas Gregor61366e92008-12-24 00:01:03 +0000293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCalld226f652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000308}
309
Douglas Gregor72b505b2008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCalld226f652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Anders Carlsson5e300d12009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000321}
322
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346 delete Toks;
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner3d1cee32008-04-08 05:04:30 +0000358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
364
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000377 //
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
386
Douglas Gregor6cc15182009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000388
Francois Pichet8d051e02011-04-10 03:03:52 +0000389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
391
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
394 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000395 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
403 else
404 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000409
Francois Pichet8cf90492011-04-10 04:58:30 +0000410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000420
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 if (!Older->getParamDecl(p)->hasDefaultArg())
426 break;
427
428 OldParam = Older->getParamDecl(p);
429 }
430
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCall3d6c1782010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
450 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
462 // instantiated.
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
472 //
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
476 // dependent type.
477 int WhichKind = 2;
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
481 WhichKind = 0;
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483 WhichKind = 1;
484 else
485 WhichKind = 2;
486 }
487
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
490 << WhichKind
491 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
499 << OldSM;
500 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000501 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000502 }
503 }
504
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//
651// This implements C++0x [dcl.constexpr]p3,4, as amended by N3308.
652//
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
662 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(NewFD)) {
663 // C++0x [dcl.constexpr]p4:
664 // In the definition of a constexpr constructor, each of the parameter
665 // types shall be a literal type.
666 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
667 return false;
668
669 // In addition, either its function-body shall be = delete or = default or
670 // it shall satisfy the following constraints:
671 // - the class shall not have any virtual base classes;
672 const CXXRecordDecl *RD = CD->getParent();
673 if (RD->getNumVBases()) {
674 // Note, this is still illegal if the body is = default, since the
675 // implicit body does not satisfy the requirements of a constexpr
676 // constructor. We also reject cases where the body is = delete, as
677 // required by N3308.
678 if (CCK != CCK_Instantiation) {
679 Diag(NewFD->getLocation(),
680 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
681 : diag::note_constexpr_tmpl_virtual_base)
682 << RD->isStruct() << RD->getNumVBases();
683 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 }
690 } else {
691 // C++0x [dcl.constexpr]p3:
692 // The definition of a constexpr function shall satisfy the following
693 // constraints:
694 // - it shall not be virtual;
695 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
696 if (Method && Method->isVirtual()) {
697 if (CCK != CCK_Instantiation) {
698 Diag(NewFD->getLocation(),
699 CCK == CCK_Declaration ? diag::err_constexpr_virtual
700 : diag::note_constexpr_tmpl_virtual);
701
702 // If it's not obvious why this function is virtual, find an overridden
703 // function which uses the 'virtual' keyword.
704 const CXXMethodDecl *WrittenVirtual = Method;
705 while (!WrittenVirtual->isVirtualAsWritten())
706 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
707 if (WrittenVirtual != Method)
708 Diag(WrittenVirtual->getLocation(),
709 diag::note_overridden_virtual_function);
710 }
711 return false;
712 }
713
714 // - its return type shall be a literal type;
715 QualType RT = NewFD->getResultType();
716 if (!RT->isDependentType() &&
717 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
718 PDiag(diag::err_constexpr_non_literal_return) :
719 PDiag(),
720 /*AllowIncompleteType*/ true)) {
721 if (CCK == CCK_NoteNonConstexprInstantiation)
722 Diag(NewFD->getLocation(),
723 diag::note_constexpr_tmpl_non_literal_return) << RT;
724 return false;
725 }
726
727 // - each of its parameter types shall be a literal type;
728 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
729 return false;
730 }
731
732 return true;
733}
734
735/// Check the given declaration statement is legal within a constexpr function
736/// body. C++0x [dcl.constexpr]p3,p4.
737///
738/// \return true if the body is OK, false if we have diagnosed a problem.
739static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
740 DeclStmt *DS) {
741 // C++0x [dcl.constexpr]p3 and p4:
742 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
743 // contain only
744 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
745 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
746 switch ((*DclIt)->getKind()) {
747 case Decl::StaticAssert:
748 case Decl::Using:
749 case Decl::UsingShadow:
750 case Decl::UsingDirective:
751 case Decl::UnresolvedUsingTypename:
752 // - static_assert-declarations
753 // - using-declarations,
754 // - using-directives,
755 continue;
756
757 case Decl::Typedef:
758 case Decl::TypeAlias: {
759 // - typedef declarations and alias-declarations that do not define
760 // classes or enumerations,
761 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
762 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
763 // Don't allow variably-modified types in constexpr functions.
764 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
765 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
766 << TL.getSourceRange() << TL.getType()
767 << isa<CXXConstructorDecl>(Dcl);
768 return false;
769 }
770 continue;
771 }
772
773 case Decl::Enum:
774 case Decl::CXXRecord:
775 // As an extension, we allow the declaration (but not the definition) of
776 // classes and enumerations in all declarations, not just in typedef and
777 // alias declarations.
778 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
779 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
780 << isa<CXXConstructorDecl>(Dcl);
781 return false;
782 }
783 continue;
784
785 case Decl::Var:
786 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
787 << isa<CXXConstructorDecl>(Dcl);
788 return false;
789
790 default:
791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794 }
795 }
796
797 return true;
798}
799
800/// Check that the given field is initialized within a constexpr constructor.
801///
802/// \param Dcl The constexpr constructor being checked.
803/// \param Field The field being checked. This may be a member of an anonymous
804/// struct or union nested within the class being checked.
805/// \param Inits All declarations, including anonymous struct/union members and
806/// indirect members, for which any initialization was provided.
807/// \param Diagnosed Set to true if an error is produced.
808static void CheckConstexprCtorInitializer(Sema &SemaRef,
809 const FunctionDecl *Dcl,
810 FieldDecl *Field,
811 llvm::SmallSet<Decl*, 16> &Inits,
812 bool &Diagnosed) {
813 if (!Inits.count(Field)) {
814 if (!Diagnosed) {
815 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
816 Diagnosed = true;
817 }
818 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
819 } else if (Field->isAnonymousStructOrUnion()) {
820 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
821 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
822 I != E; ++I)
823 // If an anonymous union contains an anonymous struct of which any member
824 // is initialized, all members must be initialized.
825 if (!RD->isUnion() || Inits.count(*I))
826 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
827 }
828}
829
830/// Check the body for the given constexpr function declaration only contains
831/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
832///
833/// \return true if the body is OK, false if we have diagnosed a problem.
834bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
835 if (isa<CXXTryStmt>(Body)) {
836 // C++0x [dcl.constexpr]p3:
837 // The definition of a constexpr function shall satisfy the following
838 // constraints: [...]
839 // - its function-body shall be = delete, = default, or a
840 // compound-statement
841 //
842 // C++0x [dcl.constexpr]p4:
843 // In the definition of a constexpr constructor, [...]
844 // - its function-body shall not be a function-try-block;
845 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
846 << isa<CXXConstructorDecl>(Dcl);
847 return false;
848 }
849
850 // - its function-body shall be [...] a compound-statement that contains only
851 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
852
853 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
854 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
855 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
856 switch ((*BodyIt)->getStmtClass()) {
857 case Stmt::NullStmtClass:
858 // - null statements,
859 continue;
860
861 case Stmt::DeclStmtClass:
862 // - static_assert-declarations
863 // - using-declarations,
864 // - using-directives,
865 // - typedef declarations and alias-declarations that do not define
866 // classes or enumerations,
867 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
868 return false;
869 continue;
870
871 case Stmt::ReturnStmtClass:
872 // - and exactly one return statement;
873 if (isa<CXXConstructorDecl>(Dcl))
874 break;
875
876 ReturnStmts.push_back((*BodyIt)->getLocStart());
877 // FIXME
878 // - every constructor call and implicit conversion used in initializing
879 // the return value shall be one of those allowed in a constant
880 // expression.
881 // Deal with this as part of a general check that the function can produce
882 // a constant expression (for [dcl.constexpr]p5).
883 continue;
884
885 default:
886 break;
887 }
888
889 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
890 << isa<CXXConstructorDecl>(Dcl);
891 return false;
892 }
893
894 if (const CXXConstructorDecl *Constructor
895 = dyn_cast<CXXConstructorDecl>(Dcl)) {
896 const CXXRecordDecl *RD = Constructor->getParent();
897 // - every non-static data member and base class sub-object shall be
898 // initialized;
899 if (RD->isUnion()) {
900 // DR1359: Exactly one member of a union shall be initialized.
901 if (Constructor->getNumCtorInitializers() == 0) {
902 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
903 return false;
904 }
905 } else if (!Constructor->isDelegatingConstructor()) {
906 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
907
908 // Skip detailed checking if we have enough initializers, and we would
909 // allow at most one initializer per member.
910 bool AnyAnonStructUnionMembers = false;
911 unsigned Fields = 0;
912 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
913 E = RD->field_end(); I != E; ++I, ++Fields) {
914 if ((*I)->isAnonymousStructOrUnion()) {
915 AnyAnonStructUnionMembers = true;
916 break;
917 }
918 }
919 if (AnyAnonStructUnionMembers ||
920 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
921 // Check initialization of non-static data members. Base classes are
922 // always initialized so do not need to be checked. Dependent bases
923 // might not have initializers in the member initializer list.
924 llvm::SmallSet<Decl*, 16> Inits;
925 for (CXXConstructorDecl::init_const_iterator
926 I = Constructor->init_begin(), E = Constructor->init_end();
927 I != E; ++I) {
928 if (FieldDecl *FD = (*I)->getMember())
929 Inits.insert(FD);
930 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
931 Inits.insert(ID->chain_begin(), ID->chain_end());
932 }
933
934 bool Diagnosed = false;
935 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
936 E = RD->field_end(); I != E; ++I)
937 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
938 if (Diagnosed)
939 return false;
940 }
941 }
942
943 // FIXME
944 // - every constructor involved in initializing non-static data members
945 // and base class sub-objects shall be a constexpr constructor;
946 // - every assignment-expression that is an initializer-clause appearing
947 // directly or indirectly within a brace-or-equal-initializer for
948 // a non-static data member that is not named by a mem-initializer-id
949 // shall be a constant expression; and
950 // - every implicit conversion used in converting a constructor argument
951 // to the corresponding parameter type and converting
952 // a full-expression to the corresponding member type shall be one of
953 // those allowed in a constant expression.
954 // Deal with these as part of a general check that the function can produce
955 // a constant expression (for [dcl.constexpr]p5).
956 } else {
957 if (ReturnStmts.empty()) {
958 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
959 return false;
960 }
961 if (ReturnStmts.size() > 1) {
962 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
963 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
964 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
965 return false;
966 }
967 }
968
969 return true;
970}
971
Douglas Gregorb48fe382008-10-31 09:07:45 +0000972/// isCurrentClassName - Determine whether the identifier II is the
973/// name of the class type currently being defined. In the case of
974/// nested classes, this will only return true if II is the name of
975/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000976bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
977 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000978 assert(getLangOptions().CPlusPlus && "No class names in C!");
979
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000980 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000981 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000982 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000983 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
984 } else
985 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
986
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000987 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000988 return &II == CurDecl->getIdentifier();
989 else
990 return false;
991}
992
Mike Stump1eb44332009-09-09 15:08:12 +0000993/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000994///
995/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
996/// and returns NULL otherwise.
997CXXBaseSpecifier *
998Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
999 SourceRange SpecifierRange,
1000 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001001 TypeSourceInfo *TInfo,
1002 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001003 QualType BaseType = TInfo->getType();
1004
Douglas Gregor2943aed2009-03-03 04:44:36 +00001005 // C++ [class.union]p1:
1006 // A union shall not have base classes.
1007 if (Class->isUnion()) {
1008 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1009 << SpecifierRange;
1010 return 0;
1011 }
1012
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001013 if (EllipsisLoc.isValid() &&
1014 !TInfo->getType()->containsUnexpandedParameterPack()) {
1015 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1016 << TInfo->getTypeLoc().getSourceRange();
1017 EllipsisLoc = SourceLocation();
1018 }
1019
Douglas Gregor2943aed2009-03-03 04:44:36 +00001020 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001021 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001022 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001023 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001024
1025 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001026
1027 // Base specifiers must be record types.
1028 if (!BaseType->isRecordType()) {
1029 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1030 return 0;
1031 }
1032
1033 // C++ [class.union]p1:
1034 // A union shall not be used as a base class.
1035 if (BaseType->isUnionType()) {
1036 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1037 return 0;
1038 }
1039
1040 // C++ [class.derived]p2:
1041 // The class-name in a base-specifier shall not be an incompletely
1042 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001043 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001044 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001045 << SpecifierRange)) {
1046 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001047 return 0;
John McCall572fc622010-08-17 07:23:57 +00001048 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001049
Eli Friedman1d954f62009-08-15 21:55:26 +00001050 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001051 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001052 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001053 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001054 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001055 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1056 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001057
Anders Carlsson1d209272011-03-25 14:55:14 +00001058 // C++ [class]p3:
1059 // If a class is marked final and it appears as a base-type-specifier in
1060 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001061 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001062 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1063 << CXXBaseDecl->getDeclName();
1064 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1065 << CXXBaseDecl->getDeclName();
1066 return 0;
1067 }
1068
John McCall572fc622010-08-17 07:23:57 +00001069 if (BaseDecl->isInvalidDecl())
1070 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001071
1072 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001073 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001074 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001075 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001076}
1077
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001078/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1079/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001080/// example:
1081/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001082/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001083BaseResult
John McCalld226f652010-08-21 09:40:31 +00001084Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001085 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001086 ParsedType basetype, SourceLocation BaseLoc,
1087 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001088 if (!classdecl)
1089 return true;
1090
Douglas Gregor40808ce2009-03-09 23:48:35 +00001091 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001092 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001093 if (!Class)
1094 return true;
1095
Nick Lewycky56062202010-07-26 16:56:01 +00001096 TypeSourceInfo *TInfo = 0;
1097 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001098
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001099 if (EllipsisLoc.isInvalid() &&
1100 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001101 UPPC_BaseType))
1102 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001103
Douglas Gregor2943aed2009-03-03 04:44:36 +00001104 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001105 Virtual, Access, TInfo,
1106 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001107 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Douglas Gregor2943aed2009-03-03 04:44:36 +00001109 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001110}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001111
Douglas Gregor2943aed2009-03-03 04:44:36 +00001112/// \brief Performs the actual work of attaching the given base class
1113/// specifiers to a C++ class.
1114bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1115 unsigned NumBases) {
1116 if (NumBases == 0)
1117 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001118
1119 // Used to keep track of which base types we have already seen, so
1120 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001121 // that the key is always the unqualified canonical type of the base
1122 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001123 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1124
1125 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001126 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001127 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001128 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001129 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001130 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001131 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001132 if (KnownBaseTypes[NewBaseType]) {
1133 // C++ [class.mi]p3:
1134 // A class shall not be specified as a direct base class of a
1135 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001136 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001137 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001138 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001140
1141 // Delete the duplicate base class specifier; we're going to
1142 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001143 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001144
1145 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001146 } else {
1147 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001148 KnownBaseTypes[NewBaseType] = Bases[idx];
1149 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001150 }
1151 }
1152
1153 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001154 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001155
1156 // Delete the remaining (good) base class specifiers, since their
1157 // data has been copied into the CXXRecordDecl.
1158 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001159 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001160
1161 return Invalid;
1162}
1163
1164/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1165/// class, after checking whether there are any duplicate base
1166/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001167void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001168 unsigned NumBases) {
1169 if (!ClassDecl || !Bases || !NumBases)
1170 return;
1171
1172 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001173 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001174 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001175}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001176
John McCall3cb0ebd2010-03-10 03:28:59 +00001177static CXXRecordDecl *GetClassForType(QualType T) {
1178 if (const RecordType *RT = T->getAs<RecordType>())
1179 return cast<CXXRecordDecl>(RT->getDecl());
1180 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1181 return ICT->getDecl();
1182 else
1183 return 0;
1184}
1185
Douglas Gregora8f32e02009-10-06 17:59:45 +00001186/// \brief Determine whether the type \p Derived is a C++ class that is
1187/// derived from the type \p Base.
1188bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1189 if (!getLangOptions().CPlusPlus)
1190 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001191
1192 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1193 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001194 return false;
1195
John McCall3cb0ebd2010-03-10 03:28:59 +00001196 CXXRecordDecl *BaseRD = GetClassForType(Base);
1197 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001198 return false;
1199
John McCall86ff3082010-02-04 22:26:26 +00001200 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1201 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001202}
1203
1204/// \brief Determine whether the type \p Derived is a C++ class that is
1205/// derived from the type \p Base.
1206bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1207 if (!getLangOptions().CPlusPlus)
1208 return false;
1209
John McCall3cb0ebd2010-03-10 03:28:59 +00001210 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1211 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001212 return false;
1213
John McCall3cb0ebd2010-03-10 03:28:59 +00001214 CXXRecordDecl *BaseRD = GetClassForType(Base);
1215 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001216 return false;
1217
Douglas Gregora8f32e02009-10-06 17:59:45 +00001218 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1219}
1220
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001221void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001222 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001223 assert(BasePathArray.empty() && "Base path array must be empty!");
1224 assert(Paths.isRecordingPaths() && "Must record paths!");
1225
1226 const CXXBasePath &Path = Paths.front();
1227
1228 // We first go backward and check if we have a virtual base.
1229 // FIXME: It would be better if CXXBasePath had the base specifier for
1230 // the nearest virtual base.
1231 unsigned Start = 0;
1232 for (unsigned I = Path.size(); I != 0; --I) {
1233 if (Path[I - 1].Base->isVirtual()) {
1234 Start = I - 1;
1235 break;
1236 }
1237 }
1238
1239 // Now add all bases.
1240 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001241 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001242}
1243
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001244/// \brief Determine whether the given base path includes a virtual
1245/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001246bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1247 for (CXXCastPath::const_iterator B = BasePath.begin(),
1248 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001249 B != BEnd; ++B)
1250 if ((*B)->isVirtual())
1251 return true;
1252
1253 return false;
1254}
1255
Douglas Gregora8f32e02009-10-06 17:59:45 +00001256/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1257/// conversion (where Derived and Base are class types) is
1258/// well-formed, meaning that the conversion is unambiguous (and
1259/// that all of the base classes are accessible). Returns true
1260/// and emits a diagnostic if the code is ill-formed, returns false
1261/// otherwise. Loc is the location where this routine should point to
1262/// if there is an error, and Range is the source range to highlight
1263/// if there is an error.
1264bool
1265Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001266 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001267 unsigned AmbigiousBaseConvID,
1268 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001269 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001270 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001271 // First, determine whether the path from Derived to Base is
1272 // ambiguous. This is slightly more expensive than checking whether
1273 // the Derived to Base conversion exists, because here we need to
1274 // explore multiple paths to determine if there is an ambiguity.
1275 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1276 /*DetectVirtual=*/false);
1277 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1278 assert(DerivationOkay &&
1279 "Can only be used with a derived-to-base conversion");
1280 (void)DerivationOkay;
1281
1282 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001283 if (InaccessibleBaseID) {
1284 // Check that the base class can be accessed.
1285 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1286 InaccessibleBaseID)) {
1287 case AR_inaccessible:
1288 return true;
1289 case AR_accessible:
1290 case AR_dependent:
1291 case AR_delayed:
1292 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001293 }
John McCall6b2accb2010-02-10 09:31:12 +00001294 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001295
1296 // Build a base path if necessary.
1297 if (BasePath)
1298 BuildBasePathArray(Paths, *BasePath);
1299 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001300 }
1301
1302 // We know that the derived-to-base conversion is ambiguous, and
1303 // we're going to produce a diagnostic. Perform the derived-to-base
1304 // search just one more time to compute all of the possible paths so
1305 // that we can print them out. This is more expensive than any of
1306 // the previous derived-to-base checks we've done, but at this point
1307 // performance isn't as much of an issue.
1308 Paths.clear();
1309 Paths.setRecordingPaths(true);
1310 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1311 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1312 (void)StillOkay;
1313
1314 // Build up a textual representation of the ambiguous paths, e.g.,
1315 // D -> B -> A, that will be used to illustrate the ambiguous
1316 // conversions in the diagnostic. We only print one of the paths
1317 // to each base class subobject.
1318 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1319
1320 Diag(Loc, AmbigiousBaseConvID)
1321 << Derived << Base << PathDisplayStr << Range << Name;
1322 return true;
1323}
1324
1325bool
1326Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001327 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001328 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001329 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001330 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001331 IgnoreAccess ? 0
1332 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001333 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001334 Loc, Range, DeclarationName(),
1335 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001336}
1337
1338
1339/// @brief Builds a string representing ambiguous paths from a
1340/// specific derived class to different subobjects of the same base
1341/// class.
1342///
1343/// This function builds a string that can be used in error messages
1344/// to show the different paths that one can take through the
1345/// inheritance hierarchy to go from the derived class to different
1346/// subobjects of a base class. The result looks something like this:
1347/// @code
1348/// struct D -> struct B -> struct A
1349/// struct D -> struct C -> struct A
1350/// @endcode
1351std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1352 std::string PathDisplayStr;
1353 std::set<unsigned> DisplayedPaths;
1354 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1355 Path != Paths.end(); ++Path) {
1356 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1357 // We haven't displayed a path to this particular base
1358 // class subobject yet.
1359 PathDisplayStr += "\n ";
1360 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1361 for (CXXBasePath::const_iterator Element = Path->begin();
1362 Element != Path->end(); ++Element)
1363 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1364 }
1365 }
1366
1367 return PathDisplayStr;
1368}
1369
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001370//===----------------------------------------------------------------------===//
1371// C++ class member Handling
1372//===----------------------------------------------------------------------===//
1373
Abramo Bagnara6206d532010-06-05 05:09:32 +00001374/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +00001375Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1376 SourceLocation ASLoc,
1377 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001378 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001379 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001380 ASLoc, ColonLoc);
1381 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +00001382 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +00001383}
1384
Anders Carlsson9e682d92011-01-20 05:57:14 +00001385/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001386void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001387 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001388 if (!MD || !MD->isVirtual())
1389 return;
1390
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001391 if (MD->isDependentContext())
1392 return;
1393
Anders Carlsson9e682d92011-01-20 05:57:14 +00001394 // C++0x [class.virtual]p3:
1395 // If a virtual function is marked with the virt-specifier override and does
1396 // not override a member function of a base class,
1397 // the program is ill-formed.
1398 bool HasOverriddenMethods =
1399 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001400 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001401 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001402 diag::err_function_marked_override_not_overriding)
1403 << MD->getDeclName();
1404 return;
1405 }
1406}
1407
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001408/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1409/// function overrides a virtual member function marked 'final', according to
1410/// C++0x [class.virtual]p3.
1411bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1412 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001413 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001414 return false;
1415
1416 Diag(New->getLocation(), diag::err_final_function_overridden)
1417 << New->getDeclName();
1418 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1419 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001420}
1421
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001422/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1423/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001424/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1425/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1426/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001427Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001428Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001429 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001430 Expr *BW, const VirtSpecifiers &VS,
1431 Expr *InitExpr, bool HasDeferredInit,
Richard Smith7a614d82011-06-11 17:19:42 +00001432 bool IsDefinition) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001433 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001434 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1435 DeclarationName Name = NameInfo.getName();
1436 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001437
1438 // For anonymous bitfields, the location should point to the type.
1439 if (Loc.isInvalid())
1440 Loc = D.getSourceRange().getBegin();
1441
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001442 Expr *BitWidth = static_cast<Expr*>(BW);
1443 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001444
John McCall4bde1e12010-06-04 08:34:12 +00001445 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001446 assert(!DS.isFriendSpecified());
Richard Smith7a614d82011-06-11 17:19:42 +00001447 assert(!Init || !HasDeferredInit);
John McCall67d1a672009-08-06 02:15:43 +00001448
Richard Smith1ab0d902011-06-25 02:28:38 +00001449 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001450
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001451 // C++ 9.2p6: A member shall not be declared to have automatic storage
1452 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001453 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1454 // data members and cannot be applied to names declared const or static,
1455 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001456 switch (DS.getStorageClassSpec()) {
1457 case DeclSpec::SCS_unspecified:
1458 case DeclSpec::SCS_typedef:
1459 case DeclSpec::SCS_static:
1460 // FALL THROUGH.
1461 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001462 case DeclSpec::SCS_mutable:
1463 if (isFunc) {
1464 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001465 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001466 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001467 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Sebastian Redla11f42f2008-11-17 23:24:37 +00001469 // FIXME: It would be nicer if the keyword was ignored only for this
1470 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001471 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001472 }
1473 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001474 default:
1475 if (DS.getStorageClassSpecLoc().isValid())
1476 Diag(DS.getStorageClassSpecLoc(),
1477 diag::err_storageclass_invalid_for_member);
1478 else
1479 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1480 D.getMutableDeclSpec().ClearStorageClassSpecs();
1481 }
1482
Sebastian Redl669d5d72008-11-14 23:42:31 +00001483 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1484 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001485 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001486
1487 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001488 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001489 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001490
1491 // Data members must have identifiers for names.
1492 if (Name.getNameKind() != DeclarationName::Identifier) {
1493 Diag(Loc, diag::err_bad_variable_name)
1494 << Name;
1495 return 0;
1496 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001497
Douglas Gregorf2503652011-09-21 14:40:46 +00001498 IdentifierInfo *II = Name.getAsIdentifierInfo();
1499
1500 // Member field could not be with "template" keyword.
1501 // So TemplateParameterLists should be empty in this case.
1502 if (TemplateParameterLists.size()) {
1503 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1504 if (TemplateParams->size()) {
1505 // There is no such thing as a member field template.
1506 Diag(D.getIdentifierLoc(), diag::err_template_member)
1507 << II
1508 << SourceRange(TemplateParams->getTemplateLoc(),
1509 TemplateParams->getRAngleLoc());
1510 } else {
1511 // There is an extraneous 'template<>' for this member.
1512 Diag(TemplateParams->getTemplateLoc(),
1513 diag::err_template_member_noparams)
1514 << II
1515 << SourceRange(TemplateParams->getTemplateLoc(),
1516 TemplateParams->getRAngleLoc());
1517 }
1518 return 0;
1519 }
1520
Douglas Gregor922fff22010-10-13 22:19:53 +00001521 if (SS.isSet() && !SS.isInvalid()) {
1522 // The user provided a superfluous scope specifier inside a class
1523 // definition:
1524 //
1525 // class X {
1526 // int X::member;
1527 // };
1528 DeclContext *DC = 0;
1529 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1530 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1531 << Name << FixItHint::CreateRemoval(SS.getRange());
1532 else
1533 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1534 << Name << SS.getRange();
1535
1536 SS.clear();
1537 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001538
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001539 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001540 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001541 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001542 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001543 assert(!HasDeferredInit);
1544
Sean Hunte4246a62011-05-12 06:15:49 +00001545 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001546 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001547 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001548 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001549
1550 // Non-instance-fields can't have a bitfield.
1551 if (BitWidth) {
1552 if (Member->isInvalidDecl()) {
1553 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001554 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001555 // C++ 9.6p3: A bit-field shall not be a static member.
1556 // "static member 'A' cannot be a bit-field"
1557 Diag(Loc, diag::err_static_not_bitfield)
1558 << Name << BitWidth->getSourceRange();
1559 } else if (isa<TypedefDecl>(Member)) {
1560 // "typedef member 'x' cannot be a bit-field"
1561 Diag(Loc, diag::err_typedef_not_bitfield)
1562 << Name << BitWidth->getSourceRange();
1563 } else {
1564 // A function typedef ("typedef int f(); f a;").
1565 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1566 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001567 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001568 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Chris Lattner8b963ef2009-03-05 23:01:03 +00001571 BitWidth = 0;
1572 Member->setInvalidDecl();
1573 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001574
1575 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Douglas Gregor37b372b2009-08-20 22:52:58 +00001577 // If we have declared a member function template, set the access of the
1578 // templated declaration as well.
1579 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1580 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001581 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001582
Anders Carlssonaae5af22011-01-20 04:34:22 +00001583 if (VS.isOverrideSpecified()) {
1584 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1585 if (!MD || !MD->isVirtual()) {
1586 Diag(Member->getLocStart(),
1587 diag::override_keyword_only_allowed_on_virtual_member_functions)
1588 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001589 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001590 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001591 }
1592 if (VS.isFinalSpecified()) {
1593 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1594 if (!MD || !MD->isVirtual()) {
1595 Diag(Member->getLocStart(),
1596 diag::override_keyword_only_allowed_on_virtual_member_functions)
1597 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001598 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001599 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001600 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001601
Douglas Gregorf5251602011-03-08 17:10:18 +00001602 if (VS.getLastLocation().isValid()) {
1603 // Update the end location of a method that has a virt-specifiers.
1604 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1605 MD->setRangeEnd(VS.getLastLocation());
1606 }
1607
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001608 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001609
Douglas Gregor10bd3682008-11-17 22:58:34 +00001610 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001611
Douglas Gregor021c3b32009-03-11 23:00:04 +00001612 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001613 AddInitializerToDecl(Member, Init, false,
1614 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smithc6d990a2011-09-29 19:11:37 +00001615 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1616 ActOnUninitializedDecl(Member, DS.getTypeSpecType() == DeclSpec::TST_auto);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001617
Richard Smith483b9f32011-02-21 20:05:19 +00001618 FinalizeDeclaration(Member);
1619
John McCallb25b2952011-02-15 07:12:36 +00001620 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001621 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001622 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001623}
1624
Richard Smith7a614d82011-06-11 17:19:42 +00001625/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001626/// in-class initializer for a non-static C++ class member, and after
1627/// instantiating an in-class initializer in a class template. Such actions
1628/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001629void
1630Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1631 Expr *InitExpr) {
1632 FieldDecl *FD = cast<FieldDecl>(D);
1633
1634 if (!InitExpr) {
1635 FD->setInvalidDecl();
1636 FD->removeInClassInitializer();
1637 return;
1638 }
1639
1640 ExprResult Init = InitExpr;
1641 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1642 // FIXME: if there is no EqualLoc, this is list-initialization.
1643 Init = PerformCopyInitialization(
1644 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1645 if (Init.isInvalid()) {
1646 FD->setInvalidDecl();
1647 return;
1648 }
1649
1650 CheckImplicitConversions(Init.get(), EqualLoc);
1651 }
1652
1653 // C++0x [class.base.init]p7:
1654 // The initialization of each base and member constitutes a
1655 // full-expression.
1656 Init = MaybeCreateExprWithCleanups(Init);
1657 if (Init.isInvalid()) {
1658 FD->setInvalidDecl();
1659 return;
1660 }
1661
1662 InitExpr = Init.release();
1663
1664 FD->setInClassInitializer(InitExpr);
1665}
1666
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001667/// \brief Find the direct and/or virtual base specifiers that
1668/// correspond to the given base type, for use in base initialization
1669/// within a constructor.
1670static bool FindBaseInitializer(Sema &SemaRef,
1671 CXXRecordDecl *ClassDecl,
1672 QualType BaseType,
1673 const CXXBaseSpecifier *&DirectBaseSpec,
1674 const CXXBaseSpecifier *&VirtualBaseSpec) {
1675 // First, check for a direct base class.
1676 DirectBaseSpec = 0;
1677 for (CXXRecordDecl::base_class_const_iterator Base
1678 = ClassDecl->bases_begin();
1679 Base != ClassDecl->bases_end(); ++Base) {
1680 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1681 // We found a direct base of this type. That's what we're
1682 // initializing.
1683 DirectBaseSpec = &*Base;
1684 break;
1685 }
1686 }
1687
1688 // Check for a virtual base class.
1689 // FIXME: We might be able to short-circuit this if we know in advance that
1690 // there are no virtual bases.
1691 VirtualBaseSpec = 0;
1692 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1693 // We haven't found a base yet; search the class hierarchy for a
1694 // virtual base class.
1695 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1696 /*DetectVirtual=*/false);
1697 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1698 BaseType, Paths)) {
1699 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1700 Path != Paths.end(); ++Path) {
1701 if (Path->back().Base->isVirtual()) {
1702 VirtualBaseSpec = Path->back().Base;
1703 break;
1704 }
1705 }
1706 }
1707 }
1708
1709 return DirectBaseSpec || VirtualBaseSpec;
1710}
1711
Sebastian Redl6df65482011-09-24 17:48:25 +00001712/// \brief Handle a C++ member initializer using braced-init-list syntax.
1713MemInitResult
1714Sema::ActOnMemInitializer(Decl *ConstructorD,
1715 Scope *S,
1716 CXXScopeSpec &SS,
1717 IdentifierInfo *MemberOrBase,
1718 ParsedType TemplateTypeTy,
1719 SourceLocation IdLoc,
1720 Expr *InitList,
1721 SourceLocation EllipsisLoc) {
1722 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1723 IdLoc, MultiInitializer(InitList), EllipsisLoc);
1724}
1725
1726/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001727MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001728Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001729 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001730 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001731 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001732 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001733 SourceLocation IdLoc,
1734 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001735 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001736 SourceLocation RParenLoc,
1737 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001738 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1739 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs,
1740 RParenLoc),
1741 EllipsisLoc);
1742}
1743
1744/// \brief Handle a C++ member initializer.
1745MemInitResult
1746Sema::BuildMemInitializer(Decl *ConstructorD,
1747 Scope *S,
1748 CXXScopeSpec &SS,
1749 IdentifierInfo *MemberOrBase,
1750 ParsedType TemplateTypeTy,
1751 SourceLocation IdLoc,
1752 const MultiInitializer &Args,
1753 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001754 if (!ConstructorD)
1755 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001757 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001758
1759 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001760 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001761 if (!Constructor) {
1762 // The user wrote a constructor initializer on a function that is
1763 // not a C++ constructor. Ignore the error for now, because we may
1764 // have more member initializers coming; we'll diagnose it just
1765 // once in ActOnMemInitializers.
1766 return true;
1767 }
1768
1769 CXXRecordDecl *ClassDecl = Constructor->getParent();
1770
1771 // C++ [class.base.init]p2:
1772 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001773 // constructor's class and, if not found in that scope, are looked
1774 // up in the scope containing the constructor's definition.
1775 // [Note: if the constructor's class contains a member with the
1776 // same name as a direct or virtual base class of the class, a
1777 // mem-initializer-id naming the member or base class and composed
1778 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001779 // mem-initializer-id for the hidden base class may be specified
1780 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001781 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001782 // Look for a member, first.
1783 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001784 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001785 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001786 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001787 Member = dyn_cast<FieldDecl>(*Result.first);
Sebastian Redl6df65482011-09-24 17:48:25 +00001788
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001789 if (Member) {
1790 if (EllipsisLoc.isValid())
1791 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001792 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1793
1794 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001795 }
Sebastian Redl6df65482011-09-24 17:48:25 +00001796
Francois Pichet00eb3f92010-12-04 09:14:42 +00001797 // Handle anonymous union case.
1798 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001799 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1800 if (EllipsisLoc.isValid())
1801 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001802 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001803
Sebastian Redl6df65482011-09-24 17:48:25 +00001804 return BuildMemberInitializer(IndirectField, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001805 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001806 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001807 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001808 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001809 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001810 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001811
1812 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001813 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001814 } else {
1815 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1816 LookupParsedName(R, S, &SS);
1817
1818 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1819 if (!TyD) {
1820 if (R.isAmbiguous()) return true;
1821
John McCallfd225442010-04-09 19:01:14 +00001822 // We don't want access-control diagnostics here.
1823 R.suppressDiagnostics();
1824
Douglas Gregor7a886e12010-01-19 06:46:48 +00001825 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1826 bool NotUnknownSpecialization = false;
1827 DeclContext *DC = computeDeclContext(SS, false);
1828 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1829 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1830
1831 if (!NotUnknownSpecialization) {
1832 // When the scope specifier can refer to a member of an unknown
1833 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001834 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1835 SS.getWithLocInContext(Context),
1836 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001837 if (BaseType.isNull())
1838 return true;
1839
Douglas Gregor7a886e12010-01-19 06:46:48 +00001840 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001841 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001842 }
1843 }
1844
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001845 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001846 TypoCorrection Corr;
Douglas Gregor7a886e12010-01-19 06:46:48 +00001847 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001848 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1849 ClassDecl, false, CTC_NoKeywords))) {
1850 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1851 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1852 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001853 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001854 // We have found a non-static data member with a similar
1855 // name to what was typed; complain and initialize that
1856 // member.
1857 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001858 << MemberOrBase << true << CorrectedQuotedStr
1859 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001860 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001861 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001862
Sebastian Redl6df65482011-09-24 17:48:25 +00001863 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001864 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001865 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001866 const CXXBaseSpecifier *DirectBaseSpec;
1867 const CXXBaseSpecifier *VirtualBaseSpec;
1868 if (FindBaseInitializer(*this, ClassDecl,
1869 Context.getTypeDeclType(Type),
1870 DirectBaseSpec, VirtualBaseSpec)) {
1871 // We have found a direct or virtual base class with a
1872 // similar name to what was typed; complain and initialize
1873 // that base class.
1874 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001875 << MemberOrBase << false << CorrectedQuotedStr
1876 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001877
1878 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1879 : VirtualBaseSpec;
1880 Diag(BaseSpec->getSourceRange().getBegin(),
1881 diag::note_base_class_specified_here)
1882 << BaseSpec->getType()
1883 << BaseSpec->getSourceRange();
1884
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001885 TyD = Type;
1886 }
1887 }
1888 }
1889
Douglas Gregor7a886e12010-01-19 06:46:48 +00001890 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001891 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001892 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001893 return true;
1894 }
John McCall2b194412009-12-21 10:41:20 +00001895 }
1896
Douglas Gregor7a886e12010-01-19 06:46:48 +00001897 if (BaseType.isNull()) {
1898 BaseType = Context.getTypeDeclType(TyD);
1899 if (SS.isSet()) {
1900 NestedNameSpecifier *Qualifier =
1901 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001902
Douglas Gregor7a886e12010-01-19 06:46:48 +00001903 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001904 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001905 }
John McCall2b194412009-12-21 10:41:20 +00001906 }
1907 }
Mike Stump1eb44332009-09-09 15:08:12 +00001908
John McCalla93c9342009-12-07 02:54:59 +00001909 if (!TInfo)
1910 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001911
Sebastian Redl6df65482011-09-24 17:48:25 +00001912 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001913}
1914
Chandler Carruth81c64772011-09-03 01:14:15 +00001915/// Checks a member initializer expression for cases where reference (or
1916/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001917static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1918 Expr *Init,
1919 SourceLocation IdLoc) {
1920 QualType MemberTy = Member->getType();
1921
1922 // We only handle pointers and references currently.
1923 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1924 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1925 return;
1926
1927 const bool IsPointer = MemberTy->isPointerType();
1928 if (IsPointer) {
1929 if (const UnaryOperator *Op
1930 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1931 // The only case we're worried about with pointers requires taking the
1932 // address.
1933 if (Op->getOpcode() != UO_AddrOf)
1934 return;
1935
1936 Init = Op->getSubExpr();
1937 } else {
1938 // We only handle address-of expression initializers for pointers.
1939 return;
1940 }
1941 }
1942
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001943 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1944 // Taking the address of a temporary will be diagnosed as a hard error.
1945 if (IsPointer)
1946 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001947
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001948 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1949 << Member << Init->getSourceRange();
1950 } else if (const DeclRefExpr *DRE
1951 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1952 // We only warn when referring to a non-reference parameter declaration.
1953 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1954 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00001955 return;
1956
1957 S.Diag(Init->getExprLoc(),
1958 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1959 : diag::warn_bind_ref_member_to_parameter)
1960 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001961 } else {
1962 // Other initializers are fine.
1963 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001964 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001965
1966 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1967 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00001968}
1969
John McCallb4190042009-11-04 23:02:40 +00001970/// Checks an initializer expression for use of uninitialized fields, such as
1971/// containing the field that is being initialized. Returns true if there is an
1972/// uninitialized field was used an updates the SourceLocation parameter; false
1973/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001974static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001975 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001976 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001977 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1978
Nick Lewycky43ad1822010-06-15 07:32:55 +00001979 if (isa<CallExpr>(S)) {
1980 // Do not descend into function calls or constructors, as the use
1981 // of an uninitialized field may be valid. One would have to inspect
1982 // the contents of the function/ctor to determine if it is safe or not.
1983 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1984 // may be safe, depending on what the function/ctor does.
1985 return false;
1986 }
1987 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1988 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001989
1990 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1991 // The member expression points to a static data member.
1992 assert(VD->isStaticDataMember() &&
1993 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001994 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001995 return false;
1996 }
1997
1998 if (isa<EnumConstantDecl>(RhsField)) {
1999 // The member expression points to an enum.
2000 return false;
2001 }
2002
John McCallb4190042009-11-04 23:02:40 +00002003 if (RhsField == LhsField) {
2004 // Initializing a field with itself. Throw a warning.
2005 // But wait; there are exceptions!
2006 // Exception #1: The field may not belong to this record.
2007 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002008 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002009 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2010 // Even though the field matches, it does not belong to this record.
2011 return false;
2012 }
2013 // None of the exceptions triggered; return true to indicate an
2014 // uninitialized field was used.
2015 *L = ME->getMemberLoc();
2016 return true;
2017 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002018 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002019 // sizeof/alignof doesn't reference contents, do not warn.
2020 return false;
2021 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2022 // address-of doesn't reference contents (the pointer may be dereferenced
2023 // in the same expression but it would be rare; and weird).
2024 if (UOE->getOpcode() == UO_AddrOf)
2025 return false;
John McCallb4190042009-11-04 23:02:40 +00002026 }
John McCall7502c1d2011-02-13 04:07:26 +00002027 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002028 if (!*it) {
2029 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002030 continue;
2031 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002032 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2033 return true;
John McCallb4190042009-11-04 23:02:40 +00002034 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002035 return false;
John McCallb4190042009-11-04 23:02:40 +00002036}
2037
John McCallf312b1e2010-08-26 23:41:50 +00002038MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002039Sema::BuildMemberInitializer(ValueDecl *Member,
2040 const MultiInitializer &Args,
2041 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002042 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2043 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2044 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002045 "Member must be a FieldDecl or IndirectFieldDecl");
2046
Douglas Gregor464b2f02010-11-05 22:21:31 +00002047 if (Member->isInvalidDecl())
2048 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002049
John McCallb4190042009-11-04 23:02:40 +00002050 // Diagnose value-uses of fields to initialize themselves, e.g.
2051 // foo(foo)
2052 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002053 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00002054 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2055 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002056 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002057 Expr *Arg = *I;
2058 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2059 Arg = DIE->getInit();
2060 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002061 // FIXME: Return true in the case when other fields are used before being
2062 // uninitialized. For example, let this field be the i'th field. When
2063 // initializing the i'th field, throw a warning if any of the >= i'th
2064 // fields are used, as they are not yet initialized.
2065 // Right now we are only handling the case where the i'th field uses
2066 // itself in its initializer.
2067 Diag(L, diag::warn_field_is_uninit);
2068 }
2069 }
2070
Sebastian Redl6df65482011-09-24 17:48:25 +00002071 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002072
Chandler Carruth894aed92010-12-06 09:23:57 +00002073 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002074 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002075 // Can't check initialization for a member of dependent type or when
2076 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002077 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002078
John McCallf85e1932011-06-15 23:02:42 +00002079 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002080 } else {
2081 // Initialize the member.
2082 InitializedEntity MemberEntity =
2083 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2084 : InitializedEntity::InitializeMember(IndirectMember, 0);
2085 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002086 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2087 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002088
Sebastian Redl6df65482011-09-24 17:48:25 +00002089 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002090 if (MemberInit.isInvalid())
2091 return true;
2092
Sebastian Redl6df65482011-09-24 17:48:25 +00002093 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002094
2095 // C++0x [class.base.init]p7:
2096 // The initialization of each base and member constitutes a
2097 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002098 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002099 if (MemberInit.isInvalid())
2100 return true;
2101
2102 // If we are in a dependent context, template instantiation will
2103 // perform this type-checking again. Just save the arguments that we
2104 // received in a ParenListExpr.
2105 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2106 // of the information that we have about the member
2107 // initializer. However, deconstructing the ASTs is a dicey process,
2108 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002109 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002110 Init = Args.CreateInitExpr(Context,
2111 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002112 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002113 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002114 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2115 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002116 }
2117
Chandler Carruth894aed92010-12-06 09:23:57 +00002118 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002119 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002120 IdLoc, Args.getStartLoc(),
2121 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002122 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002123 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002124 IdLoc, Args.getStartLoc(),
2125 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002126 }
Eli Friedman59c04372009-07-29 19:44:27 +00002127}
2128
John McCallf312b1e2010-08-26 23:41:50 +00002129MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002130Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002131 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002132 SourceLocation NameLoc,
Sean Hunt41717662011-02-26 19:13:13 +00002133 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002134 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2135 if (!LangOpts.CPlusPlus0x)
2136 return Diag(Loc, diag::err_delegation_0x_only)
2137 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002138
Sean Hunt41717662011-02-26 19:13:13 +00002139 // Initialize the object.
2140 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2141 QualType(ClassDecl->getTypeForDecl(), 0));
2142 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002143 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2144 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002145
Sebastian Redl6df65482011-09-24 17:48:25 +00002146 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002147 if (DelegationInit.isInvalid())
2148 return true;
2149
2150 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00002151 CXXConstructorDecl *Constructor
2152 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00002153 assert(Constructor && "Delegating constructor with no target?");
2154
Sebastian Redl6df65482011-09-24 17:48:25 +00002155 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002156
2157 // C++0x [class.base.init]p7:
2158 // The initialization of each base and member constitutes a
2159 // full-expression.
2160 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2161 if (DelegationInit.isInvalid())
2162 return true;
2163
Manuel Klimek0d9106f2011-06-22 20:02:16 +00002164 assert(!CurContext->isDependentContext());
Sebastian Redl6df65482011-09-24 17:48:25 +00002165 return new (Context) CXXCtorInitializer(Context, Loc, Args.getStartLoc(),
2166 Constructor,
Sean Hunt41717662011-02-26 19:13:13 +00002167 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002168 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002169}
2170
2171MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002172Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002173 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002174 CXXRecordDecl *ClassDecl,
2175 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002176 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002177
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002178 SourceLocation BaseLoc
2179 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002180
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002181 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2182 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2183 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2184
2185 // C++ [class.base.init]p2:
2186 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002187 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002188 // of that class, the mem-initializer is ill-formed. A
2189 // mem-initializer-list can initialize a base class using any
2190 // name that denotes that base class type.
2191 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2192
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002193 if (EllipsisLoc.isValid()) {
2194 // This is a pack expansion.
2195 if (!BaseType->containsUnexpandedParameterPack()) {
2196 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002197 << SourceRange(BaseLoc, Args.getEndLoc());
2198
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002199 EllipsisLoc = SourceLocation();
2200 }
2201 } else {
2202 // Check for any unexpanded parameter packs.
2203 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2204 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002205
2206 if (Args.DiagnoseUnexpandedParameterPack(*this))
2207 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002208 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002209
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002210 // Check for direct and virtual base classes.
2211 const CXXBaseSpecifier *DirectBaseSpec = 0;
2212 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2213 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002214 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2215 BaseType))
Sebastian Redl6df65482011-09-24 17:48:25 +00002216 return BuildDelegatingInitializer(BaseTInfo, Args, BaseLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002217
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002218 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2219 VirtualBaseSpec);
2220
2221 // C++ [base.class.init]p2:
2222 // Unless the mem-initializer-id names a nonstatic data member of the
2223 // constructor's class or a direct or virtual base of that class, the
2224 // mem-initializer is ill-formed.
2225 if (!DirectBaseSpec && !VirtualBaseSpec) {
2226 // If the class has any dependent bases, then it's possible that
2227 // one of those types will resolve to the same type as
2228 // BaseType. Therefore, just treat this as a dependent base
2229 // class initialization. FIXME: Should we try to check the
2230 // initialization anyway? It seems odd.
2231 if (ClassDecl->hasAnyDependentBases())
2232 Dependent = true;
2233 else
2234 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2235 << BaseType << Context.getTypeDeclType(ClassDecl)
2236 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2237 }
2238 }
2239
2240 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002241 // Can't check initialization for a base of dependent type or when
2242 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002243 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002244
John McCallf85e1932011-06-15 23:02:42 +00002245 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Sebastian Redl6df65482011-09-24 17:48:25 +00002247 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2248 /*IsVirtual=*/false,
2249 Args.getStartLoc(), BaseInit,
2250 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002251 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002252
2253 // C++ [base.class.init]p2:
2254 // If a mem-initializer-id is ambiguous because it designates both
2255 // a direct non-virtual base class and an inherited virtual base
2256 // class, the mem-initializer is ill-formed.
2257 if (DirectBaseSpec && VirtualBaseSpec)
2258 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002259 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002260
2261 CXXBaseSpecifier *BaseSpec
2262 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2263 if (!BaseSpec)
2264 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2265
2266 // Initialize the base.
2267 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002268 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002269 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002270 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2271 Args.getEndLoc());
2272
2273 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002274 if (BaseInit.isInvalid())
2275 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002276
Sebastian Redl6df65482011-09-24 17:48:25 +00002277 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2278
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002279 // C++0x [class.base.init]p7:
2280 // The initialization of each base and member constitutes a
2281 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002282 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002283 if (BaseInit.isInvalid())
2284 return true;
2285
2286 // If we are in a dependent context, template instantiation will
2287 // perform this type-checking again. Just save the arguments that we
2288 // received in a ParenListExpr.
2289 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2290 // of the information that we have about the base
2291 // initializer. However, deconstructing the ASTs is a dicey process,
2292 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002293 if (CurContext->isDependentContext())
2294 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002295
Sean Huntcbb67482011-01-08 20:30:50 +00002296 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002297 BaseSpec->isVirtual(),
2298 Args.getStartLoc(),
2299 BaseInit.takeAs<Expr>(),
2300 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002301}
2302
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002303// Create a static_cast\<T&&>(expr).
2304static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2305 QualType ExprType = E->getType();
2306 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2307 SourceLocation ExprLoc = E->getLocStart();
2308 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2309 TargetType, ExprLoc);
2310
2311 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2312 SourceRange(ExprLoc, ExprLoc),
2313 E->getSourceRange()).take();
2314}
2315
Anders Carlssone5ef7402010-04-23 03:10:23 +00002316/// ImplicitInitializerKind - How an implicit base or member initializer should
2317/// initialize its base or member.
2318enum ImplicitInitializerKind {
2319 IIK_Default,
2320 IIK_Copy,
2321 IIK_Move
2322};
2323
Anders Carlssondefefd22010-04-23 02:00:02 +00002324static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002325BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002326 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002327 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002328 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002329 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002330 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002331 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2332 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002333
John McCall60d7b3a2010-08-24 06:29:42 +00002334 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002335
2336 switch (ImplicitInitKind) {
2337 case IIK_Default: {
2338 InitializationKind InitKind
2339 = InitializationKind::CreateDefault(Constructor->getLocation());
2340 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2341 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002342 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002343 break;
2344 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002345
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002346 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002347 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002348 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002349 ParmVarDecl *Param = Constructor->getParamDecl(0);
2350 QualType ParamType = Param->getType().getNonReferenceType();
2351
2352 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002353 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002354 Constructor->getLocation(), ParamType,
2355 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002356
Anders Carlssonc7957502010-04-24 22:02:54 +00002357 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002358 QualType ArgTy =
2359 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2360 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002361
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002362 if (Moving) {
2363 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2364 }
2365
John McCallf871d0c2010-08-07 06:22:56 +00002366 CXXCastPath BasePath;
2367 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002368 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2369 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002370 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002371 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002372
Anders Carlssone5ef7402010-04-23 03:10:23 +00002373 InitializationKind InitKind
2374 = InitializationKind::CreateDirect(Constructor->getLocation(),
2375 SourceLocation(), SourceLocation());
2376 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2377 &CopyCtorArg, 1);
2378 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002379 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002380 break;
2381 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002382 }
John McCall9ae2f072010-08-23 23:25:46 +00002383
Douglas Gregor53c374f2010-12-07 00:41:46 +00002384 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002385 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002386 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002387
Anders Carlssondefefd22010-04-23 02:00:02 +00002388 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002389 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002390 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2391 SourceLocation()),
2392 BaseSpec->isVirtual(),
2393 SourceLocation(),
2394 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002395 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002396 SourceLocation());
2397
Anders Carlssondefefd22010-04-23 02:00:02 +00002398 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002399}
2400
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002401static bool RefersToRValueRef(Expr *MemRef) {
2402 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2403 return Referenced->getType()->isRValueReferenceType();
2404}
2405
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002406static bool
2407BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002408 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002409 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002410 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002411 if (Field->isInvalidDecl())
2412 return true;
2413
Chandler Carruthf186b542010-06-29 23:50:44 +00002414 SourceLocation Loc = Constructor->getLocation();
2415
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002416 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2417 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002418 ParmVarDecl *Param = Constructor->getParamDecl(0);
2419 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002420
2421 // Suppress copying zero-width bitfields.
2422 if (const Expr *Width = Field->getBitWidth())
2423 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2424 return false;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002425
2426 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00002427 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002428 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002429
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002430 if (Moving) {
2431 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2432 }
2433
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002434 // Build a reference to this field within the parameter.
2435 CXXScopeSpec SS;
2436 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2437 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002438 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2439 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002440 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002441 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002442 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002443 ParamType, Loc,
2444 /*IsArrow=*/false,
2445 SS,
2446 /*FirstQualifierInScope=*/0,
2447 MemberLookup,
2448 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002449 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002450 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002451
2452 // C++11 [class.copy]p15:
2453 // - if a member m has rvalue reference type T&&, it is direct-initialized
2454 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002455 if (RefersToRValueRef(CtorArg.get())) {
2456 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002457 }
2458
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002459 // When the field we are copying is an array, create index variables for
2460 // each dimension of the array. We use these index variables to subscript
2461 // the source array, and other clients (e.g., CodeGen) will perform the
2462 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002463 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002464 QualType BaseType = Field->getType();
2465 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002466 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002467 while (const ConstantArrayType *Array
2468 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002469 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002470 // Create the iteration variable for this array index.
2471 IdentifierInfo *IterationVarName = 0;
2472 {
2473 llvm::SmallString<8> Str;
2474 llvm::raw_svector_ostream OS(Str);
2475 OS << "__i" << IndexVariables.size();
2476 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2477 }
2478 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002479 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002480 IterationVarName, SizeType,
2481 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002482 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002483 IndexVariables.push_back(IterationVar);
2484
2485 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002486 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002487 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002488 assert(!IterationVarRef.isInvalid() &&
2489 "Reference to invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002490
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002491 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002492 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002493 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002494 Loc);
2495 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002496 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002497
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002498 BaseType = Array->getElementType();
2499 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002500
2501 // The array subscript expression is an lvalue, which is wrong for moving.
2502 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002503 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002504
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002505 // Construct the entity that we will be initializing. For an array, this
2506 // will be first element in the array, which may require several levels
2507 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002508 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002509 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002510 if (Indirect)
2511 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2512 else
2513 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002514 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2515 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2516 0,
2517 Entities.back()));
2518
2519 // Direct-initialize to use the copy constructor.
2520 InitializationKind InitKind =
2521 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2522
Sebastian Redl74e611a2011-09-04 18:14:28 +00002523 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002524 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002525 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002526
John McCall60d7b3a2010-08-24 06:29:42 +00002527 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002528 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002529 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002530 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002531 if (MemberInit.isInvalid())
2532 return true;
2533
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002534 if (Indirect) {
2535 assert(IndexVariables.size() == 0 &&
2536 "Indirect field improperly initialized");
2537 CXXMemberInit
2538 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2539 Loc, Loc,
2540 MemberInit.takeAs<Expr>(),
2541 Loc);
2542 } else
2543 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2544 Loc, MemberInit.takeAs<Expr>(),
2545 Loc,
2546 IndexVariables.data(),
2547 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002548 return false;
2549 }
2550
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002551 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2552
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002553 QualType FieldBaseElementType =
2554 SemaRef.Context.getBaseElementType(Field->getType());
2555
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002556 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002557 InitializedEntity InitEntity
2558 = Indirect? InitializedEntity::InitializeMember(Indirect)
2559 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002560 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002561 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002562
2563 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002564 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002565 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002566
Douglas Gregor53c374f2010-12-07 00:41:46 +00002567 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002568 if (MemberInit.isInvalid())
2569 return true;
2570
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002571 if (Indirect)
2572 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2573 Indirect, Loc,
2574 Loc,
2575 MemberInit.get(),
2576 Loc);
2577 else
2578 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2579 Field, Loc, Loc,
2580 MemberInit.get(),
2581 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002582 return false;
2583 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002584
Sean Hunt1f2f3842011-05-17 00:19:05 +00002585 if (!Field->getParent()->isUnion()) {
2586 if (FieldBaseElementType->isReferenceType()) {
2587 SemaRef.Diag(Constructor->getLocation(),
2588 diag::err_uninitialized_member_in_ctor)
2589 << (int)Constructor->isImplicit()
2590 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2591 << 0 << Field->getDeclName();
2592 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2593 return true;
2594 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002595
Sean Hunt1f2f3842011-05-17 00:19:05 +00002596 if (FieldBaseElementType.isConstQualified()) {
2597 SemaRef.Diag(Constructor->getLocation(),
2598 diag::err_uninitialized_member_in_ctor)
2599 << (int)Constructor->isImplicit()
2600 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2601 << 1 << Field->getDeclName();
2602 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2603 return true;
2604 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002605 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002606
John McCallf85e1932011-06-15 23:02:42 +00002607 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2608 FieldBaseElementType->isObjCRetainableType() &&
2609 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2610 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2611 // Instant objects:
2612 // Default-initialize Objective-C pointers to NULL.
2613 CXXMemberInit
2614 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2615 Loc, Loc,
2616 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2617 Loc);
2618 return false;
2619 }
2620
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002621 // Nothing to initialize.
2622 CXXMemberInit = 0;
2623 return false;
2624}
John McCallf1860e52010-05-20 23:23:51 +00002625
2626namespace {
2627struct BaseAndFieldInfo {
2628 Sema &S;
2629 CXXConstructorDecl *Ctor;
2630 bool AnyErrorsInInits;
2631 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002632 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002633 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002634
2635 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2636 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002637 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2638 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002639 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002640 else if (Generated && Ctor->isMoveConstructor())
2641 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002642 else
2643 IIK = IIK_Default;
2644 }
2645};
2646}
2647
Richard Smitha4950662011-09-19 13:34:43 +00002648/// \brief Determine whether the given indirect field declaration is somewhere
2649/// within an anonymous union.
2650static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2651 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2652 CEnd = F->chain_end();
2653 C != CEnd; ++C)
2654 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2655 if (Record->isUnion())
2656 return true;
2657
2658 return false;
2659}
2660
Richard Smith7a614d82011-06-11 17:19:42 +00002661static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002662 FieldDecl *Field,
2663 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002664
Chandler Carruthe861c602010-06-30 02:59:29 +00002665 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002666 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002667 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002668 return false;
2669 }
2670
Richard Smith7a614d82011-06-11 17:19:42 +00002671 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2672 // has a brace-or-equal-initializer, the entity is initialized as specified
2673 // in [dcl.init].
2674 if (Field->hasInClassInitializer()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002675 CXXCtorInitializer *Init;
2676 if (Indirect)
2677 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2678 SourceLocation(),
2679 SourceLocation(), 0,
2680 SourceLocation());
2681 else
2682 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2683 SourceLocation(),
2684 SourceLocation(), 0,
2685 SourceLocation());
2686 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002687 return false;
2688 }
2689
Richard Smithc115f632011-09-18 11:14:50 +00002690 // Don't build an implicit initializer for union members if none was
2691 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002692 if (Field->getParent()->isUnion() ||
2693 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002694 return false;
2695
John McCallf1860e52010-05-20 23:23:51 +00002696 // Don't try to build an implicit initializer if there were semantic
2697 // errors in any of the initializers (and therefore we might be
2698 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002699 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002700 return false;
2701
Sean Huntcbb67482011-01-08 20:30:50 +00002702 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002703 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2704 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002705 return true;
John McCallf1860e52010-05-20 23:23:51 +00002706
Francois Pichet00eb3f92010-12-04 09:14:42 +00002707 if (Init)
2708 Info.AllToInit.push_back(Init);
2709
John McCallf1860e52010-05-20 23:23:51 +00002710 return false;
2711}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002712
2713bool
2714Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2715 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002716 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002717 Constructor->setNumCtorInitializers(1);
2718 CXXCtorInitializer **initializer =
2719 new (Context) CXXCtorInitializer*[1];
2720 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2721 Constructor->setCtorInitializers(initializer);
2722
Sean Huntb76af9c2011-05-03 23:05:34 +00002723 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2724 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2725 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2726 }
2727
Sean Huntc1598702011-05-05 00:05:47 +00002728 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002729
Sean Hunt059ce0d2011-05-01 07:04:31 +00002730 return false;
2731}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002732
John McCallb77115d2011-06-17 00:18:42 +00002733bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2734 CXXCtorInitializer **Initializers,
2735 unsigned NumInitializers,
2736 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002737 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002738 // Just store the initializers as written, they will be checked during
2739 // instantiation.
2740 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002741 Constructor->setNumCtorInitializers(NumInitializers);
2742 CXXCtorInitializer **baseOrMemberInitializers =
2743 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002744 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002745 NumInitializers * sizeof(CXXCtorInitializer*));
2746 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002747 }
2748
2749 return false;
2750 }
2751
John McCallf1860e52010-05-20 23:23:51 +00002752 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002753
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002754 // We need to build the initializer AST according to order of construction
2755 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002756 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002757 if (!ClassDecl)
2758 return true;
2759
Eli Friedman80c30da2009-11-09 19:20:36 +00002760 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002762 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002763 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002764
2765 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002766 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002767 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002768 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002769 }
2770
Anders Carlsson711f34a2010-04-21 19:52:01 +00002771 // Keep track of the direct virtual bases.
2772 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2773 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2774 E = ClassDecl->bases_end(); I != E; ++I) {
2775 if (I->isVirtual())
2776 DirectVBases.insert(I);
2777 }
2778
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002779 // Push virtual bases before others.
2780 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2781 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2782
Sean Huntcbb67482011-01-08 20:30:50 +00002783 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002784 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2785 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002786 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002787 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002788 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002789 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002790 VBase, IsInheritedVirtualBase,
2791 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002792 HadError = true;
2793 continue;
2794 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002795
John McCallf1860e52010-05-20 23:23:51 +00002796 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002797 }
2798 }
Mike Stump1eb44332009-09-09 15:08:12 +00002799
John McCallf1860e52010-05-20 23:23:51 +00002800 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002801 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2802 E = ClassDecl->bases_end(); Base != E; ++Base) {
2803 // Virtuals are in the virtual base list and already constructed.
2804 if (Base->isVirtual())
2805 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002806
Sean Huntcbb67482011-01-08 20:30:50 +00002807 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002808 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2809 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002810 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002811 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002812 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002813 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002814 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002815 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002816 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002817 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002818
John McCallf1860e52010-05-20 23:23:51 +00002819 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002820 }
2821 }
Mike Stump1eb44332009-09-09 15:08:12 +00002822
John McCallf1860e52010-05-20 23:23:51 +00002823 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002824 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2825 MemEnd = ClassDecl->decls_end();
2826 Mem != MemEnd; ++Mem) {
2827 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2828 if (F->getType()->isIncompleteArrayType()) {
2829 assert(ClassDecl->hasFlexibleArrayMember() &&
2830 "Incomplete array type is not valid");
2831 continue;
2832 }
2833
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002834 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002835 // handle anonymous struct/union fields based on their individual
2836 // indirect fields.
2837 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2838 continue;
2839
2840 if (CollectFieldInitializer(*this, Info, F))
2841 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002842 continue;
2843 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002844
2845 // Beyond this point, we only consider default initialization.
2846 if (Info.IIK != IIK_Default)
2847 continue;
2848
2849 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2850 if (F->getType()->isIncompleteArrayType()) {
2851 assert(ClassDecl->hasFlexibleArrayMember() &&
2852 "Incomplete array type is not valid");
2853 continue;
2854 }
2855
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002856 // Initialize each field of an anonymous struct individually.
2857 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2858 HadError = true;
2859
2860 continue;
2861 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002862 }
Mike Stump1eb44332009-09-09 15:08:12 +00002863
John McCallf1860e52010-05-20 23:23:51 +00002864 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002865 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002866 Constructor->setNumCtorInitializers(NumInitializers);
2867 CXXCtorInitializer **baseOrMemberInitializers =
2868 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002869 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002870 NumInitializers * sizeof(CXXCtorInitializer*));
2871 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002872
John McCallef027fe2010-03-16 21:39:52 +00002873 // Constructors implicitly reference the base and member
2874 // destructors.
2875 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2876 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002877 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002878
2879 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002880}
2881
Eli Friedman6347f422009-07-21 19:28:10 +00002882static void *GetKeyForTopLevelField(FieldDecl *Field) {
2883 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002884 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002885 if (RT->getDecl()->isAnonymousStructOrUnion())
2886 return static_cast<void *>(RT->getDecl());
2887 }
2888 return static_cast<void *>(Field);
2889}
2890
Anders Carlssonea356fb2010-04-02 05:42:15 +00002891static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002892 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002893}
2894
Anders Carlssonea356fb2010-04-02 05:42:15 +00002895static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002896 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002897 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002898 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002899
Eli Friedman6347f422009-07-21 19:28:10 +00002900 // For fields injected into the class via declaration of an anonymous union,
2901 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002902 FieldDecl *Field = Member->getAnyMember();
2903
John McCall3c3ccdb2010-04-10 09:28:51 +00002904 // If the field is a member of an anonymous struct or union, our key
2905 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002906 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002907 if (RD->isAnonymousStructOrUnion()) {
2908 while (true) {
2909 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2910 if (Parent->isAnonymousStructOrUnion())
2911 RD = Parent;
2912 else
2913 break;
2914 }
2915
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002916 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002917 }
Mike Stump1eb44332009-09-09 15:08:12 +00002918
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002919 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002920}
2921
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002922static void
2923DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002924 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002925 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002926 unsigned NumInits) {
2927 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002928 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002930 // Don't check initializers order unless the warning is enabled at the
2931 // location of at least one initializer.
2932 bool ShouldCheckOrder = false;
2933 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002934 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002935 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2936 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00002937 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002938 ShouldCheckOrder = true;
2939 break;
2940 }
2941 }
2942 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002943 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002944
John McCalld6ca8da2010-04-10 07:37:23 +00002945 // Build the list of bases and members in the order that they'll
2946 // actually be initialized. The explicit initializers should be in
2947 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002948 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002949
Anders Carlsson071d6102010-04-02 03:38:04 +00002950 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2951
John McCalld6ca8da2010-04-10 07:37:23 +00002952 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002953 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002954 ClassDecl->vbases_begin(),
2955 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002956 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002957
John McCalld6ca8da2010-04-10 07:37:23 +00002958 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002959 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002960 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002961 if (Base->isVirtual())
2962 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002963 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002964 }
Mike Stump1eb44332009-09-09 15:08:12 +00002965
John McCalld6ca8da2010-04-10 07:37:23 +00002966 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002967 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2968 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002969 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002970
John McCalld6ca8da2010-04-10 07:37:23 +00002971 unsigned NumIdealInits = IdealInitKeys.size();
2972 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002973
Sean Huntcbb67482011-01-08 20:30:50 +00002974 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002975 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002976 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002977 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002978
2979 // Scan forward to try to find this initializer in the idealized
2980 // initializers list.
2981 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2982 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002983 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002984
2985 // If we didn't find this initializer, it must be because we
2986 // scanned past it on a previous iteration. That can only
2987 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002988 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002989 Sema::SemaDiagnosticBuilder D =
2990 SemaRef.Diag(PrevInit->getSourceLocation(),
2991 diag::warn_initializer_out_of_order);
2992
Francois Pichet00eb3f92010-12-04 09:14:42 +00002993 if (PrevInit->isAnyMemberInitializer())
2994 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002995 else
2996 D << 1 << PrevInit->getBaseClassInfo()->getType();
2997
Francois Pichet00eb3f92010-12-04 09:14:42 +00002998 if (Init->isAnyMemberInitializer())
2999 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003000 else
3001 D << 1 << Init->getBaseClassInfo()->getType();
3002
3003 // Move back to the initializer's location in the ideal list.
3004 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3005 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003006 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003007
3008 assert(IdealIndex != NumIdealInits &&
3009 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003010 }
John McCalld6ca8da2010-04-10 07:37:23 +00003011
3012 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003013 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003014}
3015
John McCall3c3ccdb2010-04-10 09:28:51 +00003016namespace {
3017bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003018 CXXCtorInitializer *Init,
3019 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003020 if (!PrevInit) {
3021 PrevInit = Init;
3022 return false;
3023 }
3024
3025 if (FieldDecl *Field = Init->getMember())
3026 S.Diag(Init->getSourceLocation(),
3027 diag::err_multiple_mem_initialization)
3028 << Field->getDeclName()
3029 << Init->getSourceRange();
3030 else {
John McCallf4c73712011-01-19 06:33:43 +00003031 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003032 assert(BaseClass && "neither field nor base");
3033 S.Diag(Init->getSourceLocation(),
3034 diag::err_multiple_base_initialization)
3035 << QualType(BaseClass, 0)
3036 << Init->getSourceRange();
3037 }
3038 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3039 << 0 << PrevInit->getSourceRange();
3040
3041 return true;
3042}
3043
Sean Huntcbb67482011-01-08 20:30:50 +00003044typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003045typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3046
3047bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003048 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003049 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003050 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003051 RecordDecl *Parent = Field->getParent();
3052 if (!Parent->isAnonymousStructOrUnion())
3053 return false;
3054
3055 NamedDecl *Child = Field;
3056 do {
3057 if (Parent->isUnion()) {
3058 UnionEntry &En = Unions[Parent];
3059 if (En.first && En.first != Child) {
3060 S.Diag(Init->getSourceLocation(),
3061 diag::err_multiple_mem_union_initialization)
3062 << Field->getDeclName()
3063 << Init->getSourceRange();
3064 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3065 << 0 << En.second->getSourceRange();
3066 return true;
3067 } else if (!En.first) {
3068 En.first = Child;
3069 En.second = Init;
3070 }
3071 }
3072
3073 Child = Parent;
3074 Parent = cast<RecordDecl>(Parent->getDeclContext());
3075 } while (Parent->isAnonymousStructOrUnion());
3076
3077 return false;
3078}
3079}
3080
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003081/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003082void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003083 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003084 CXXCtorInitializer **meminits,
3085 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003086 bool AnyErrors) {
3087 if (!ConstructorDecl)
3088 return;
3089
3090 AdjustDeclIfTemplate(ConstructorDecl);
3091
3092 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003093 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003094
3095 if (!Constructor) {
3096 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3097 return;
3098 }
3099
Sean Huntcbb67482011-01-08 20:30:50 +00003100 CXXCtorInitializer **MemInits =
3101 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003102
3103 // Mapping for the duplicate initializers check.
3104 // For member initializers, this is keyed with a FieldDecl*.
3105 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003106 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003107
3108 // Mapping for the inconsistent anonymous-union initializers check.
3109 RedundantUnionMap MemberUnions;
3110
Anders Carlssonea356fb2010-04-02 05:42:15 +00003111 bool HadError = false;
3112 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003113 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003114
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003115 // Set the source order index.
3116 Init->setSourceOrder(i);
3117
Francois Pichet00eb3f92010-12-04 09:14:42 +00003118 if (Init->isAnyMemberInitializer()) {
3119 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003120 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3121 CheckRedundantUnionInit(*this, Init, MemberUnions))
3122 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003123 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003124 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3125 if (CheckRedundantInit(*this, Init, Members[Key]))
3126 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003127 } else {
3128 assert(Init->isDelegatingInitializer());
3129 // This must be the only initializer
3130 if (i != 0 || NumMemInits > 1) {
3131 Diag(MemInits[0]->getSourceLocation(),
3132 diag::err_delegating_initializer_alone)
3133 << MemInits[0]->getSourceRange();
3134 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003135 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003136 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003137 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003138 // Return immediately as the initializer is set.
3139 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003140 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003141 }
3142
Anders Carlssonea356fb2010-04-02 05:42:15 +00003143 if (HadError)
3144 return;
3145
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003146 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003147
Sean Huntcbb67482011-01-08 20:30:50 +00003148 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003149}
3150
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003151void
John McCallef027fe2010-03-16 21:39:52 +00003152Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3153 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003154 // Ignore dependent contexts. Also ignore unions, since their members never
3155 // have destructors implicitly called.
3156 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003157 return;
John McCall58e6f342010-03-16 05:22:47 +00003158
3159 // FIXME: all the access-control diagnostics are positioned on the
3160 // field/base declaration. That's probably good; that said, the
3161 // user might reasonably want to know why the destructor is being
3162 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003163
Anders Carlsson9f853df2009-11-17 04:44:12 +00003164 // Non-static data members.
3165 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3166 E = ClassDecl->field_end(); I != E; ++I) {
3167 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003168 if (Field->isInvalidDecl())
3169 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003170 QualType FieldType = Context.getBaseElementType(Field->getType());
3171
3172 const RecordType* RT = FieldType->getAs<RecordType>();
3173 if (!RT)
3174 continue;
3175
3176 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003177 if (FieldClassDecl->isInvalidDecl())
3178 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003179 if (FieldClassDecl->hasTrivialDestructor())
3180 continue;
3181
Douglas Gregordb89f282010-07-01 22:47:18 +00003182 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003183 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003184 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003185 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003186 << Field->getDeclName()
3187 << FieldType);
3188
John McCallef027fe2010-03-16 21:39:52 +00003189 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003190 }
3191
John McCall58e6f342010-03-16 05:22:47 +00003192 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3193
Anders Carlsson9f853df2009-11-17 04:44:12 +00003194 // Bases.
3195 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3196 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003197 // Bases are always records in a well-formed non-dependent class.
3198 const RecordType *RT = Base->getType()->getAs<RecordType>();
3199
3200 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003201 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003202 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003203
John McCall58e6f342010-03-16 05:22:47 +00003204 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003205 // If our base class is invalid, we probably can't get its dtor anyway.
3206 if (BaseClassDecl->isInvalidDecl())
3207 continue;
3208 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003209 if (BaseClassDecl->hasTrivialDestructor())
3210 continue;
John McCall58e6f342010-03-16 05:22:47 +00003211
Douglas Gregordb89f282010-07-01 22:47:18 +00003212 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003213 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003214
3215 // FIXME: caret should be on the start of the class name
3216 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003217 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003218 << Base->getType()
3219 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003220
John McCallef027fe2010-03-16 21:39:52 +00003221 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003222 }
3223
3224 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003225 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3226 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003227
3228 // Bases are always records in a well-formed non-dependent class.
3229 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3230
3231 // Ignore direct virtual bases.
3232 if (DirectVirtualBases.count(RT))
3233 continue;
3234
John McCall58e6f342010-03-16 05:22:47 +00003235 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003236 // If our base class is invalid, we probably can't get its dtor anyway.
3237 if (BaseClassDecl->isInvalidDecl())
3238 continue;
3239 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003240 if (BaseClassDecl->hasTrivialDestructor())
3241 continue;
John McCall58e6f342010-03-16 05:22:47 +00003242
Douglas Gregordb89f282010-07-01 22:47:18 +00003243 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003244 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003245 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003246 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003247 << VBase->getType());
3248
John McCallef027fe2010-03-16 21:39:52 +00003249 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003250 }
3251}
3252
John McCalld226f652010-08-21 09:40:31 +00003253void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003254 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003255 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Mike Stump1eb44332009-09-09 15:08:12 +00003257 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003258 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003259 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003260}
3261
Mike Stump1eb44332009-09-09 15:08:12 +00003262bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003263 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003264 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003265 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003266 else
John McCall94c3b562010-08-18 09:41:07 +00003267 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003268}
3269
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003270bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003271 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003272 if (!getLangOptions().CPlusPlus)
3273 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Anders Carlsson11f21a02009-03-23 19:10:31 +00003275 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003276 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Ted Kremenek6217b802009-07-29 21:53:49 +00003278 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003279 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003280 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003281 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003283 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003284 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003285 }
Mike Stump1eb44332009-09-09 15:08:12 +00003286
Ted Kremenek6217b802009-07-29 21:53:49 +00003287 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003288 if (!RT)
3289 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003290
John McCall86ff3082010-02-04 22:26:26 +00003291 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003292
John McCall94c3b562010-08-18 09:41:07 +00003293 // We can't answer whether something is abstract until it has a
3294 // definition. If it's currently being defined, we'll walk back
3295 // over all the declarations when we have a full definition.
3296 const CXXRecordDecl *Def = RD->getDefinition();
3297 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003298 return false;
3299
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003300 if (!RD->isAbstract())
3301 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003303 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003304 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003305
John McCall94c3b562010-08-18 09:41:07 +00003306 return true;
3307}
3308
3309void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3310 // Check if we've already emitted the list of pure virtual functions
3311 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003312 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003313 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003315 CXXFinalOverriderMap FinalOverriders;
3316 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003317
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003318 // Keep a set of seen pure methods so we won't diagnose the same method
3319 // more than once.
3320 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3321
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003322 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3323 MEnd = FinalOverriders.end();
3324 M != MEnd;
3325 ++M) {
3326 for (OverridingMethods::iterator SO = M->second.begin(),
3327 SOEnd = M->second.end();
3328 SO != SOEnd; ++SO) {
3329 // C++ [class.abstract]p4:
3330 // A class is abstract if it contains or inherits at least one
3331 // pure virtual function for which the final overrider is pure
3332 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003333
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003334 //
3335 if (SO->second.size() != 1)
3336 continue;
3337
3338 if (!SO->second.front().Method->isPure())
3339 continue;
3340
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003341 if (!SeenPureMethods.insert(SO->second.front().Method))
3342 continue;
3343
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003344 Diag(SO->second.front().Method->getLocation(),
3345 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003346 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003347 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003348 }
3349
3350 if (!PureVirtualClassDiagSet)
3351 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3352 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003353}
3354
Anders Carlsson8211eff2009-03-24 01:19:16 +00003355namespace {
John McCall94c3b562010-08-18 09:41:07 +00003356struct AbstractUsageInfo {
3357 Sema &S;
3358 CXXRecordDecl *Record;
3359 CanQualType AbstractType;
3360 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003361
John McCall94c3b562010-08-18 09:41:07 +00003362 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3363 : S(S), Record(Record),
3364 AbstractType(S.Context.getCanonicalType(
3365 S.Context.getTypeDeclType(Record))),
3366 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003367
John McCall94c3b562010-08-18 09:41:07 +00003368 void DiagnoseAbstractType() {
3369 if (Invalid) return;
3370 S.DiagnoseAbstractType(Record);
3371 Invalid = true;
3372 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003373
John McCall94c3b562010-08-18 09:41:07 +00003374 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3375};
3376
3377struct CheckAbstractUsage {
3378 AbstractUsageInfo &Info;
3379 const NamedDecl *Ctx;
3380
3381 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3382 : Info(Info), Ctx(Ctx) {}
3383
3384 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3385 switch (TL.getTypeLocClass()) {
3386#define ABSTRACT_TYPELOC(CLASS, PARENT)
3387#define TYPELOC(CLASS, PARENT) \
3388 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3389#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003390 }
John McCall94c3b562010-08-18 09:41:07 +00003391 }
Mike Stump1eb44332009-09-09 15:08:12 +00003392
John McCall94c3b562010-08-18 09:41:07 +00003393 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3394 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3395 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003396 if (!TL.getArg(I))
3397 continue;
3398
John McCall94c3b562010-08-18 09:41:07 +00003399 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3400 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003401 }
John McCall94c3b562010-08-18 09:41:07 +00003402 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003403
John McCall94c3b562010-08-18 09:41:07 +00003404 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3405 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3406 }
Mike Stump1eb44332009-09-09 15:08:12 +00003407
John McCall94c3b562010-08-18 09:41:07 +00003408 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3409 // Visit the type parameters from a permissive context.
3410 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3411 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3412 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3413 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3414 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3415 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003416 }
John McCall94c3b562010-08-18 09:41:07 +00003417 }
Mike Stump1eb44332009-09-09 15:08:12 +00003418
John McCall94c3b562010-08-18 09:41:07 +00003419 // Visit pointee types from a permissive context.
3420#define CheckPolymorphic(Type) \
3421 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3422 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3423 }
3424 CheckPolymorphic(PointerTypeLoc)
3425 CheckPolymorphic(ReferenceTypeLoc)
3426 CheckPolymorphic(MemberPointerTypeLoc)
3427 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003428 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003429
John McCall94c3b562010-08-18 09:41:07 +00003430 /// Handle all the types we haven't given a more specific
3431 /// implementation for above.
3432 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3433 // Every other kind of type that we haven't called out already
3434 // that has an inner type is either (1) sugar or (2) contains that
3435 // inner type in some way as a subobject.
3436 if (TypeLoc Next = TL.getNextTypeLoc())
3437 return Visit(Next, Sel);
3438
3439 // If there's no inner type and we're in a permissive context,
3440 // don't diagnose.
3441 if (Sel == Sema::AbstractNone) return;
3442
3443 // Check whether the type matches the abstract type.
3444 QualType T = TL.getType();
3445 if (T->isArrayType()) {
3446 Sel = Sema::AbstractArrayType;
3447 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003448 }
John McCall94c3b562010-08-18 09:41:07 +00003449 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3450 if (CT != Info.AbstractType) return;
3451
3452 // It matched; do some magic.
3453 if (Sel == Sema::AbstractArrayType) {
3454 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3455 << T << TL.getSourceRange();
3456 } else {
3457 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3458 << Sel << T << TL.getSourceRange();
3459 }
3460 Info.DiagnoseAbstractType();
3461 }
3462};
3463
3464void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3465 Sema::AbstractDiagSelID Sel) {
3466 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3467}
3468
3469}
3470
3471/// Check for invalid uses of an abstract type in a method declaration.
3472static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3473 CXXMethodDecl *MD) {
3474 // No need to do the check on definitions, which require that
3475 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003476 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003477 return;
3478
3479 // For safety's sake, just ignore it if we don't have type source
3480 // information. This should never happen for non-implicit methods,
3481 // but...
3482 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3483 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3484}
3485
3486/// Check for invalid uses of an abstract type within a class definition.
3487static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3488 CXXRecordDecl *RD) {
3489 for (CXXRecordDecl::decl_iterator
3490 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3491 Decl *D = *I;
3492 if (D->isImplicit()) continue;
3493
3494 // Methods and method templates.
3495 if (isa<CXXMethodDecl>(D)) {
3496 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3497 } else if (isa<FunctionTemplateDecl>(D)) {
3498 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3499 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3500
3501 // Fields and static variables.
3502 } else if (isa<FieldDecl>(D)) {
3503 FieldDecl *FD = cast<FieldDecl>(D);
3504 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3505 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3506 } else if (isa<VarDecl>(D)) {
3507 VarDecl *VD = cast<VarDecl>(D);
3508 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3509 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3510
3511 // Nested classes and class templates.
3512 } else if (isa<CXXRecordDecl>(D)) {
3513 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3514 } else if (isa<ClassTemplateDecl>(D)) {
3515 CheckAbstractClassUsage(Info,
3516 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3517 }
3518 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003519}
3520
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003521/// \brief Perform semantic checks on a class definition that has been
3522/// completing, introducing implicitly-declared members, checking for
3523/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003524void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003525 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003526 return;
3527
John McCall94c3b562010-08-18 09:41:07 +00003528 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3529 AbstractUsageInfo Info(*this, Record);
3530 CheckAbstractClassUsage(Info, Record);
3531 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003532
3533 // If this is not an aggregate type and has no user-declared constructor,
3534 // complain about any non-static data members of reference or const scalar
3535 // type, since they will never get initializers.
3536 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3537 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3538 bool Complained = false;
3539 for (RecordDecl::field_iterator F = Record->field_begin(),
3540 FEnd = Record->field_end();
3541 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003542 if (F->hasInClassInitializer())
3543 continue;
3544
Douglas Gregor325e5932010-04-15 00:00:53 +00003545 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003546 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003547 if (!Complained) {
3548 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3549 << Record->getTagKind() << Record;
3550 Complained = true;
3551 }
3552
3553 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3554 << F->getType()->isReferenceType()
3555 << F->getDeclName();
3556 }
3557 }
3558 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003559
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003560 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003561 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003562
3563 if (Record->getIdentifier()) {
3564 // C++ [class.mem]p13:
3565 // If T is the name of a class, then each of the following shall have a
3566 // name different from T:
3567 // - every member of every anonymous union that is a member of class T.
3568 //
3569 // C++ [class.mem]p14:
3570 // In addition, if class T has a user-declared constructor (12.1), every
3571 // non-static data member of class T shall have a name different from T.
3572 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003573 R.first != R.second; ++R.first) {
3574 NamedDecl *D = *R.first;
3575 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3576 isa<IndirectFieldDecl>(D)) {
3577 Diag(D->getLocation(), diag::err_member_name_of_class)
3578 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003579 break;
3580 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003581 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003582 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003583
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003584 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003585 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003586 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003587 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003588 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3589 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3590 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003591
3592 // See if a method overloads virtual methods in a base
3593 /// class without overriding any.
3594 if (!Record->isDependentType()) {
3595 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3596 MEnd = Record->method_end();
3597 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003598 if (!(*M)->isStatic())
3599 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003600 }
3601 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003602
Richard Smith9f569cc2011-10-01 02:31:28 +00003603 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3604 // function that is not a constructor declares that member function to be
3605 // const. [...] The class of which that function is a member shall be
3606 // a literal type.
3607 //
3608 // It's fine to diagnose constructors here too: such constructors cannot
3609 // produce a constant expression, so are ill-formed (no diagnostic required).
3610 //
3611 // If the class has virtual bases, any constexpr members will already have
3612 // been diagnosed by the checks performed on the member declaration, so
3613 // suppress this (less useful) diagnostic.
3614 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3615 !Record->isLiteral() && !Record->getNumVBases()) {
3616 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3617 MEnd = Record->method_end();
3618 M != MEnd; ++M) {
3619 if ((*M)->isConstexpr()) {
3620 switch (Record->getTemplateSpecializationKind()) {
3621 case TSK_ImplicitInstantiation:
3622 case TSK_ExplicitInstantiationDeclaration:
3623 case TSK_ExplicitInstantiationDefinition:
3624 // If a template instantiates to a non-literal type, but its members
3625 // instantiate to constexpr functions, the template is technically
3626 // ill-formed, but we allow it for sanity. Such members are treated as
3627 // non-constexpr.
3628 (*M)->setConstexpr(false);
3629 continue;
3630
3631 case TSK_Undeclared:
3632 case TSK_ExplicitSpecialization:
3633 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3634 PDiag(diag::err_constexpr_method_non_literal));
3635 break;
3636 }
3637
3638 // Only produce one error per class.
3639 break;
3640 }
3641 }
3642 }
3643
Sebastian Redlf677ea32011-02-05 19:23:19 +00003644 // Declare inherited constructors. We do this eagerly here because:
3645 // - The standard requires an eager diagnostic for conflicting inherited
3646 // constructors from different classes.
3647 // - The lazy declaration of the other implicit constructors is so as to not
3648 // waste space and performance on classes that are not meant to be
3649 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3650 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003651 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003652
Sean Hunteb88ae52011-05-23 21:07:59 +00003653 if (!Record->isDependentType())
3654 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003655}
3656
3657void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003658 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3659 ME = Record->method_end();
3660 MI != ME; ++MI) {
3661 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3662 switch (getSpecialMember(*MI)) {
3663 case CXXDefaultConstructor:
3664 CheckExplicitlyDefaultedDefaultConstructor(
3665 cast<CXXConstructorDecl>(*MI));
3666 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003667
Sean Huntcb45a0f2011-05-12 22:46:25 +00003668 case CXXDestructor:
3669 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3670 break;
3671
3672 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003673 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3674 break;
3675
Sean Huntcb45a0f2011-05-12 22:46:25 +00003676 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003677 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003678 break;
3679
Sean Hunt82713172011-05-25 23:16:36 +00003680 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003681 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003682 break;
3683
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003684 case CXXMoveAssignment:
3685 CheckExplicitlyDefaultedMoveAssignment(*MI);
3686 break;
3687
3688 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003689 llvm_unreachable("non-special member explicitly defaulted!");
3690 }
Sean Hunt001cad92011-05-10 00:49:42 +00003691 }
3692 }
3693
Sean Hunt001cad92011-05-10 00:49:42 +00003694}
3695
3696void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3697 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3698
3699 // Whether this was the first-declared instance of the constructor.
3700 // This affects whether we implicitly add an exception spec (and, eventually,
3701 // constexpr). It is also ill-formed to explicitly default a constructor such
3702 // that it would be deleted. (C++0x [decl.fct.def.default])
3703 bool First = CD == CD->getCanonicalDecl();
3704
Sean Hunt49634cf2011-05-13 06:10:58 +00003705 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003706 if (CD->getNumParams() != 0) {
3707 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3708 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003709 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003710 }
3711
3712 ImplicitExceptionSpecification Spec
3713 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3714 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003715 if (EPI.ExceptionSpecType == EST_Delayed) {
3716 // Exception specification depends on some deferred part of the class. We'll
3717 // try again when the class's definition has been fully processed.
3718 return;
3719 }
Sean Hunt001cad92011-05-10 00:49:42 +00003720 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3721 *ExceptionType = Context.getFunctionType(
3722 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3723
3724 if (CtorType->hasExceptionSpec()) {
3725 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003726 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003727 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003728 PDiag(),
3729 ExceptionType, SourceLocation(),
3730 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003731 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003732 }
3733 } else if (First) {
3734 // We set the declaration to have the computed exception spec here.
3735 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003736 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003737 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3738 }
Sean Huntca46d132011-05-12 03:51:48 +00003739
Sean Hunt49634cf2011-05-13 06:10:58 +00003740 if (HadError) {
3741 CD->setInvalidDecl();
3742 return;
3743 }
3744
Sean Hunte16da072011-10-10 06:18:57 +00003745 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003746 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003747 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003748 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003749 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003750 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003751 CD->setInvalidDecl();
3752 }
3753 }
3754}
3755
3756void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3757 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3758
3759 // Whether this was the first-declared instance of the constructor.
3760 bool First = CD == CD->getCanonicalDecl();
3761
3762 bool HadError = false;
3763 if (CD->getNumParams() != 1) {
3764 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3765 << CD->getSourceRange();
3766 HadError = true;
3767 }
3768
3769 ImplicitExceptionSpecification Spec(Context);
3770 bool Const;
3771 llvm::tie(Spec, Const) =
3772 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3773
3774 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3775 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3776 *ExceptionType = Context.getFunctionType(
3777 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3778
3779 // Check for parameter type matching.
3780 // This is a copy ctor so we know it's a cv-qualified reference to T.
3781 QualType ArgType = CtorType->getArgType(0);
3782 if (ArgType->getPointeeType().isVolatileQualified()) {
3783 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3784 HadError = true;
3785 }
3786 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3787 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3788 HadError = true;
3789 }
3790
3791 if (CtorType->hasExceptionSpec()) {
3792 if (CheckEquivalentExceptionSpec(
3793 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003794 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003795 PDiag(),
3796 ExceptionType, SourceLocation(),
3797 CtorType, CD->getLocation())) {
3798 HadError = true;
3799 }
3800 } else if (First) {
3801 // We set the declaration to have the computed exception spec here.
3802 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003803 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003804 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3805 }
3806
3807 if (HadError) {
3808 CD->setInvalidDecl();
3809 return;
3810 }
3811
3812 if (ShouldDeleteCopyConstructor(CD)) {
3813 if (First) {
3814 CD->setDeletedAsWritten();
3815 } else {
3816 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003817 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003818 CD->setInvalidDecl();
3819 }
Sean Huntca46d132011-05-12 03:51:48 +00003820 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003821}
Sean Hunt001cad92011-05-10 00:49:42 +00003822
Sean Hunt2b188082011-05-14 05:23:28 +00003823void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3824 assert(MD->isExplicitlyDefaulted());
3825
3826 // Whether this was the first-declared instance of the operator
3827 bool First = MD == MD->getCanonicalDecl();
3828
3829 bool HadError = false;
3830 if (MD->getNumParams() != 1) {
3831 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3832 << MD->getSourceRange();
3833 HadError = true;
3834 }
3835
3836 QualType ReturnType =
3837 MD->getType()->getAs<FunctionType>()->getResultType();
3838 if (!ReturnType->isLValueReferenceType() ||
3839 !Context.hasSameType(
3840 Context.getCanonicalType(ReturnType->getPointeeType()),
3841 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3842 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3843 HadError = true;
3844 }
3845
3846 ImplicitExceptionSpecification Spec(Context);
3847 bool Const;
3848 llvm::tie(Spec, Const) =
3849 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3850
3851 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3852 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3853 *ExceptionType = Context.getFunctionType(
3854 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3855
Sean Hunt2b188082011-05-14 05:23:28 +00003856 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003857 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00003858 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003859 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003860 } else {
3861 if (ArgType->getPointeeType().isVolatileQualified()) {
3862 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3863 HadError = true;
3864 }
3865 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3866 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3867 HadError = true;
3868 }
Sean Hunt2b188082011-05-14 05:23:28 +00003869 }
Sean Huntbe631222011-05-17 20:44:43 +00003870
Sean Hunt2b188082011-05-14 05:23:28 +00003871 if (OperType->getTypeQuals()) {
3872 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3873 HadError = true;
3874 }
3875
3876 if (OperType->hasExceptionSpec()) {
3877 if (CheckEquivalentExceptionSpec(
3878 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003879 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003880 PDiag(),
3881 ExceptionType, SourceLocation(),
3882 OperType, MD->getLocation())) {
3883 HadError = true;
3884 }
3885 } else if (First) {
3886 // We set the declaration to have the computed exception spec here.
3887 // We duplicate the one parameter type.
3888 EPI.RefQualifier = OperType->getRefQualifier();
3889 EPI.ExtInfo = OperType->getExtInfo();
3890 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3891 }
3892
3893 if (HadError) {
3894 MD->setInvalidDecl();
3895 return;
3896 }
3897
3898 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3899 if (First) {
3900 MD->setDeletedAsWritten();
3901 } else {
3902 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003903 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003904 MD->setInvalidDecl();
3905 }
3906 }
3907}
3908
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003909void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3910 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3911
3912 // Whether this was the first-declared instance of the constructor.
3913 bool First = CD == CD->getCanonicalDecl();
3914
3915 bool HadError = false;
3916 if (CD->getNumParams() != 1) {
3917 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3918 << CD->getSourceRange();
3919 HadError = true;
3920 }
3921
3922 ImplicitExceptionSpecification Spec(
3923 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3924
3925 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3926 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3927 *ExceptionType = Context.getFunctionType(
3928 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3929
3930 // Check for parameter type matching.
3931 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3932 QualType ArgType = CtorType->getArgType(0);
3933 if (ArgType->getPointeeType().isVolatileQualified()) {
3934 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3935 HadError = true;
3936 }
3937 if (ArgType->getPointeeType().isConstQualified()) {
3938 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3939 HadError = true;
3940 }
3941
3942 if (CtorType->hasExceptionSpec()) {
3943 if (CheckEquivalentExceptionSpec(
3944 PDiag(diag::err_incorrect_defaulted_exception_spec)
3945 << CXXMoveConstructor,
3946 PDiag(),
3947 ExceptionType, SourceLocation(),
3948 CtorType, CD->getLocation())) {
3949 HadError = true;
3950 }
3951 } else if (First) {
3952 // We set the declaration to have the computed exception spec here.
3953 // We duplicate the one parameter type.
3954 EPI.ExtInfo = CtorType->getExtInfo();
3955 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3956 }
3957
3958 if (HadError) {
3959 CD->setInvalidDecl();
3960 return;
3961 }
3962
3963 if (ShouldDeleteMoveConstructor(CD)) {
3964 if (First) {
3965 CD->setDeletedAsWritten();
3966 } else {
3967 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3968 << CXXMoveConstructor;
3969 CD->setInvalidDecl();
3970 }
3971 }
3972}
3973
3974void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3975 assert(MD->isExplicitlyDefaulted());
3976
3977 // Whether this was the first-declared instance of the operator
3978 bool First = MD == MD->getCanonicalDecl();
3979
3980 bool HadError = false;
3981 if (MD->getNumParams() != 1) {
3982 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3983 << MD->getSourceRange();
3984 HadError = true;
3985 }
3986
3987 QualType ReturnType =
3988 MD->getType()->getAs<FunctionType>()->getResultType();
3989 if (!ReturnType->isLValueReferenceType() ||
3990 !Context.hasSameType(
3991 Context.getCanonicalType(ReturnType->getPointeeType()),
3992 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3993 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3994 HadError = true;
3995 }
3996
3997 ImplicitExceptionSpecification Spec(
3998 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3999
4000 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4001 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4002 *ExceptionType = Context.getFunctionType(
4003 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4004
4005 QualType ArgType = OperType->getArgType(0);
4006 if (!ArgType->isRValueReferenceType()) {
4007 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4008 HadError = true;
4009 } else {
4010 if (ArgType->getPointeeType().isVolatileQualified()) {
4011 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4012 HadError = true;
4013 }
4014 if (ArgType->getPointeeType().isConstQualified()) {
4015 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4016 HadError = true;
4017 }
4018 }
4019
4020 if (OperType->getTypeQuals()) {
4021 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4022 HadError = true;
4023 }
4024
4025 if (OperType->hasExceptionSpec()) {
4026 if (CheckEquivalentExceptionSpec(
4027 PDiag(diag::err_incorrect_defaulted_exception_spec)
4028 << CXXMoveAssignment,
4029 PDiag(),
4030 ExceptionType, SourceLocation(),
4031 OperType, MD->getLocation())) {
4032 HadError = true;
4033 }
4034 } else if (First) {
4035 // We set the declaration to have the computed exception spec here.
4036 // We duplicate the one parameter type.
4037 EPI.RefQualifier = OperType->getRefQualifier();
4038 EPI.ExtInfo = OperType->getExtInfo();
4039 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4040 }
4041
4042 if (HadError) {
4043 MD->setInvalidDecl();
4044 return;
4045 }
4046
4047 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4048 if (First) {
4049 MD->setDeletedAsWritten();
4050 } else {
4051 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4052 << CXXMoveAssignment;
4053 MD->setInvalidDecl();
4054 }
4055 }
4056}
4057
Sean Huntcb45a0f2011-05-12 22:46:25 +00004058void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4059 assert(DD->isExplicitlyDefaulted());
4060
4061 // Whether this was the first-declared instance of the destructor.
4062 bool First = DD == DD->getCanonicalDecl();
4063
4064 ImplicitExceptionSpecification Spec
4065 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4066 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4067 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4068 *ExceptionType = Context.getFunctionType(
4069 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4070
4071 if (DtorType->hasExceptionSpec()) {
4072 if (CheckEquivalentExceptionSpec(
4073 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004074 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004075 PDiag(),
4076 ExceptionType, SourceLocation(),
4077 DtorType, DD->getLocation())) {
4078 DD->setInvalidDecl();
4079 return;
4080 }
4081 } else if (First) {
4082 // We set the declaration to have the computed exception spec here.
4083 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004084 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004085 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4086 }
4087
4088 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004089 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004090 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004091 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004092 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004093 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004094 DD->setInvalidDecl();
4095 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004096 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004097}
4098
Sean Hunte16da072011-10-10 06:18:57 +00004099/// This function implements the following C++0x paragraphs:
4100/// - [class.ctor]/5
4101bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4102 assert(!MD->isInvalidDecl());
4103 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004104 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004105 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004106 return false;
4107
Sean Hunte16da072011-10-10 06:18:57 +00004108 bool IsUnion = RD->isUnion();
4109 bool IsConstructor = false;
4110 bool IsAssignment = false;
4111 bool IsMove = false;
4112
4113 bool ConstArg = false;
4114
4115 switch (CSM) {
4116 case CXXDefaultConstructor:
4117 IsConstructor = true;
4118 break;
4119 default:
4120 llvm_unreachable("function only currently implemented for default ctors");
4121 }
4122
4123 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004124
Sean Huntcdee3fe2011-05-11 22:34:38 +00004125 // Do access control from the constructor
Sean Hunte16da072011-10-10 06:18:57 +00004126 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004127
Sean Huntcdee3fe2011-05-11 22:34:38 +00004128 bool AllConst = true;
4129
Sean Huntcdee3fe2011-05-11 22:34:38 +00004130 // We do this because we should never actually use an anonymous
4131 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004132 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004133 return false;
4134
4135 // FIXME: We should put some diagnostic logic right into this function.
4136
Sean Huntcdee3fe2011-05-11 22:34:38 +00004137 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4138 BE = RD->bases_end();
4139 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004140 // We'll handle this one later
4141 if (BI->isVirtual())
4142 continue;
4143
Sean Huntcdee3fe2011-05-11 22:34:38 +00004144 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4145 assert(BaseDecl && "base isn't a CXXRecordDecl");
4146
Sean Hunte16da072011-10-10 06:18:57 +00004147 // Unless we have an assignment operator, the base's destructor must
4148 // be accessible and not deleted.
4149 if (!IsAssignment) {
4150 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4151 if (BaseDtor->isDeleted())
4152 return true;
4153 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4154 AR_accessible)
4155 return true;
4156 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004157
Sean Hunte16da072011-10-10 06:18:57 +00004158 // Finding the corresponding member in the base should lead to a
4159 // unique, accessible, non-deleted function.
4160 if (CSM != CXXDestructor) {
4161 SpecialMemberOverloadResult *SMOR =
4162 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, IsMove, false,
4163 false);
4164 if (!SMOR->hasSuccess())
4165 return true;
4166 CXXMethodDecl *BaseMember = SMOR->getMethod();
4167 if (IsConstructor) {
4168 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4169 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4170 PDiag()) != AR_accessible)
4171 return true;
4172 }
4173 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004174 }
4175
4176 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4177 BE = RD->vbases_end();
4178 BI != BE; ++BI) {
4179 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4180 assert(BaseDecl && "base isn't a CXXRecordDecl");
4181
Sean Hunte16da072011-10-10 06:18:57 +00004182 // Unless we have an assignment operator, the base's destructor must
4183 // be accessible and not deleted.
4184 if (!IsAssignment) {
4185 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4186 if (BaseDtor->isDeleted())
4187 return true;
4188 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4189 AR_accessible)
4190 return true;
4191 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004192
Sean Hunte16da072011-10-10 06:18:57 +00004193 // Finding the corresponding member in the base should lead to a
4194 // unique, accessible, non-deleted function.
4195 if (CSM != CXXDestructor) {
4196 SpecialMemberOverloadResult *SMOR =
4197 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, IsMove, false,
4198 false);
4199 if (!SMOR->hasSuccess())
4200 return true;
4201 CXXMethodDecl *BaseMember = SMOR->getMethod();
4202 if (IsConstructor) {
4203 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4204 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4205 PDiag()) != AR_accessible)
4206 return true;
4207 }
4208 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004209 }
4210
4211 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4212 FE = RD->field_end();
4213 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00004214 if (FI->isInvalidDecl())
4215 continue;
4216
Sean Huntcdee3fe2011-05-11 22:34:38 +00004217 QualType FieldType = Context.getBaseElementType(FI->getType());
4218 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004219
Sean Hunte16da072011-10-10 06:18:57 +00004220 // For a default constructor, all references must be initialized in-class
4221 // and, if a union, it must have a non-const member.
4222 if (CSM == CXXDefaultConstructor) {
4223 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4224 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004225
Sean Hunte16da072011-10-10 06:18:57 +00004226 if (IsUnion && !FieldType.isConstQualified())
4227 AllConst = false;
4228 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004229
4230 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004231 // Unless we're doing assignment, the field's destructor must be
4232 // accessible and not deleted.
4233 if (!IsAssignment) {
4234 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4235 if (FieldDtor->isDeleted())
4236 return true;
4237 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4238 AR_accessible)
4239 return true;
4240 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004241
Sean Hunte16da072011-10-10 06:18:57 +00004242 // For a default constructor, a const member must have a user-provided
4243 // default constructor or else be explicitly initialized.
4244 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004245 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004246 !FieldRecord->hasUserProvidedDefaultConstructor())
4247 return true;
4248
Sean Hunte16da072011-10-10 06:18:57 +00004249 // For a default constructor, additional restrictions exist on the
4250 // variant members.
4251 if (CSM == CXXDefaultConstructor && !IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004252 FieldRecord->isAnonymousStructOrUnion()) {
4253 // We're okay to reuse AllConst here since we only care about the
4254 // value otherwise if we're in a union.
4255 AllConst = true;
4256
4257 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4258 UE = FieldRecord->field_end();
4259 UI != UE; ++UI) {
4260 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4261 CXXRecordDecl *UnionFieldRecord =
4262 UnionFieldType->getAsCXXRecordDecl();
4263
4264 if (!UnionFieldType.isConstQualified())
4265 AllConst = false;
4266
4267 if (UnionFieldRecord &&
4268 !UnionFieldRecord->hasTrivialDefaultConstructor())
4269 return true;
4270 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004271
Sean Huntcdee3fe2011-05-11 22:34:38 +00004272 if (AllConst)
4273 return true;
4274
4275 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004276 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004277 continue;
4278 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004279
Sean Hunte16da072011-10-10 06:18:57 +00004280 // Check that the corresponding member of the field is accessible,
4281 // unique, and non-deleted. We don't do this if it has an explicit
4282 // initialization when default-constructing.
4283 if (CSM != CXXDestructor &&
4284 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4285 SpecialMemberOverloadResult *SMOR =
4286 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, IsMove, false,
4287 false);
4288 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004289 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004290
4291 CXXMethodDecl *FieldMember = SMOR->getMethod();
4292 if (IsConstructor) {
4293 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4294 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4295 PDiag()) != AR_accessible)
4296 return true;
4297 }
4298
4299 // We need the corresponding member of a union to be trivial so that
4300 // we can safely copy them all simultaneously.
4301 // FIXME: Note that performing the check here (where we rely on the lack
4302 // of an in-class initializer) is technically ill-formed. However, this
4303 // seems most obviously to be a bug in the standard.
4304 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004305 return true;
4306 }
Sean Hunte16da072011-10-10 06:18:57 +00004307 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4308 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4309 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004310 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004311 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004312 }
4313
Sean Hunte16da072011-10-10 06:18:57 +00004314 // We can't have all const members in a union when default-constructing,
4315 // or else they're all nonsensical garbage values that can't be changed.
4316 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004317 return true;
4318
4319 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004320}
4321
Sean Hunt49634cf2011-05-13 06:10:58 +00004322bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00004323 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00004324 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004325 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt49634cf2011-05-13 06:10:58 +00004326 return false;
4327
Sean Hunt71a682f2011-05-18 03:41:58 +00004328 SourceLocation Loc = CD->getLocation();
4329
Sean Hunt49634cf2011-05-13 06:10:58 +00004330 // Do access control from the constructor
4331 ContextRAII CtorContext(*this, CD);
4332
Sean Huntc530d172011-06-10 04:44:37 +00004333 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00004334
Sean Hunt2b188082011-05-14 05:23:28 +00004335 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4336 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00004337 unsigned ArgQuals =
4338 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4339 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00004340
4341 // We do this because we should never actually use an anonymous
4342 // union's constructor.
4343 if (Union && RD->isAnonymousStructOrUnion())
4344 return false;
4345
4346 // FIXME: We should put some diagnostic logic right into this function.
4347
4348 // C++0x [class.copy]/11
4349 // A defaulted [copy] constructor for class X is defined as delete if X has:
4350
4351 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4352 BE = RD->bases_end();
4353 BI != BE; ++BI) {
4354 // We'll handle this one later
4355 if (BI->isVirtual())
4356 continue;
4357
4358 QualType BaseType = BI->getType();
4359 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4360 assert(BaseDecl && "base isn't a CXXRecordDecl");
4361
4362 // -- any [direct base class] of a type with a destructor that is deleted or
4363 // inaccessible from the defaulted constructor
4364 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4365 if (BaseDtor->isDeleted())
4366 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004367 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00004368 AR_accessible)
4369 return true;
4370
4371 // -- a [direct base class] B that cannot be [copied] because overload
4372 // resolution, as applied to B's [copy] constructor, results in an
4373 // ambiguity or a function that is deleted or inaccessible from the
4374 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00004375 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00004376 if (!BaseCtor || BaseCtor->isDeleted())
4377 return true;
4378 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4379 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00004380 return true;
4381 }
4382
4383 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4384 BE = RD->vbases_end();
4385 BI != BE; ++BI) {
4386 QualType BaseType = BI->getType();
4387 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4388 assert(BaseDecl && "base isn't a CXXRecordDecl");
4389
Sean Huntb320e0c2011-06-10 03:50:41 +00004390 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00004391 // inaccessible from the defaulted constructor
4392 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4393 if (BaseDtor->isDeleted())
4394 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004395 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00004396 AR_accessible)
4397 return true;
4398
4399 // -- a [virtual base class] B that cannot be [copied] because overload
4400 // resolution, as applied to B's [copy] constructor, results in an
4401 // ambiguity or a function that is deleted or inaccessible from the
4402 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00004403 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00004404 if (!BaseCtor || BaseCtor->isDeleted())
4405 return true;
4406 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4407 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00004408 return true;
4409 }
4410
4411 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4412 FE = RD->field_end();
4413 FI != FE; ++FI) {
4414 QualType FieldType = Context.getBaseElementType(FI->getType());
4415
4416 // -- for a copy constructor, a non-static data member of rvalue reference
4417 // type
4418 if (FieldType->isRValueReferenceType())
4419 return true;
4420
4421 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4422
4423 if (FieldRecord) {
4424 // This is an anonymous union
4425 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4426 // Anonymous unions inside unions do not variant members create
4427 if (!Union) {
4428 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4429 UE = FieldRecord->field_end();
4430 UI != UE; ++UI) {
4431 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4432 CXXRecordDecl *UnionFieldRecord =
4433 UnionFieldType->getAsCXXRecordDecl();
4434
4435 // -- a variant member with a non-trivial [copy] constructor and X
4436 // is a union-like class
4437 if (UnionFieldRecord &&
4438 !UnionFieldRecord->hasTrivialCopyConstructor())
4439 return true;
4440 }
4441 }
4442
4443 // Don't try to initalize an anonymous union
4444 continue;
4445 } else {
4446 // -- a variant member with a non-trivial [copy] constructor and X is a
4447 // union-like class
4448 if (Union && !FieldRecord->hasTrivialCopyConstructor())
4449 return true;
4450
4451 // -- any [non-static data member] of a type with a destructor that is
4452 // deleted or inaccessible from the defaulted constructor
4453 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4454 if (FieldDtor->isDeleted())
4455 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004456 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00004457 AR_accessible)
4458 return true;
4459 }
Sean Huntc530d172011-06-10 04:44:37 +00004460
4461 // -- a [non-static data member of class type (or array thereof)] B that
4462 // cannot be [copied] because overload resolution, as applied to B's
4463 // [copy] constructor, results in an ambiguity or a function that is
4464 // deleted or inaccessible from the defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00004465 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
4466 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00004467 if (!FieldCtor || FieldCtor->isDeleted())
4468 return true;
4469 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4470 PDiag()) != AR_accessible)
4471 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00004472 }
Sean Hunt49634cf2011-05-13 06:10:58 +00004473 }
4474
4475 return false;
4476}
4477
Sean Hunt7f410192011-05-14 05:23:24 +00004478bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4479 CXXRecordDecl *RD = MD->getParent();
4480 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004481 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004482 return false;
4483
Sean Hunt71a682f2011-05-18 03:41:58 +00004484 SourceLocation Loc = MD->getLocation();
4485
Sean Hunt7f410192011-05-14 05:23:24 +00004486 // Do access control from the constructor
4487 ContextRAII MethodContext(*this, MD);
4488
4489 bool Union = RD->isUnion();
4490
Sean Hunt661c67a2011-06-21 23:42:56 +00004491 unsigned ArgQuals =
4492 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4493 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004494
4495 // We do this because we should never actually use an anonymous
4496 // union's constructor.
4497 if (Union && RD->isAnonymousStructOrUnion())
4498 return false;
4499
Sean Hunt7f410192011-05-14 05:23:24 +00004500 // FIXME: We should put some diagnostic logic right into this function.
4501
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004502 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004503 // A defaulted [copy] assignment operator for class X is defined as deleted
4504 // if X has:
4505
4506 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4507 BE = RD->bases_end();
4508 BI != BE; ++BI) {
4509 // We'll handle this one later
4510 if (BI->isVirtual())
4511 continue;
4512
4513 QualType BaseType = BI->getType();
4514 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4515 assert(BaseDecl && "base isn't a CXXRecordDecl");
4516
4517 // -- a [direct base class] B that cannot be [copied] because overload
4518 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004519 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004520 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004521 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4522 0);
4523 if (!CopyOper || CopyOper->isDeleted())
4524 return true;
4525 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004526 return true;
4527 }
4528
4529 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4530 BE = RD->vbases_end();
4531 BI != BE; ++BI) {
4532 QualType BaseType = BI->getType();
4533 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4534 assert(BaseDecl && "base isn't a CXXRecordDecl");
4535
Sean Hunt7f410192011-05-14 05:23:24 +00004536 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004537 // resolution, as applied to B's [copy] assignment operator, results in
4538 // an ambiguity or a function that is deleted or inaccessible from the
4539 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004540 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4541 0);
4542 if (!CopyOper || CopyOper->isDeleted())
4543 return true;
4544 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004545 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004546 }
4547
4548 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4549 FE = RD->field_end();
4550 FI != FE; ++FI) {
4551 QualType FieldType = Context.getBaseElementType(FI->getType());
4552
4553 // -- a non-static data member of reference type
4554 if (FieldType->isReferenceType())
4555 return true;
4556
4557 // -- a non-static data member of const non-class type (or array thereof)
4558 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4559 return true;
4560
4561 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4562
4563 if (FieldRecord) {
4564 // This is an anonymous union
4565 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4566 // Anonymous unions inside unions do not variant members create
4567 if (!Union) {
4568 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4569 UE = FieldRecord->field_end();
4570 UI != UE; ++UI) {
4571 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4572 CXXRecordDecl *UnionFieldRecord =
4573 UnionFieldType->getAsCXXRecordDecl();
4574
4575 // -- a variant member with a non-trivial [copy] assignment operator
4576 // and X is a union-like class
4577 if (UnionFieldRecord &&
4578 !UnionFieldRecord->hasTrivialCopyAssignment())
4579 return true;
4580 }
4581 }
4582
4583 // Don't try to initalize an anonymous union
4584 continue;
4585 // -- a variant member with a non-trivial [copy] assignment operator
4586 // and X is a union-like class
4587 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4588 return true;
4589 }
Sean Hunt7f410192011-05-14 05:23:24 +00004590
Sean Hunt661c67a2011-06-21 23:42:56 +00004591 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4592 false, 0);
4593 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004594 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004595 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004596 return true;
4597 }
4598 }
4599
4600 return false;
4601}
4602
4603bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4604 CXXRecordDecl *RD = CD->getParent();
4605 assert(!RD->isDependentType() && "do deletion after instantiation");
4606 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4607 return false;
4608
4609 SourceLocation Loc = CD->getLocation();
4610
4611 // Do access control from the constructor
4612 ContextRAII CtorContext(*this, CD);
4613
4614 bool Union = RD->isUnion();
4615
4616 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4617 "copy assignment arg has no pointee type");
4618
4619 // We do this because we should never actually use an anonymous
4620 // union's constructor.
4621 if (Union && RD->isAnonymousStructOrUnion())
4622 return false;
4623
4624 // C++0x [class.copy]/11
4625 // A defaulted [move] constructor for class X is defined as deleted
4626 // if X has:
4627
4628 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4629 BE = RD->bases_end();
4630 BI != BE; ++BI) {
4631 // We'll handle this one later
4632 if (BI->isVirtual())
4633 continue;
4634
4635 QualType BaseType = BI->getType();
4636 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4637 assert(BaseDecl && "base isn't a CXXRecordDecl");
4638
4639 // -- any [direct base class] of a type with a destructor that is deleted or
4640 // inaccessible from the defaulted constructor
4641 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4642 if (BaseDtor->isDeleted())
4643 return true;
4644 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4645 AR_accessible)
4646 return true;
4647
4648 // -- a [direct base class] B that cannot be [moved] because overload
4649 // resolution, as applied to B's [move] constructor, results in an
4650 // ambiguity or a function that is deleted or inaccessible from the
4651 // defaulted constructor
4652 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4653 if (!BaseCtor || BaseCtor->isDeleted())
4654 return true;
4655 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4656 AR_accessible)
4657 return true;
4658
4659 // -- for a move constructor, a [direct base class] with a type that
4660 // does not have a move constructor and is not trivially copyable.
4661 // If the field isn't a record, it's always trivially copyable.
4662 // A moving constructor could be a copy constructor instead.
4663 if (!BaseCtor->isMoveConstructor() &&
4664 !BaseDecl->isTriviallyCopyable())
4665 return true;
4666 }
4667
4668 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4669 BE = RD->vbases_end();
4670 BI != BE; ++BI) {
4671 QualType BaseType = BI->getType();
4672 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4673 assert(BaseDecl && "base isn't a CXXRecordDecl");
4674
4675 // -- any [virtual base class] of a type with a destructor that is deleted
4676 // or inaccessible from the defaulted constructor
4677 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4678 if (BaseDtor->isDeleted())
4679 return true;
4680 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4681 AR_accessible)
4682 return true;
4683
4684 // -- a [virtual base class] B that cannot be [moved] because overload
4685 // resolution, as applied to B's [move] constructor, results in an
4686 // ambiguity or a function that is deleted or inaccessible from the
4687 // defaulted constructor
4688 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4689 if (!BaseCtor || BaseCtor->isDeleted())
4690 return true;
4691 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4692 AR_accessible)
4693 return true;
4694
4695 // -- for a move constructor, a [virtual base class] with a type that
4696 // does not have a move constructor and is not trivially copyable.
4697 // If the field isn't a record, it's always trivially copyable.
4698 // A moving constructor could be a copy constructor instead.
4699 if (!BaseCtor->isMoveConstructor() &&
4700 !BaseDecl->isTriviallyCopyable())
4701 return true;
4702 }
4703
4704 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4705 FE = RD->field_end();
4706 FI != FE; ++FI) {
4707 QualType FieldType = Context.getBaseElementType(FI->getType());
4708
4709 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4710 // This is an anonymous union
4711 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4712 // Anonymous unions inside unions do not variant members create
4713 if (!Union) {
4714 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4715 UE = FieldRecord->field_end();
4716 UI != UE; ++UI) {
4717 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4718 CXXRecordDecl *UnionFieldRecord =
4719 UnionFieldType->getAsCXXRecordDecl();
4720
4721 // -- a variant member with a non-trivial [move] constructor and X
4722 // is a union-like class
4723 if (UnionFieldRecord &&
4724 !UnionFieldRecord->hasTrivialMoveConstructor())
4725 return true;
4726 }
4727 }
4728
4729 // Don't try to initalize an anonymous union
4730 continue;
4731 } else {
4732 // -- a variant member with a non-trivial [move] constructor and X is a
4733 // union-like class
4734 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4735 return true;
4736
4737 // -- any [non-static data member] of a type with a destructor that is
4738 // deleted or inaccessible from the defaulted constructor
4739 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4740 if (FieldDtor->isDeleted())
4741 return true;
4742 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4743 AR_accessible)
4744 return true;
4745 }
4746
4747 // -- a [non-static data member of class type (or array thereof)] B that
4748 // cannot be [moved] because overload resolution, as applied to B's
4749 // [move] constructor, results in an ambiguity or a function that is
4750 // deleted or inaccessible from the defaulted constructor
4751 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4752 if (!FieldCtor || FieldCtor->isDeleted())
4753 return true;
4754 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4755 PDiag()) != AR_accessible)
4756 return true;
4757
4758 // -- for a move constructor, a [non-static data member] with a type that
4759 // does not have a move constructor and is not trivially copyable.
4760 // If the field isn't a record, it's always trivially copyable.
4761 // A moving constructor could be a copy constructor instead.
4762 if (!FieldCtor->isMoveConstructor() &&
4763 !FieldRecord->isTriviallyCopyable())
4764 return true;
4765 }
4766 }
4767
4768 return false;
4769}
4770
4771bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4772 CXXRecordDecl *RD = MD->getParent();
4773 assert(!RD->isDependentType() && "do deletion after instantiation");
4774 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4775 return false;
4776
4777 SourceLocation Loc = MD->getLocation();
4778
4779 // Do access control from the constructor
4780 ContextRAII MethodContext(*this, MD);
4781
4782 bool Union = RD->isUnion();
4783
4784 // We do this because we should never actually use an anonymous
4785 // union's constructor.
4786 if (Union && RD->isAnonymousStructOrUnion())
4787 return false;
4788
4789 // C++0x [class.copy]/20
4790 // A defaulted [move] assignment operator for class X is defined as deleted
4791 // if X has:
4792
4793 // -- for the move constructor, [...] any direct or indirect virtual base
4794 // class.
4795 if (RD->getNumVBases() != 0)
4796 return true;
4797
4798 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4799 BE = RD->bases_end();
4800 BI != BE; ++BI) {
4801
4802 QualType BaseType = BI->getType();
4803 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4804 assert(BaseDecl && "base isn't a CXXRecordDecl");
4805
4806 // -- a [direct base class] B that cannot be [moved] because overload
4807 // resolution, as applied to B's [move] assignment operator, results in
4808 // an ambiguity or a function that is deleted or inaccessible from the
4809 // assignment operator
4810 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4811 if (!MoveOper || MoveOper->isDeleted())
4812 return true;
4813 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4814 return true;
4815
4816 // -- for the move assignment operator, a [direct base class] with a type
4817 // that does not have a move assignment operator and is not trivially
4818 // copyable.
4819 if (!MoveOper->isMoveAssignmentOperator() &&
4820 !BaseDecl->isTriviallyCopyable())
4821 return true;
4822 }
4823
4824 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4825 FE = RD->field_end();
4826 FI != FE; ++FI) {
4827 QualType FieldType = Context.getBaseElementType(FI->getType());
4828
4829 // -- a non-static data member of reference type
4830 if (FieldType->isReferenceType())
4831 return true;
4832
4833 // -- a non-static data member of const non-class type (or array thereof)
4834 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4835 return true;
4836
4837 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4838
4839 if (FieldRecord) {
4840 // This is an anonymous union
4841 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4842 // Anonymous unions inside unions do not variant members create
4843 if (!Union) {
4844 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4845 UE = FieldRecord->field_end();
4846 UI != UE; ++UI) {
4847 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4848 CXXRecordDecl *UnionFieldRecord =
4849 UnionFieldType->getAsCXXRecordDecl();
4850
4851 // -- a variant member with a non-trivial [move] assignment operator
4852 // and X is a union-like class
4853 if (UnionFieldRecord &&
4854 !UnionFieldRecord->hasTrivialMoveAssignment())
4855 return true;
4856 }
4857 }
4858
4859 // Don't try to initalize an anonymous union
4860 continue;
4861 // -- a variant member with a non-trivial [move] assignment operator
4862 // and X is a union-like class
4863 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4864 return true;
4865 }
4866
4867 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4868 if (!MoveOper || MoveOper->isDeleted())
4869 return true;
4870 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4871 return true;
4872
4873 // -- for the move assignment operator, a [non-static data member] with a
4874 // type that does not have a move assignment operator and is not
4875 // trivially copyable.
4876 if (!MoveOper->isMoveAssignmentOperator() &&
4877 !FieldRecord->isTriviallyCopyable())
4878 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004879 }
Sean Hunt7f410192011-05-14 05:23:24 +00004880 }
4881
4882 return false;
4883}
4884
Sean Huntcb45a0f2011-05-12 22:46:25 +00004885bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4886 CXXRecordDecl *RD = DD->getParent();
4887 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004888 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004889 return false;
4890
Sean Hunt71a682f2011-05-18 03:41:58 +00004891 SourceLocation Loc = DD->getLocation();
4892
Sean Huntcb45a0f2011-05-12 22:46:25 +00004893 // Do access control from the destructor
4894 ContextRAII CtorContext(*this, DD);
4895
4896 bool Union = RD->isUnion();
4897
Sean Hunt49634cf2011-05-13 06:10:58 +00004898 // We do this because we should never actually use an anonymous
4899 // union's destructor.
4900 if (Union && RD->isAnonymousStructOrUnion())
4901 return false;
4902
Sean Huntcb45a0f2011-05-12 22:46:25 +00004903 // C++0x [class.dtor]p5
4904 // A defaulted destructor for a class X is defined as deleted if:
4905 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4906 BE = RD->bases_end();
4907 BI != BE; ++BI) {
4908 // We'll handle this one later
4909 if (BI->isVirtual())
4910 continue;
4911
4912 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4913 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4914 assert(BaseDtor && "base has no destructor");
4915
4916 // -- any direct or virtual base class has a deleted destructor or
4917 // a destructor that is inaccessible from the defaulted destructor
4918 if (BaseDtor->isDeleted())
4919 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004920 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004921 AR_accessible)
4922 return true;
4923 }
4924
4925 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4926 BE = RD->vbases_end();
4927 BI != BE; ++BI) {
4928 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4929 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4930 assert(BaseDtor && "base has no destructor");
4931
4932 // -- any direct or virtual base class has a deleted destructor or
4933 // a destructor that is inaccessible from the defaulted destructor
4934 if (BaseDtor->isDeleted())
4935 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004936 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004937 AR_accessible)
4938 return true;
4939 }
4940
4941 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4942 FE = RD->field_end();
4943 FI != FE; ++FI) {
4944 QualType FieldType = Context.getBaseElementType(FI->getType());
4945 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4946 if (FieldRecord) {
4947 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4948 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4949 UE = FieldRecord->field_end();
4950 UI != UE; ++UI) {
4951 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4952 CXXRecordDecl *UnionFieldRecord =
4953 UnionFieldType->getAsCXXRecordDecl();
4954
4955 // -- X is a union-like class that has a variant member with a non-
4956 // trivial destructor.
4957 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4958 return true;
4959 }
4960 // Technically we are supposed to do this next check unconditionally.
4961 // But that makes absolutely no sense.
4962 } else {
4963 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4964
4965 // -- any of the non-static data members has class type M (or array
4966 // thereof) and M has a deleted destructor or a destructor that is
4967 // inaccessible from the defaulted destructor
4968 if (FieldDtor->isDeleted())
4969 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004970 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004971 AR_accessible)
4972 return true;
4973
4974 // -- X is a union-like class that has a variant member with a non-
4975 // trivial destructor.
4976 if (Union && !FieldDtor->isTrivial())
4977 return true;
4978 }
4979 }
4980 }
4981
4982 if (DD->isVirtual()) {
4983 FunctionDecl *OperatorDelete = 0;
4984 DeclarationName Name =
4985 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004986 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004987 false))
4988 return true;
4989 }
4990
4991
4992 return false;
4993}
4994
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004995/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004996namespace {
4997 struct FindHiddenVirtualMethodData {
4998 Sema *S;
4999 CXXMethodDecl *Method;
5000 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005001 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005002 };
5003}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005004
5005/// \brief Member lookup function that determines whether a given C++
5006/// method overloads virtual methods in a base class without overriding any,
5007/// to be used with CXXRecordDecl::lookupInBases().
5008static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5009 CXXBasePath &Path,
5010 void *UserData) {
5011 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5012
5013 FindHiddenVirtualMethodData &Data
5014 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5015
5016 DeclarationName Name = Data.Method->getDeclName();
5017 assert(Name.getNameKind() == DeclarationName::Identifier);
5018
5019 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005020 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005021 for (Path.Decls = BaseRecord->lookup(Name);
5022 Path.Decls.first != Path.Decls.second;
5023 ++Path.Decls.first) {
5024 NamedDecl *D = *Path.Decls.first;
5025 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005026 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005027 foundSameNameMethod = true;
5028 // Interested only in hidden virtual methods.
5029 if (!MD->isVirtual())
5030 continue;
5031 // If the method we are checking overrides a method from its base
5032 // don't warn about the other overloaded methods.
5033 if (!Data.S->IsOverload(Data.Method, MD, false))
5034 return true;
5035 // Collect the overload only if its hidden.
5036 if (!Data.OverridenAndUsingBaseMethods.count(MD))
5037 overloadedMethods.push_back(MD);
5038 }
5039 }
5040
5041 if (foundSameNameMethod)
5042 Data.OverloadedMethods.append(overloadedMethods.begin(),
5043 overloadedMethods.end());
5044 return foundSameNameMethod;
5045}
5046
5047/// \brief See if a method overloads virtual methods in a base class without
5048/// overriding any.
5049void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5050 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005051 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005052 return;
5053 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
5054 return;
5055
5056 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5057 /*bool RecordPaths=*/false,
5058 /*bool DetectVirtual=*/false);
5059 FindHiddenVirtualMethodData Data;
5060 Data.Method = MD;
5061 Data.S = this;
5062
5063 // Keep the base methods that were overriden or introduced in the subclass
5064 // by 'using' in a set. A base method not in this set is hidden.
5065 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5066 res.first != res.second; ++res.first) {
5067 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
5068 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5069 E = MD->end_overridden_methods();
5070 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005071 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005072 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5073 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005074 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005075 }
5076
5077 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5078 !Data.OverloadedMethods.empty()) {
5079 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5080 << MD << (Data.OverloadedMethods.size() > 1);
5081
5082 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5083 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5084 Diag(overloadedMD->getLocation(),
5085 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5086 }
5087 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005088}
5089
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005090void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005091 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005092 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005093 SourceLocation RBrac,
5094 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005095 if (!TagDecl)
5096 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005097
Douglas Gregor42af25f2009-05-11 19:58:34 +00005098 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005099
David Blaikie77b6de02011-09-22 02:58:26 +00005100 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005101 // strict aliasing violation!
5102 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005103 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005104
Douglas Gregor23c94db2010-07-02 17:43:08 +00005105 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005106 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005107}
5108
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005109/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5110/// special functions, such as the default constructor, copy
5111/// constructor, or destructor, to the given C++ class (C++
5112/// [special]p1). This routine can only be executed just before the
5113/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005114void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005115 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005116 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005117
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005118 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005119 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005120
Douglas Gregora376d102010-07-02 21:50:04 +00005121 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5122 ++ASTContext::NumImplicitCopyAssignmentOperators;
5123
5124 // If we have a dynamic class, then the copy assignment operator may be
5125 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5126 // it shows up in the right place in the vtable and that we diagnose
5127 // problems with the implicit exception specification.
5128 if (ClassDecl->isDynamicClass())
5129 DeclareImplicitCopyAssignment(ClassDecl);
5130 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005131
Douglas Gregor4923aa22010-07-02 20:37:36 +00005132 if (!ClassDecl->hasUserDeclaredDestructor()) {
5133 ++ASTContext::NumImplicitDestructors;
5134
5135 // If we have a dynamic class, then the destructor may be virtual, so we
5136 // have to declare the destructor immediately. This ensures that, e.g., it
5137 // shows up in the right place in the vtable and that we diagnose problems
5138 // with the implicit exception specification.
5139 if (ClassDecl->isDynamicClass())
5140 DeclareImplicitDestructor(ClassDecl);
5141 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005142}
5143
Francois Pichet8387e2a2011-04-22 22:18:13 +00005144void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5145 if (!D)
5146 return;
5147
5148 int NumParamList = D->getNumTemplateParameterLists();
5149 for (int i = 0; i < NumParamList; i++) {
5150 TemplateParameterList* Params = D->getTemplateParameterList(i);
5151 for (TemplateParameterList::iterator Param = Params->begin(),
5152 ParamEnd = Params->end();
5153 Param != ParamEnd; ++Param) {
5154 NamedDecl *Named = cast<NamedDecl>(*Param);
5155 if (Named->getDeclName()) {
5156 S->AddDecl(Named);
5157 IdResolver.AddDecl(Named);
5158 }
5159 }
5160 }
5161}
5162
John McCalld226f652010-08-21 09:40:31 +00005163void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005164 if (!D)
5165 return;
5166
5167 TemplateParameterList *Params = 0;
5168 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5169 Params = Template->getTemplateParameters();
5170 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5171 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5172 Params = PartialSpec->getTemplateParameters();
5173 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005174 return;
5175
Douglas Gregor6569d682009-05-27 23:11:45 +00005176 for (TemplateParameterList::iterator Param = Params->begin(),
5177 ParamEnd = Params->end();
5178 Param != ParamEnd; ++Param) {
5179 NamedDecl *Named = cast<NamedDecl>(*Param);
5180 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005181 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005182 IdResolver.AddDecl(Named);
5183 }
5184 }
5185}
5186
John McCalld226f652010-08-21 09:40:31 +00005187void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005188 if (!RecordD) return;
5189 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005190 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005191 PushDeclContext(S, Record);
5192}
5193
John McCalld226f652010-08-21 09:40:31 +00005194void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005195 if (!RecordD) return;
5196 PopDeclContext();
5197}
5198
Douglas Gregor72b505b2008-12-16 21:30:33 +00005199/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5200/// parsing a top-level (non-nested) C++ class, and we are now
5201/// parsing those parts of the given Method declaration that could
5202/// not be parsed earlier (C++ [class.mem]p2), such as default
5203/// arguments. This action should enter the scope of the given
5204/// Method declaration as if we had just parsed the qualified method
5205/// name. However, it should not bring the parameters into scope;
5206/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005207void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005208}
5209
5210/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5211/// C++ method declaration. We're (re-)introducing the given
5212/// function parameter into scope for use in parsing later parts of
5213/// the method declaration. For example, we could see an
5214/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005215void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005216 if (!ParamD)
5217 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005218
John McCalld226f652010-08-21 09:40:31 +00005219 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005220
5221 // If this parameter has an unparsed default argument, clear it out
5222 // to make way for the parsed default argument.
5223 if (Param->hasUnparsedDefaultArg())
5224 Param->setDefaultArg(0);
5225
John McCalld226f652010-08-21 09:40:31 +00005226 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005227 if (Param->getDeclName())
5228 IdResolver.AddDecl(Param);
5229}
5230
5231/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5232/// processing the delayed method declaration for Method. The method
5233/// declaration is now considered finished. There may be a separate
5234/// ActOnStartOfFunctionDef action later (not necessarily
5235/// immediately!) for this method, if it was also defined inside the
5236/// class body.
John McCalld226f652010-08-21 09:40:31 +00005237void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005238 if (!MethodD)
5239 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005240
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005241 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005242
John McCalld226f652010-08-21 09:40:31 +00005243 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005244
5245 // Now that we have our default arguments, check the constructor
5246 // again. It could produce additional diagnostics or affect whether
5247 // the class has implicitly-declared destructors, among other
5248 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005249 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5250 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005251
5252 // Check the default arguments, which we may have added.
5253 if (!Method->isInvalidDecl())
5254 CheckCXXDefaultArguments(Method);
5255}
5256
Douglas Gregor42a552f2008-11-05 20:51:48 +00005257/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005258/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005259/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005260/// emit diagnostics and set the invalid bit to true. In any case, the type
5261/// will be updated to reflect a well-formed type for the constructor and
5262/// returned.
5263QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005264 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005265 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005266
5267 // C++ [class.ctor]p3:
5268 // A constructor shall not be virtual (10.3) or static (9.4). A
5269 // constructor can be invoked for a const, volatile or const
5270 // volatile object. A constructor shall not be declared const,
5271 // volatile, or const volatile (9.3.2).
5272 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005273 if (!D.isInvalidType())
5274 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5275 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5276 << SourceRange(D.getIdentifierLoc());
5277 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005278 }
John McCalld931b082010-08-26 03:08:43 +00005279 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005280 if (!D.isInvalidType())
5281 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5282 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5283 << SourceRange(D.getIdentifierLoc());
5284 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005285 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005286 }
Mike Stump1eb44332009-09-09 15:08:12 +00005287
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005288 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005289 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005290 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005291 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5292 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005293 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005294 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5295 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005296 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005297 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5298 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005299 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005300 }
Mike Stump1eb44332009-09-09 15:08:12 +00005301
Douglas Gregorc938c162011-01-26 05:01:58 +00005302 // C++0x [class.ctor]p4:
5303 // A constructor shall not be declared with a ref-qualifier.
5304 if (FTI.hasRefQualifier()) {
5305 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5306 << FTI.RefQualifierIsLValueRef
5307 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5308 D.setInvalidType();
5309 }
5310
Douglas Gregor42a552f2008-11-05 20:51:48 +00005311 // Rebuild the function type "R" without any type qualifiers (in
5312 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005313 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005314 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005315 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5316 return R;
5317
5318 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5319 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005320 EPI.RefQualifier = RQ_None;
5321
Chris Lattner65401802009-04-25 08:28:21 +00005322 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005323 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005324}
5325
Douglas Gregor72b505b2008-12-16 21:30:33 +00005326/// CheckConstructor - Checks a fully-formed constructor for
5327/// well-formedness, issuing any diagnostics required. Returns true if
5328/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005329void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005330 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005331 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5332 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005333 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005334
5335 // C++ [class.copy]p3:
5336 // A declaration of a constructor for a class X is ill-formed if
5337 // its first parameter is of type (optionally cv-qualified) X and
5338 // either there are no other parameters or else all other
5339 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005340 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005341 ((Constructor->getNumParams() == 1) ||
5342 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005343 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5344 Constructor->getTemplateSpecializationKind()
5345 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005346 QualType ParamType = Constructor->getParamDecl(0)->getType();
5347 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5348 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005349 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005350 const char *ConstRef
5351 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5352 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005353 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005354 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005355
5356 // FIXME: Rather that making the constructor invalid, we should endeavor
5357 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005358 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005359 }
5360 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005361}
5362
John McCall15442822010-08-04 01:04:25 +00005363/// CheckDestructor - Checks a fully-formed destructor definition for
5364/// well-formedness, issuing any diagnostics required. Returns true
5365/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005366bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005367 CXXRecordDecl *RD = Destructor->getParent();
5368
5369 if (Destructor->isVirtual()) {
5370 SourceLocation Loc;
5371
5372 if (!Destructor->isImplicit())
5373 Loc = Destructor->getLocation();
5374 else
5375 Loc = RD->getLocation();
5376
5377 // If we have a virtual destructor, look up the deallocation function
5378 FunctionDecl *OperatorDelete = 0;
5379 DeclarationName Name =
5380 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005381 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005382 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005383
5384 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005385
5386 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005387 }
Anders Carlsson37909802009-11-30 21:24:50 +00005388
5389 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005390}
5391
Mike Stump1eb44332009-09-09 15:08:12 +00005392static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005393FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5394 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5395 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005396 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005397}
5398
Douglas Gregor42a552f2008-11-05 20:51:48 +00005399/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5400/// the well-formednes of the destructor declarator @p D with type @p
5401/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005402/// emit diagnostics and set the declarator to invalid. Even if this happens,
5403/// will be updated to reflect a well-formed type for the destructor and
5404/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005405QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005406 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005407 // C++ [class.dtor]p1:
5408 // [...] A typedef-name that names a class is a class-name
5409 // (7.1.3); however, a typedef-name that names a class shall not
5410 // be used as the identifier in the declarator for a destructor
5411 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005412 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005413 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005414 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005415 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005416 else if (const TemplateSpecializationType *TST =
5417 DeclaratorType->getAs<TemplateSpecializationType>())
5418 if (TST->isTypeAlias())
5419 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5420 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005421
5422 // C++ [class.dtor]p2:
5423 // A destructor is used to destroy objects of its class type. A
5424 // destructor takes no parameters, and no return type can be
5425 // specified for it (not even void). The address of a destructor
5426 // shall not be taken. A destructor shall not be static. A
5427 // destructor can be invoked for a const, volatile or const
5428 // volatile object. A destructor shall not be declared const,
5429 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005430 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005431 if (!D.isInvalidType())
5432 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5433 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005434 << SourceRange(D.getIdentifierLoc())
5435 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5436
John McCalld931b082010-08-26 03:08:43 +00005437 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005438 }
Chris Lattner65401802009-04-25 08:28:21 +00005439 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005440 // Destructors don't have return types, but the parser will
5441 // happily parse something like:
5442 //
5443 // class X {
5444 // float ~X();
5445 // };
5446 //
5447 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005448 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5449 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5450 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005451 }
Mike Stump1eb44332009-09-09 15:08:12 +00005452
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005453 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005454 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005455 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005456 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5457 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005458 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005459 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5460 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005461 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005462 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5463 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005464 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005465 }
5466
Douglas Gregorc938c162011-01-26 05:01:58 +00005467 // C++0x [class.dtor]p2:
5468 // A destructor shall not be declared with a ref-qualifier.
5469 if (FTI.hasRefQualifier()) {
5470 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5471 << FTI.RefQualifierIsLValueRef
5472 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5473 D.setInvalidType();
5474 }
5475
Douglas Gregor42a552f2008-11-05 20:51:48 +00005476 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005477 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005478 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5479
5480 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005481 FTI.freeArgs();
5482 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005483 }
5484
Mike Stump1eb44332009-09-09 15:08:12 +00005485 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005486 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005487 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005488 D.setInvalidType();
5489 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005490
5491 // Rebuild the function type "R" without any type qualifiers or
5492 // parameters (in case any of the errors above fired) and with
5493 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005494 // types.
John McCalle23cf432010-12-14 08:05:40 +00005495 if (!D.isInvalidType())
5496 return R;
5497
Douglas Gregord92ec472010-07-01 05:10:53 +00005498 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005499 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5500 EPI.Variadic = false;
5501 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005502 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005503 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005504}
5505
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005506/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5507/// well-formednes of the conversion function declarator @p D with
5508/// type @p R. If there are any errors in the declarator, this routine
5509/// will emit diagnostics and return true. Otherwise, it will return
5510/// false. Either way, the type @p R will be updated to reflect a
5511/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005512void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005513 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005514 // C++ [class.conv.fct]p1:
5515 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005516 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005517 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005518 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005519 if (!D.isInvalidType())
5520 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5521 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5522 << SourceRange(D.getIdentifierLoc());
5523 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005524 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005525 }
John McCalla3f81372010-04-13 00:04:31 +00005526
5527 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5528
Chris Lattner6e475012009-04-25 08:35:12 +00005529 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005530 // Conversion functions don't have return types, but the parser will
5531 // happily parse something like:
5532 //
5533 // class X {
5534 // float operator bool();
5535 // };
5536 //
5537 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005538 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5539 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5540 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005541 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005542 }
5543
John McCalla3f81372010-04-13 00:04:31 +00005544 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5545
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005546 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005547 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005548 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5549
5550 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005551 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005552 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005553 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005554 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005555 D.setInvalidType();
5556 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005557
John McCalla3f81372010-04-13 00:04:31 +00005558 // Diagnose "&operator bool()" and other such nonsense. This
5559 // is actually a gcc extension which we don't support.
5560 if (Proto->getResultType() != ConvType) {
5561 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5562 << Proto->getResultType();
5563 D.setInvalidType();
5564 ConvType = Proto->getResultType();
5565 }
5566
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005567 // C++ [class.conv.fct]p4:
5568 // The conversion-type-id shall not represent a function type nor
5569 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005570 if (ConvType->isArrayType()) {
5571 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5572 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005573 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005574 } else if (ConvType->isFunctionType()) {
5575 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5576 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005577 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005578 }
5579
5580 // Rebuild the function type "R" without any parameters (in case any
5581 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005582 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005583 if (D.isInvalidType())
5584 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005585
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005586 // C++0x explicit conversion operators.
5587 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00005588 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005589 diag::warn_explicit_conversion_functions)
5590 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005591}
5592
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005593/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5594/// the declaration of the given C++ conversion function. This routine
5595/// is responsible for recording the conversion function in the C++
5596/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005597Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005598 assert(Conversion && "Expected to receive a conversion function declaration");
5599
Douglas Gregor9d350972008-12-12 08:25:50 +00005600 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005601
5602 // Make sure we aren't redeclaring the conversion function.
5603 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005604
5605 // C++ [class.conv.fct]p1:
5606 // [...] A conversion function is never used to convert a
5607 // (possibly cv-qualified) object to the (possibly cv-qualified)
5608 // same object type (or a reference to it), to a (possibly
5609 // cv-qualified) base class of that type (or a reference to it),
5610 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005611 // FIXME: Suppress this warning if the conversion function ends up being a
5612 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005613 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005614 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005615 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005616 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005617 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5618 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005619 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005620 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005621 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5622 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005623 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005624 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005625 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005626 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005627 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005628 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005629 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005630 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005631 }
5632
Douglas Gregore80622f2010-09-29 04:25:11 +00005633 if (FunctionTemplateDecl *ConversionTemplate
5634 = Conversion->getDescribedFunctionTemplate())
5635 return ConversionTemplate;
5636
John McCalld226f652010-08-21 09:40:31 +00005637 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005638}
5639
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005640//===----------------------------------------------------------------------===//
5641// Namespace Handling
5642//===----------------------------------------------------------------------===//
5643
John McCallea318642010-08-26 09:15:37 +00005644
5645
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005646/// ActOnStartNamespaceDef - This is called at the start of a namespace
5647/// definition.
John McCalld226f652010-08-21 09:40:31 +00005648Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005649 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005650 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005651 SourceLocation IdentLoc,
5652 IdentifierInfo *II,
5653 SourceLocation LBrace,
5654 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005655 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5656 // For anonymous namespace, take the location of the left brace.
5657 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00005658 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005659 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005660 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005661
5662 Scope *DeclRegionScope = NamespcScope->getParent();
5663
Anders Carlsson2a3503d2010-02-07 01:09:23 +00005664 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5665
John McCall90f14502010-12-10 02:59:44 +00005666 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5667 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005668
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005669 if (II) {
5670 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005671 // The identifier in an original-namespace-definition shall not
5672 // have been previously defined in the declarative region in
5673 // which the original-namespace-definition appears. The
5674 // identifier in an original-namespace-definition is the name of
5675 // the namespace. Subsequently in that declarative region, it is
5676 // treated as an original-namespace-name.
5677 //
5678 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005679 // look through using directives, just look for any ordinary names.
5680
5681 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5682 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5683 Decl::IDNS_Namespace;
5684 NamedDecl *PrevDecl = 0;
5685 for (DeclContext::lookup_result R
5686 = CurContext->getRedeclContext()->lookup(II);
5687 R.first != R.second; ++R.first) {
5688 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5689 PrevDecl = *R.first;
5690 break;
5691 }
5692 }
5693
Douglas Gregor44b43212008-12-11 16:49:14 +00005694 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5695 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005696 if (Namespc->isInline() != OrigNS->isInline()) {
5697 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005698 if (OrigNS->isInline()) {
5699 // The user probably just forgot the 'inline', so suggest that it
5700 // be added back.
5701 Diag(Namespc->getLocation(),
5702 diag::warn_inline_namespace_reopened_noninline)
5703 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5704 } else {
5705 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5706 << Namespc->isInline();
5707 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005708 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005709
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005710 // Recover by ignoring the new namespace's inline status.
5711 Namespc->setInline(OrigNS->isInline());
5712 }
5713
Douglas Gregor44b43212008-12-11 16:49:14 +00005714 // Attach this namespace decl to the chain of extended namespace
5715 // definitions.
5716 OrigNS->setNextNamespace(Namespc);
5717 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005718
Mike Stump1eb44332009-09-09 15:08:12 +00005719 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00005720 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00005721 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00005722 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005723 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005724 } else if (PrevDecl) {
5725 // This is an invalid name redefinition.
5726 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5727 << Namespc->getDeclName();
5728 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5729 Namespc->setInvalidDecl();
5730 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005731 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005732 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005733 // This is the first "real" definition of the namespace "std", so update
5734 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005735 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005736 // We had already defined a dummy namespace "std". Link this new
5737 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005738 StdNS->setNextNamespace(Namespc);
5739 StdNS->setLocation(IdentLoc);
5740 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005741 }
5742
5743 // Make our StdNamespace cache point at the first real definition of the
5744 // "std" namespace.
5745 StdNamespace = Namespc;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005746
5747 // Add this instance of "std" to the set of known namespaces
5748 KnownNamespaces[Namespc] = false;
5749 } else if (!Namespc->isInline()) {
5750 // Since this is an "original" namespace, add it to the known set of
5751 // namespaces if it is not an inline namespace.
5752 KnownNamespaces[Namespc] = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005753 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005754
5755 PushOnScopeChains(Namespc, DeclRegionScope);
5756 } else {
John McCall9aeed322009-10-01 00:25:31 +00005757 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00005758 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00005759
5760 // Link the anonymous namespace into its parent.
5761 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005762 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005763 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5764 PrevDecl = TU->getAnonymousNamespace();
5765 TU->setAnonymousNamespace(Namespc);
5766 } else {
5767 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5768 PrevDecl = ND->getAnonymousNamespace();
5769 ND->setAnonymousNamespace(Namespc);
5770 }
5771
5772 // Link the anonymous namespace with its previous declaration.
5773 if (PrevDecl) {
5774 assert(PrevDecl->isAnonymousNamespace());
5775 assert(!PrevDecl->getNextNamespace());
5776 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5777 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005778
5779 if (Namespc->isInline() != PrevDecl->isInline()) {
5780 // inline-ness must match
5781 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5782 << Namespc->isInline();
5783 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5784 Namespc->setInvalidDecl();
5785 // Recover by ignoring the new namespace's inline status.
5786 Namespc->setInline(PrevDecl->isInline());
5787 }
John McCall5fdd7642009-12-16 02:06:49 +00005788 }
John McCall9aeed322009-10-01 00:25:31 +00005789
Douglas Gregora4181472010-03-24 00:46:35 +00005790 CurContext->addDecl(Namespc);
5791
John McCall9aeed322009-10-01 00:25:31 +00005792 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5793 // behaves as if it were replaced by
5794 // namespace unique { /* empty body */ }
5795 // using namespace unique;
5796 // namespace unique { namespace-body }
5797 // where all occurrences of 'unique' in a translation unit are
5798 // replaced by the same identifier and this identifier differs
5799 // from all other identifiers in the entire program.
5800
5801 // We just create the namespace with an empty name and then add an
5802 // implicit using declaration, just like the standard suggests.
5803 //
5804 // CodeGen enforces the "universally unique" aspect by giving all
5805 // declarations semantically contained within an anonymous
5806 // namespace internal linkage.
5807
John McCall5fdd7642009-12-16 02:06:49 +00005808 if (!PrevDecl) {
5809 UsingDirectiveDecl* UD
5810 = UsingDirectiveDecl::Create(Context, CurContext,
5811 /* 'using' */ LBrace,
5812 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005813 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005814 /* identifier */ SourceLocation(),
5815 Namespc,
5816 /* Ancestor */ CurContext);
5817 UD->setImplicit();
5818 CurContext->addDecl(UD);
5819 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005820 }
5821
5822 // Although we could have an invalid decl (i.e. the namespace name is a
5823 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005824 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5825 // for the namespace has the declarations that showed up in that particular
5826 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005827 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005828 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005829}
5830
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005831/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5832/// is a namespace alias, returns the namespace it points to.
5833static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5834 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5835 return AD->getNamespace();
5836 return dyn_cast_or_null<NamespaceDecl>(D);
5837}
5838
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005839/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5840/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005841void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005842 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5843 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005844 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005845 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005846 if (Namespc->hasAttr<VisibilityAttr>())
5847 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005848}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005849
John McCall384aff82010-08-25 07:42:41 +00005850CXXRecordDecl *Sema::getStdBadAlloc() const {
5851 return cast_or_null<CXXRecordDecl>(
5852 StdBadAlloc.get(Context.getExternalSource()));
5853}
5854
5855NamespaceDecl *Sema::getStdNamespace() const {
5856 return cast_or_null<NamespaceDecl>(
5857 StdNamespace.get(Context.getExternalSource()));
5858}
5859
Douglas Gregor66992202010-06-29 17:53:46 +00005860/// \brief Retrieve the special "std" namespace, which may require us to
5861/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005862NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005863 if (!StdNamespace) {
5864 // The "std" namespace has not yet been defined, so build one implicitly.
5865 StdNamespace = NamespaceDecl::Create(Context,
5866 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005867 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00005868 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005869 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005870 }
5871
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005872 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005873}
5874
Douglas Gregor9172aa62011-03-26 22:25:30 +00005875/// \brief Determine whether a using statement is in a context where it will be
5876/// apply in all contexts.
5877static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5878 switch (CurContext->getDeclKind()) {
5879 case Decl::TranslationUnit:
5880 return true;
5881 case Decl::LinkageSpec:
5882 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5883 default:
5884 return false;
5885 }
5886}
5887
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005888static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5889 CXXScopeSpec &SS,
5890 SourceLocation IdentLoc,
5891 IdentifierInfo *Ident) {
5892 R.clear();
5893 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5894 R.getLookupKind(), Sc, &SS, NULL,
5895 false, S.CTC_NoKeywords, NULL)) {
5896 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5897 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5898 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5899 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5900 if (DeclContext *DC = S.computeDeclContext(SS, false))
5901 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5902 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5903 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5904 else
5905 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5906 << Ident << CorrectedQuotedStr
5907 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5908
5909 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5910 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5911
5912 Ident = Corrected.getCorrectionAsIdentifierInfo();
5913 R.addDecl(Corrected.getCorrectionDecl());
5914 return true;
5915 }
5916 R.setLookupName(Ident);
5917 }
5918 return false;
5919}
5920
John McCalld226f652010-08-21 09:40:31 +00005921Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005922 SourceLocation UsingLoc,
5923 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005924 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005925 SourceLocation IdentLoc,
5926 IdentifierInfo *NamespcName,
5927 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005928 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5929 assert(NamespcName && "Invalid NamespcName.");
5930 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005931
5932 // This can only happen along a recovery path.
5933 while (S->getFlags() & Scope::TemplateParamScope)
5934 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005935 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005936
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005937 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005938 NestedNameSpecifier *Qualifier = 0;
5939 if (SS.isSet())
5940 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5941
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005942 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005943 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5944 LookupParsedName(R, S, &SS);
5945 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005946 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005947
Douglas Gregor66992202010-06-29 17:53:46 +00005948 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005949 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005950 // Allow "using namespace std;" or "using namespace ::std;" even if
5951 // "std" hasn't been defined yet, for GCC compatibility.
5952 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5953 NamespcName->isStr("std")) {
5954 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005955 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005956 R.resolveKind();
5957 }
5958 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005959 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005960 }
5961
John McCallf36e02d2009-10-09 21:13:30 +00005962 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005963 NamedDecl *Named = R.getFoundDecl();
5964 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5965 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005966 // C++ [namespace.udir]p1:
5967 // A using-directive specifies that the names in the nominated
5968 // namespace can be used in the scope in which the
5969 // using-directive appears after the using-directive. During
5970 // unqualified name lookup (3.4.1), the names appear as if they
5971 // were declared in the nearest enclosing namespace which
5972 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005973 // namespace. [Note: in this context, "contains" means "contains
5974 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005975
5976 // Find enclosing context containing both using-directive and
5977 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005978 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005979 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5980 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5981 CommonAncestor = CommonAncestor->getParent();
5982
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005983 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005984 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005985 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005986
Douglas Gregor9172aa62011-03-26 22:25:30 +00005987 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005988 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005989 Diag(IdentLoc, diag::warn_using_directive_in_header);
5990 }
5991
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005992 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005993 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005994 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005995 }
5996
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005997 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005998 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005999}
6000
6001void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6002 // If scope has associated entity, then using directive is at namespace
6003 // or translation unit scope. We add UsingDirectiveDecls, into
6004 // it's lookup structure.
6005 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006006 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006007 else
6008 // Otherwise it is block-sope. using-directives will affect lookup
6009 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006010 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006011}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006012
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006013
John McCalld226f652010-08-21 09:40:31 +00006014Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006015 AccessSpecifier AS,
6016 bool HasUsingKeyword,
6017 SourceLocation UsingLoc,
6018 CXXScopeSpec &SS,
6019 UnqualifiedId &Name,
6020 AttributeList *AttrList,
6021 bool IsTypeName,
6022 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006023 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006024
Douglas Gregor12c118a2009-11-04 16:30:06 +00006025 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006026 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006027 case UnqualifiedId::IK_Identifier:
6028 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006029 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006030 case UnqualifiedId::IK_ConversionFunctionId:
6031 break;
6032
6033 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006034 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006035 // C++0x inherited constructors.
6036 if (getLangOptions().CPlusPlus0x) break;
6037
Douglas Gregor12c118a2009-11-04 16:30:06 +00006038 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
6039 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006040 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006041
6042 case UnqualifiedId::IK_DestructorName:
6043 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6044 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006045 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006046
6047 case UnqualifiedId::IK_TemplateId:
6048 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6049 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006050 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006051 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006052
6053 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6054 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006055 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006056 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006057
John McCall60fa3cf2009-12-11 02:10:03 +00006058 // Warn about using declarations.
6059 // TODO: store that the declaration was written without 'using' and
6060 // talk about access decls instead of using decls in the
6061 // diagnostics.
6062 if (!HasUsingKeyword) {
6063 UsingLoc = Name.getSourceRange().getBegin();
6064
6065 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006066 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006067 }
6068
Douglas Gregor56c04582010-12-16 00:46:58 +00006069 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6070 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6071 return 0;
6072
John McCall9488ea12009-11-17 05:59:44 +00006073 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006074 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006075 /* IsInstantiation */ false,
6076 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006077 if (UD)
6078 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006079
John McCalld226f652010-08-21 09:40:31 +00006080 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006081}
6082
Douglas Gregor09acc982010-07-07 23:08:52 +00006083/// \brief Determine whether a using declaration considers the given
6084/// declarations as "equivalent", e.g., if they are redeclarations of
6085/// the same entity or are both typedefs of the same type.
6086static bool
6087IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6088 bool &SuppressRedeclaration) {
6089 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6090 SuppressRedeclaration = false;
6091 return true;
6092 }
6093
Richard Smith162e1c12011-04-15 14:24:37 +00006094 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6095 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006096 SuppressRedeclaration = true;
6097 return Context.hasSameType(TD1->getUnderlyingType(),
6098 TD2->getUnderlyingType());
6099 }
6100
6101 return false;
6102}
6103
6104
John McCall9f54ad42009-12-10 09:41:52 +00006105/// Determines whether to create a using shadow decl for a particular
6106/// decl, given the set of decls existing prior to this using lookup.
6107bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6108 const LookupResult &Previous) {
6109 // Diagnose finding a decl which is not from a base class of the
6110 // current class. We do this now because there are cases where this
6111 // function will silently decide not to build a shadow decl, which
6112 // will pre-empt further diagnostics.
6113 //
6114 // We don't need to do this in C++0x because we do the check once on
6115 // the qualifier.
6116 //
6117 // FIXME: diagnose the following if we care enough:
6118 // struct A { int foo; };
6119 // struct B : A { using A::foo; };
6120 // template <class T> struct C : A {};
6121 // template <class T> struct D : C<T> { using B::foo; } // <---
6122 // This is invalid (during instantiation) in C++03 because B::foo
6123 // resolves to the using decl in B, which is not a base class of D<T>.
6124 // We can't diagnose it immediately because C<T> is an unknown
6125 // specialization. The UsingShadowDecl in D<T> then points directly
6126 // to A::foo, which will look well-formed when we instantiate.
6127 // The right solution is to not collapse the shadow-decl chain.
6128 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6129 DeclContext *OrigDC = Orig->getDeclContext();
6130
6131 // Handle enums and anonymous structs.
6132 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6133 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6134 while (OrigRec->isAnonymousStructOrUnion())
6135 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6136
6137 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6138 if (OrigDC == CurContext) {
6139 Diag(Using->getLocation(),
6140 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006141 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006142 Diag(Orig->getLocation(), diag::note_using_decl_target);
6143 return true;
6144 }
6145
Douglas Gregordc355712011-02-25 00:36:19 +00006146 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006147 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006148 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006149 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006150 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006151 Diag(Orig->getLocation(), diag::note_using_decl_target);
6152 return true;
6153 }
6154 }
6155
6156 if (Previous.empty()) return false;
6157
6158 NamedDecl *Target = Orig;
6159 if (isa<UsingShadowDecl>(Target))
6160 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6161
John McCalld7533ec2009-12-11 02:33:26 +00006162 // If the target happens to be one of the previous declarations, we
6163 // don't have a conflict.
6164 //
6165 // FIXME: but we might be increasing its access, in which case we
6166 // should redeclare it.
6167 NamedDecl *NonTag = 0, *Tag = 0;
6168 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6169 I != E; ++I) {
6170 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006171 bool Result;
6172 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6173 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006174
6175 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6176 }
6177
John McCall9f54ad42009-12-10 09:41:52 +00006178 if (Target->isFunctionOrFunctionTemplate()) {
6179 FunctionDecl *FD;
6180 if (isa<FunctionTemplateDecl>(Target))
6181 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6182 else
6183 FD = cast<FunctionDecl>(Target);
6184
6185 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006186 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006187 case Ovl_Overload:
6188 return false;
6189
6190 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006191 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006192 break;
6193
6194 // We found a decl with the exact signature.
6195 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006196 // If we're in a record, we want to hide the target, so we
6197 // return true (without a diagnostic) to tell the caller not to
6198 // build a shadow decl.
6199 if (CurContext->isRecord())
6200 return true;
6201
6202 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006203 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006204 break;
6205 }
6206
6207 Diag(Target->getLocation(), diag::note_using_decl_target);
6208 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6209 return true;
6210 }
6211
6212 // Target is not a function.
6213
John McCall9f54ad42009-12-10 09:41:52 +00006214 if (isa<TagDecl>(Target)) {
6215 // No conflict between a tag and a non-tag.
6216 if (!Tag) return false;
6217
John McCall41ce66f2009-12-10 19:51:03 +00006218 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006219 Diag(Target->getLocation(), diag::note_using_decl_target);
6220 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6221 return true;
6222 }
6223
6224 // No conflict between a tag and a non-tag.
6225 if (!NonTag) return false;
6226
John McCall41ce66f2009-12-10 19:51:03 +00006227 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006228 Diag(Target->getLocation(), diag::note_using_decl_target);
6229 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6230 return true;
6231}
6232
John McCall9488ea12009-11-17 05:59:44 +00006233/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006234UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006235 UsingDecl *UD,
6236 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006237
6238 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006239 NamedDecl *Target = Orig;
6240 if (isa<UsingShadowDecl>(Target)) {
6241 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6242 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006243 }
6244
6245 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006246 = UsingShadowDecl::Create(Context, CurContext,
6247 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006248 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006249
6250 Shadow->setAccess(UD->getAccess());
6251 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6252 Shadow->setInvalidDecl();
6253
John McCall9488ea12009-11-17 05:59:44 +00006254 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006255 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006256 else
John McCall604e7f12009-12-08 07:46:18 +00006257 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006258
John McCall604e7f12009-12-08 07:46:18 +00006259
John McCall9f54ad42009-12-10 09:41:52 +00006260 return Shadow;
6261}
John McCall604e7f12009-12-08 07:46:18 +00006262
John McCall9f54ad42009-12-10 09:41:52 +00006263/// Hides a using shadow declaration. This is required by the current
6264/// using-decl implementation when a resolvable using declaration in a
6265/// class is followed by a declaration which would hide or override
6266/// one or more of the using decl's targets; for example:
6267///
6268/// struct Base { void foo(int); };
6269/// struct Derived : Base {
6270/// using Base::foo;
6271/// void foo(int);
6272/// };
6273///
6274/// The governing language is C++03 [namespace.udecl]p12:
6275///
6276/// When a using-declaration brings names from a base class into a
6277/// derived class scope, member functions in the derived class
6278/// override and/or hide member functions with the same name and
6279/// parameter types in a base class (rather than conflicting).
6280///
6281/// There are two ways to implement this:
6282/// (1) optimistically create shadow decls when they're not hidden
6283/// by existing declarations, or
6284/// (2) don't create any shadow decls (or at least don't make them
6285/// visible) until we've fully parsed/instantiated the class.
6286/// The problem with (1) is that we might have to retroactively remove
6287/// a shadow decl, which requires several O(n) operations because the
6288/// decl structures are (very reasonably) not designed for removal.
6289/// (2) avoids this but is very fiddly and phase-dependent.
6290void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006291 if (Shadow->getDeclName().getNameKind() ==
6292 DeclarationName::CXXConversionFunctionName)
6293 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6294
John McCall9f54ad42009-12-10 09:41:52 +00006295 // Remove it from the DeclContext...
6296 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006297
John McCall9f54ad42009-12-10 09:41:52 +00006298 // ...and the scope, if applicable...
6299 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006300 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006301 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006302 }
6303
John McCall9f54ad42009-12-10 09:41:52 +00006304 // ...and the using decl.
6305 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6306
6307 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006308 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006309}
6310
John McCall7ba107a2009-11-18 02:36:19 +00006311/// Builds a using declaration.
6312///
6313/// \param IsInstantiation - Whether this call arises from an
6314/// instantiation of an unresolved using declaration. We treat
6315/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006316NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6317 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006318 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006319 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006320 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006321 bool IsInstantiation,
6322 bool IsTypeName,
6323 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006324 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006325 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006326 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006327
Anders Carlsson550b14b2009-08-28 05:49:21 +00006328 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006329
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006330 if (SS.isEmpty()) {
6331 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006332 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006333 }
Mike Stump1eb44332009-09-09 15:08:12 +00006334
John McCall9f54ad42009-12-10 09:41:52 +00006335 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006336 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006337 ForRedeclaration);
6338 Previous.setHideTags(false);
6339 if (S) {
6340 LookupName(Previous, S);
6341
6342 // It is really dumb that we have to do this.
6343 LookupResult::Filter F = Previous.makeFilter();
6344 while (F.hasNext()) {
6345 NamedDecl *D = F.next();
6346 if (!isDeclInScope(D, CurContext, S))
6347 F.erase();
6348 }
6349 F.done();
6350 } else {
6351 assert(IsInstantiation && "no scope in non-instantiation");
6352 assert(CurContext->isRecord() && "scope not record in instantiation");
6353 LookupQualifiedName(Previous, CurContext);
6354 }
6355
John McCall9f54ad42009-12-10 09:41:52 +00006356 // Check for invalid redeclarations.
6357 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6358 return 0;
6359
6360 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006361 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6362 return 0;
6363
John McCallaf8e6ed2009-11-12 03:15:40 +00006364 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006365 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006366 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006367 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006368 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006369 // FIXME: not all declaration name kinds are legal here
6370 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6371 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006372 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006373 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006374 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006375 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6376 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006377 }
John McCalled976492009-12-04 22:46:56 +00006378 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006379 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6380 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006381 }
John McCalled976492009-12-04 22:46:56 +00006382 D->setAccess(AS);
6383 CurContext->addDecl(D);
6384
6385 if (!LookupContext) return D;
6386 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006387
John McCall77bb1aa2010-05-01 00:40:08 +00006388 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006389 UD->setInvalidDecl();
6390 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006391 }
6392
Sebastian Redlf677ea32011-02-05 19:23:19 +00006393 // Constructor inheriting using decls get special treatment.
6394 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006395 if (CheckInheritedConstructorUsingDecl(UD))
6396 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006397 return UD;
6398 }
6399
6400 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006401
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006402 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006403
John McCall604e7f12009-12-08 07:46:18 +00006404 // Unlike most lookups, we don't always want to hide tag
6405 // declarations: tag names are visible through the using declaration
6406 // even if hidden by ordinary names, *except* in a dependent context
6407 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006408 if (!IsInstantiation)
6409 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006410
John McCalla24dc2e2009-11-17 02:14:36 +00006411 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006412
John McCallf36e02d2009-10-09 21:13:30 +00006413 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006414 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006415 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006416 UD->setInvalidDecl();
6417 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006418 }
6419
John McCalled976492009-12-04 22:46:56 +00006420 if (R.isAmbiguous()) {
6421 UD->setInvalidDecl();
6422 return UD;
6423 }
Mike Stump1eb44332009-09-09 15:08:12 +00006424
John McCall7ba107a2009-11-18 02:36:19 +00006425 if (IsTypeName) {
6426 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006427 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006428 Diag(IdentLoc, diag::err_using_typename_non_type);
6429 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6430 Diag((*I)->getUnderlyingDecl()->getLocation(),
6431 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006432 UD->setInvalidDecl();
6433 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006434 }
6435 } else {
6436 // If we asked for a non-typename and we got a type, error out,
6437 // but only if this is an instantiation of an unresolved using
6438 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006439 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006440 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6441 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006442 UD->setInvalidDecl();
6443 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006444 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006445 }
6446
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006447 // C++0x N2914 [namespace.udecl]p6:
6448 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006449 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006450 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6451 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006452 UD->setInvalidDecl();
6453 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006454 }
Mike Stump1eb44332009-09-09 15:08:12 +00006455
John McCall9f54ad42009-12-10 09:41:52 +00006456 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6457 if (!CheckUsingShadowDecl(UD, *I, Previous))
6458 BuildUsingShadowDecl(S, UD, *I);
6459 }
John McCall9488ea12009-11-17 05:59:44 +00006460
6461 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006462}
6463
Sebastian Redlf677ea32011-02-05 19:23:19 +00006464/// Additional checks for a using declaration referring to a constructor name.
6465bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6466 if (UD->isTypeName()) {
6467 // FIXME: Cannot specify typename when specifying constructor
6468 return true;
6469 }
6470
Douglas Gregordc355712011-02-25 00:36:19 +00006471 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006472 assert(SourceType &&
6473 "Using decl naming constructor doesn't have type in scope spec.");
6474 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6475
6476 // Check whether the named type is a direct base class.
6477 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6478 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6479 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6480 BaseIt != BaseE; ++BaseIt) {
6481 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6482 if (CanonicalSourceType == BaseType)
6483 break;
6484 }
6485
6486 if (BaseIt == BaseE) {
6487 // Did not find SourceType in the bases.
6488 Diag(UD->getUsingLocation(),
6489 diag::err_using_decl_constructor_not_in_direct_base)
6490 << UD->getNameInfo().getSourceRange()
6491 << QualType(SourceType, 0) << TargetClass;
6492 return true;
6493 }
6494
6495 BaseIt->setInheritConstructors();
6496
6497 return false;
6498}
6499
John McCall9f54ad42009-12-10 09:41:52 +00006500/// Checks that the given using declaration is not an invalid
6501/// redeclaration. Note that this is checking only for the using decl
6502/// itself, not for any ill-formedness among the UsingShadowDecls.
6503bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6504 bool isTypeName,
6505 const CXXScopeSpec &SS,
6506 SourceLocation NameLoc,
6507 const LookupResult &Prev) {
6508 // C++03 [namespace.udecl]p8:
6509 // C++0x [namespace.udecl]p10:
6510 // A using-declaration is a declaration and can therefore be used
6511 // repeatedly where (and only where) multiple declarations are
6512 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006513 //
John McCall8a726212010-11-29 18:01:58 +00006514 // That's in non-member contexts.
6515 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006516 return false;
6517
6518 NestedNameSpecifier *Qual
6519 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6520
6521 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6522 NamedDecl *D = *I;
6523
6524 bool DTypename;
6525 NestedNameSpecifier *DQual;
6526 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6527 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006528 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006529 } else if (UnresolvedUsingValueDecl *UD
6530 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6531 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006532 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006533 } else if (UnresolvedUsingTypenameDecl *UD
6534 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6535 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006536 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006537 } else continue;
6538
6539 // using decls differ if one says 'typename' and the other doesn't.
6540 // FIXME: non-dependent using decls?
6541 if (isTypeName != DTypename) continue;
6542
6543 // using decls differ if they name different scopes (but note that
6544 // template instantiation can cause this check to trigger when it
6545 // didn't before instantiation).
6546 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6547 Context.getCanonicalNestedNameSpecifier(DQual))
6548 continue;
6549
6550 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006551 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006552 return true;
6553 }
6554
6555 return false;
6556}
6557
John McCall604e7f12009-12-08 07:46:18 +00006558
John McCalled976492009-12-04 22:46:56 +00006559/// Checks that the given nested-name qualifier used in a using decl
6560/// in the current context is appropriately related to the current
6561/// scope. If an error is found, diagnoses it and returns true.
6562bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6563 const CXXScopeSpec &SS,
6564 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006565 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006566
John McCall604e7f12009-12-08 07:46:18 +00006567 if (!CurContext->isRecord()) {
6568 // C++03 [namespace.udecl]p3:
6569 // C++0x [namespace.udecl]p8:
6570 // A using-declaration for a class member shall be a member-declaration.
6571
6572 // If we weren't able to compute a valid scope, it must be a
6573 // dependent class scope.
6574 if (!NamedContext || NamedContext->isRecord()) {
6575 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6576 << SS.getRange();
6577 return true;
6578 }
6579
6580 // Otherwise, everything is known to be fine.
6581 return false;
6582 }
6583
6584 // The current scope is a record.
6585
6586 // If the named context is dependent, we can't decide much.
6587 if (!NamedContext) {
6588 // FIXME: in C++0x, we can diagnose if we can prove that the
6589 // nested-name-specifier does not refer to a base class, which is
6590 // still possible in some cases.
6591
6592 // Otherwise we have to conservatively report that things might be
6593 // okay.
6594 return false;
6595 }
6596
6597 if (!NamedContext->isRecord()) {
6598 // Ideally this would point at the last name in the specifier,
6599 // but we don't have that level of source info.
6600 Diag(SS.getRange().getBegin(),
6601 diag::err_using_decl_nested_name_specifier_is_not_class)
6602 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6603 return true;
6604 }
6605
Douglas Gregor6fb07292010-12-21 07:41:49 +00006606 if (!NamedContext->isDependentContext() &&
6607 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6608 return true;
6609
John McCall604e7f12009-12-08 07:46:18 +00006610 if (getLangOptions().CPlusPlus0x) {
6611 // C++0x [namespace.udecl]p3:
6612 // In a using-declaration used as a member-declaration, the
6613 // nested-name-specifier shall name a base class of the class
6614 // being defined.
6615
6616 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6617 cast<CXXRecordDecl>(NamedContext))) {
6618 if (CurContext == NamedContext) {
6619 Diag(NameLoc,
6620 diag::err_using_decl_nested_name_specifier_is_current_class)
6621 << SS.getRange();
6622 return true;
6623 }
6624
6625 Diag(SS.getRange().getBegin(),
6626 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6627 << (NestedNameSpecifier*) SS.getScopeRep()
6628 << cast<CXXRecordDecl>(CurContext)
6629 << SS.getRange();
6630 return true;
6631 }
6632
6633 return false;
6634 }
6635
6636 // C++03 [namespace.udecl]p4:
6637 // A using-declaration used as a member-declaration shall refer
6638 // to a member of a base class of the class being defined [etc.].
6639
6640 // Salient point: SS doesn't have to name a base class as long as
6641 // lookup only finds members from base classes. Therefore we can
6642 // diagnose here only if we can prove that that can't happen,
6643 // i.e. if the class hierarchies provably don't intersect.
6644
6645 // TODO: it would be nice if "definitely valid" results were cached
6646 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6647 // need to be repeated.
6648
6649 struct UserData {
6650 llvm::DenseSet<const CXXRecordDecl*> Bases;
6651
6652 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6653 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6654 Data->Bases.insert(Base);
6655 return true;
6656 }
6657
6658 bool hasDependentBases(const CXXRecordDecl *Class) {
6659 return !Class->forallBases(collect, this);
6660 }
6661
6662 /// Returns true if the base is dependent or is one of the
6663 /// accumulated base classes.
6664 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6665 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6666 return !Data->Bases.count(Base);
6667 }
6668
6669 bool mightShareBases(const CXXRecordDecl *Class) {
6670 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6671 }
6672 };
6673
6674 UserData Data;
6675
6676 // Returns false if we find a dependent base.
6677 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6678 return false;
6679
6680 // Returns false if the class has a dependent base or if it or one
6681 // of its bases is present in the base set of the current context.
6682 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6683 return false;
6684
6685 Diag(SS.getRange().getBegin(),
6686 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6687 << (NestedNameSpecifier*) SS.getScopeRep()
6688 << cast<CXXRecordDecl>(CurContext)
6689 << SS.getRange();
6690
6691 return true;
John McCalled976492009-12-04 22:46:56 +00006692}
6693
Richard Smith162e1c12011-04-15 14:24:37 +00006694Decl *Sema::ActOnAliasDeclaration(Scope *S,
6695 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006696 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006697 SourceLocation UsingLoc,
6698 UnqualifiedId &Name,
6699 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006700 // Skip up to the relevant declaration scope.
6701 while (S->getFlags() & Scope::TemplateParamScope)
6702 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006703 assert((S->getFlags() & Scope::DeclScope) &&
6704 "got alias-declaration outside of declaration scope");
6705
6706 if (Type.isInvalid())
6707 return 0;
6708
6709 bool Invalid = false;
6710 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6711 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006712 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006713
6714 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6715 return 0;
6716
6717 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006718 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006719 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006720 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6721 TInfo->getTypeLoc().getBeginLoc());
6722 }
Richard Smith162e1c12011-04-15 14:24:37 +00006723
6724 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6725 LookupName(Previous, S);
6726
6727 // Warn about shadowing the name of a template parameter.
6728 if (Previous.isSingleResult() &&
6729 Previous.getFoundDecl()->isTemplateParameter()) {
6730 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6731 Previous.getFoundDecl()))
6732 Invalid = true;
6733 Previous.clear();
6734 }
6735
6736 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6737 "name in alias declaration must be an identifier");
6738 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6739 Name.StartLocation,
6740 Name.Identifier, TInfo);
6741
6742 NewTD->setAccess(AS);
6743
6744 if (Invalid)
6745 NewTD->setInvalidDecl();
6746
Richard Smith3e4c6c42011-05-05 21:57:07 +00006747 CheckTypedefForVariablyModifiedType(S, NewTD);
6748 Invalid |= NewTD->isInvalidDecl();
6749
Richard Smith162e1c12011-04-15 14:24:37 +00006750 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006751
6752 NamedDecl *NewND;
6753 if (TemplateParamLists.size()) {
6754 TypeAliasTemplateDecl *OldDecl = 0;
6755 TemplateParameterList *OldTemplateParams = 0;
6756
6757 if (TemplateParamLists.size() != 1) {
6758 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6759 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6760 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6761 }
6762 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6763
6764 // Only consider previous declarations in the same scope.
6765 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6766 /*ExplicitInstantiationOrSpecialization*/false);
6767 if (!Previous.empty()) {
6768 Redeclaration = true;
6769
6770 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6771 if (!OldDecl && !Invalid) {
6772 Diag(UsingLoc, diag::err_redefinition_different_kind)
6773 << Name.Identifier;
6774
6775 NamedDecl *OldD = Previous.getRepresentativeDecl();
6776 if (OldD->getLocation().isValid())
6777 Diag(OldD->getLocation(), diag::note_previous_definition);
6778
6779 Invalid = true;
6780 }
6781
6782 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6783 if (TemplateParameterListsAreEqual(TemplateParams,
6784 OldDecl->getTemplateParameters(),
6785 /*Complain=*/true,
6786 TPL_TemplateMatch))
6787 OldTemplateParams = OldDecl->getTemplateParameters();
6788 else
6789 Invalid = true;
6790
6791 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6792 if (!Invalid &&
6793 !Context.hasSameType(OldTD->getUnderlyingType(),
6794 NewTD->getUnderlyingType())) {
6795 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6796 // but we can't reasonably accept it.
6797 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6798 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6799 if (OldTD->getLocation().isValid())
6800 Diag(OldTD->getLocation(), diag::note_previous_definition);
6801 Invalid = true;
6802 }
6803 }
6804 }
6805
6806 // Merge any previous default template arguments into our parameters,
6807 // and check the parameter list.
6808 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6809 TPC_TypeAliasTemplate))
6810 return 0;
6811
6812 TypeAliasTemplateDecl *NewDecl =
6813 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6814 Name.Identifier, TemplateParams,
6815 NewTD);
6816
6817 NewDecl->setAccess(AS);
6818
6819 if (Invalid)
6820 NewDecl->setInvalidDecl();
6821 else if (OldDecl)
6822 NewDecl->setPreviousDeclaration(OldDecl);
6823
6824 NewND = NewDecl;
6825 } else {
6826 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6827 NewND = NewTD;
6828 }
Richard Smith162e1c12011-04-15 14:24:37 +00006829
6830 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006831 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006832
Richard Smith3e4c6c42011-05-05 21:57:07 +00006833 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006834}
6835
John McCalld226f652010-08-21 09:40:31 +00006836Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006837 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006838 SourceLocation AliasLoc,
6839 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006840 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006841 SourceLocation IdentLoc,
6842 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006843
Anders Carlsson81c85c42009-03-28 23:53:49 +00006844 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006845 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6846 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006847
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006848 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006849 NamedDecl *PrevDecl
6850 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6851 ForRedeclaration);
6852 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6853 PrevDecl = 0;
6854
6855 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006856 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006857 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006858 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006859 // FIXME: At some point, we'll want to create the (redundant)
6860 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006861 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006862 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006863 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006864 }
Mike Stump1eb44332009-09-09 15:08:12 +00006865
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006866 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6867 diag::err_redefinition_different_kind;
6868 Diag(AliasLoc, DiagID) << Alias;
6869 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006870 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006871 }
6872
John McCalla24dc2e2009-11-17 02:14:36 +00006873 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006874 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006875
John McCallf36e02d2009-10-09 21:13:30 +00006876 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006877 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006878 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006879 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006880 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006881 }
Mike Stump1eb44332009-09-09 15:08:12 +00006882
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006883 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006884 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006885 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006886 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006887
John McCall3dbd3d52010-02-16 06:53:13 +00006888 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006889 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006890}
6891
Douglas Gregor39957dc2010-05-01 15:04:51 +00006892namespace {
6893 /// \brief Scoped object used to handle the state changes required in Sema
6894 /// to implicitly define the body of a C++ member function;
6895 class ImplicitlyDefinedFunctionScope {
6896 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006897 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006898
6899 public:
6900 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006901 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006902 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006903 S.PushFunctionScope();
6904 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6905 }
6906
6907 ~ImplicitlyDefinedFunctionScope() {
6908 S.PopExpressionEvaluationContext();
6909 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006910 }
6911 };
6912}
6913
Sean Hunt001cad92011-05-10 00:49:42 +00006914Sema::ImplicitExceptionSpecification
6915Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006916 // C++ [except.spec]p14:
6917 // An implicitly declared special member function (Clause 12) shall have an
6918 // exception-specification. [...]
6919 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006920 if (ClassDecl->isInvalidDecl())
6921 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006922
Sebastian Redl60618fa2011-03-12 11:50:43 +00006923 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006924 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6925 BEnd = ClassDecl->bases_end();
6926 B != BEnd; ++B) {
6927 if (B->isVirtual()) // Handled below.
6928 continue;
6929
Douglas Gregor18274032010-07-03 00:47:00 +00006930 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6931 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006932 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6933 // If this is a deleted function, add it anyway. This might be conformant
6934 // with the standard. This might not. I'm not sure. It might not matter.
6935 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006936 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006937 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006938 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006939
6940 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006941 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6942 BEnd = ClassDecl->vbases_end();
6943 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006944 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6945 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006946 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6947 // If this is a deleted function, add it anyway. This might be conformant
6948 // with the standard. This might not. I'm not sure. It might not matter.
6949 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006950 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006951 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006952 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006953
6954 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006955 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6956 FEnd = ClassDecl->field_end();
6957 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006958 if (F->hasInClassInitializer()) {
6959 if (Expr *E = F->getInClassInitializer())
6960 ExceptSpec.CalledExpr(E);
6961 else if (!F->isInvalidDecl())
6962 ExceptSpec.SetDelayed();
6963 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006964 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006965 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6966 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6967 // If this is a deleted function, add it anyway. This might be conformant
6968 // with the standard. This might not. I'm not sure. It might not matter.
6969 // In particular, the problem is that this function never gets called. It
6970 // might just be ill-formed because this function attempts to refer to
6971 // a deleted function here.
6972 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006973 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006974 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006975 }
John McCalle23cf432010-12-14 08:05:40 +00006976
Sean Hunt001cad92011-05-10 00:49:42 +00006977 return ExceptSpec;
6978}
6979
6980CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6981 CXXRecordDecl *ClassDecl) {
6982 // C++ [class.ctor]p5:
6983 // A default constructor for a class X is a constructor of class X
6984 // that can be called without an argument. If there is no
6985 // user-declared constructor for class X, a default constructor is
6986 // implicitly declared. An implicitly-declared default constructor
6987 // is an inline public member of its class.
6988 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6989 "Should not build implicit default constructor!");
6990
6991 ImplicitExceptionSpecification Spec =
6992 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6993 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006994
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006995 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006996 CanQualType ClassType
6997 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006998 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006999 DeclarationName Name
7000 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007001 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007002 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007003 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00007004 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00007005 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00007006 /*TInfo=*/0,
7007 /*isExplicit=*/false,
7008 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007009 /*isImplicitlyDeclared=*/true,
7010 // FIXME: apply the rules for definitions here
7011 /*isConstexpr=*/false);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007012 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007013 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007014 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007015 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007016
7017 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007018 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7019
Douglas Gregor23c94db2010-07-02 17:43:08 +00007020 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007021 PushOnScopeChains(DefaultCon, S, false);
7022 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007023
Sean Hunte16da072011-10-10 06:18:57 +00007024 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007025 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007026
Douglas Gregor32df23e2010-07-01 22:02:46 +00007027 return DefaultCon;
7028}
7029
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007030void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7031 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007032 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007033 !Constructor->doesThisDeclarationHaveABody() &&
7034 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007035 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007036
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007037 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007038 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007039
Douglas Gregor39957dc2010-05-01 15:04:51 +00007040 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007041 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007042 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007043 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007044 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007045 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007046 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007047 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007048 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007049
7050 SourceLocation Loc = Constructor->getLocation();
7051 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7052
7053 Constructor->setUsed();
7054 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007055
7056 if (ASTMutationListener *L = getASTMutationListener()) {
7057 L->CompletedImplicitDefinition(Constructor);
7058 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007059}
7060
Richard Smith7a614d82011-06-11 17:19:42 +00007061/// Get any existing defaulted default constructor for the given class. Do not
7062/// implicitly define one if it does not exist.
7063static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7064 CXXRecordDecl *D) {
7065 ASTContext &Context = Self.Context;
7066 QualType ClassType = Context.getTypeDeclType(D);
7067 DeclarationName ConstructorName
7068 = Context.DeclarationNames.getCXXConstructorName(
7069 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7070
7071 DeclContext::lookup_const_iterator Con, ConEnd;
7072 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7073 Con != ConEnd; ++Con) {
7074 // A function template cannot be defaulted.
7075 if (isa<FunctionTemplateDecl>(*Con))
7076 continue;
7077
7078 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7079 if (Constructor->isDefaultConstructor())
7080 return Constructor->isDefaulted() ? Constructor : 0;
7081 }
7082 return 0;
7083}
7084
7085void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7086 if (!D) return;
7087 AdjustDeclIfTemplate(D);
7088
7089 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7090 CXXConstructorDecl *CtorDecl
7091 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7092
7093 if (!CtorDecl) return;
7094
7095 // Compute the exception specification for the default constructor.
7096 const FunctionProtoType *CtorTy =
7097 CtorDecl->getType()->castAs<FunctionProtoType>();
7098 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7099 ImplicitExceptionSpecification Spec =
7100 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7101 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7102 assert(EPI.ExceptionSpecType != EST_Delayed);
7103
7104 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7105 }
7106
7107 // If the default constructor is explicitly defaulted, checking the exception
7108 // specification is deferred until now.
7109 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7110 !ClassDecl->isDependentType())
7111 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7112}
7113
Sebastian Redlf677ea32011-02-05 19:23:19 +00007114void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7115 // We start with an initial pass over the base classes to collect those that
7116 // inherit constructors from. If there are none, we can forgo all further
7117 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007118 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007119 BasesVector BasesToInheritFrom;
7120 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7121 BaseE = ClassDecl->bases_end();
7122 BaseIt != BaseE; ++BaseIt) {
7123 if (BaseIt->getInheritConstructors()) {
7124 QualType Base = BaseIt->getType();
7125 if (Base->isDependentType()) {
7126 // If we inherit constructors from anything that is dependent, just
7127 // abort processing altogether. We'll get another chance for the
7128 // instantiations.
7129 return;
7130 }
7131 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7132 }
7133 }
7134 if (BasesToInheritFrom.empty())
7135 return;
7136
7137 // Now collect the constructors that we already have in the current class.
7138 // Those take precedence over inherited constructors.
7139 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7140 // unless there is a user-declared constructor with the same signature in
7141 // the class where the using-declaration appears.
7142 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7143 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7144 CtorE = ClassDecl->ctor_end();
7145 CtorIt != CtorE; ++CtorIt) {
7146 ExistingConstructors.insert(
7147 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7148 }
7149
7150 Scope *S = getScopeForContext(ClassDecl);
7151 DeclarationName CreatedCtorName =
7152 Context.DeclarationNames.getCXXConstructorName(
7153 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7154
7155 // Now comes the true work.
7156 // First, we keep a map from constructor types to the base that introduced
7157 // them. Needed for finding conflicting constructors. We also keep the
7158 // actually inserted declarations in there, for pretty diagnostics.
7159 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7160 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7161 ConstructorToSourceMap InheritedConstructors;
7162 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7163 BaseE = BasesToInheritFrom.end();
7164 BaseIt != BaseE; ++BaseIt) {
7165 const RecordType *Base = *BaseIt;
7166 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7167 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7168 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7169 CtorE = BaseDecl->ctor_end();
7170 CtorIt != CtorE; ++CtorIt) {
7171 // Find the using declaration for inheriting this base's constructors.
7172 DeclarationName Name =
7173 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7174 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7175 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7176 SourceLocation UsingLoc = UD ? UD->getLocation() :
7177 ClassDecl->getLocation();
7178
7179 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7180 // from the class X named in the using-declaration consists of actual
7181 // constructors and notional constructors that result from the
7182 // transformation of defaulted parameters as follows:
7183 // - all non-template default constructors of X, and
7184 // - for each non-template constructor of X that has at least one
7185 // parameter with a default argument, the set of constructors that
7186 // results from omitting any ellipsis parameter specification and
7187 // successively omitting parameters with a default argument from the
7188 // end of the parameter-type-list.
7189 CXXConstructorDecl *BaseCtor = *CtorIt;
7190 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7191 const FunctionProtoType *BaseCtorType =
7192 BaseCtor->getType()->getAs<FunctionProtoType>();
7193
7194 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7195 maxParams = BaseCtor->getNumParams();
7196 params <= maxParams; ++params) {
7197 // Skip default constructors. They're never inherited.
7198 if (params == 0)
7199 continue;
7200 // Skip copy and move constructors for the same reason.
7201 if (CanBeCopyOrMove && params == 1)
7202 continue;
7203
7204 // Build up a function type for this particular constructor.
7205 // FIXME: The working paper does not consider that the exception spec
7206 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007207 // source. This code doesn't yet, either. When it does, this code will
7208 // need to be delayed until after exception specifications and in-class
7209 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007210 const Type *NewCtorType;
7211 if (params == maxParams)
7212 NewCtorType = BaseCtorType;
7213 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007214 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007215 for (unsigned i = 0; i < params; ++i) {
7216 Args.push_back(BaseCtorType->getArgType(i));
7217 }
7218 FunctionProtoType::ExtProtoInfo ExtInfo =
7219 BaseCtorType->getExtProtoInfo();
7220 ExtInfo.Variadic = false;
7221 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7222 Args.data(), params, ExtInfo)
7223 .getTypePtr();
7224 }
7225 const Type *CanonicalNewCtorType =
7226 Context.getCanonicalType(NewCtorType);
7227
7228 // Now that we have the type, first check if the class already has a
7229 // constructor with this signature.
7230 if (ExistingConstructors.count(CanonicalNewCtorType))
7231 continue;
7232
7233 // Then we check if we have already declared an inherited constructor
7234 // with this signature.
7235 std::pair<ConstructorToSourceMap::iterator, bool> result =
7236 InheritedConstructors.insert(std::make_pair(
7237 CanonicalNewCtorType,
7238 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7239 if (!result.second) {
7240 // Already in the map. If it came from a different class, that's an
7241 // error. Not if it's from the same.
7242 CanQualType PreviousBase = result.first->second.first;
7243 if (CanonicalBase != PreviousBase) {
7244 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7245 const CXXConstructorDecl *PrevBaseCtor =
7246 PrevCtor->getInheritedConstructor();
7247 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7248
7249 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7250 Diag(BaseCtor->getLocation(),
7251 diag::note_using_decl_constructor_conflict_current_ctor);
7252 Diag(PrevBaseCtor->getLocation(),
7253 diag::note_using_decl_constructor_conflict_previous_ctor);
7254 Diag(PrevCtor->getLocation(),
7255 diag::note_using_decl_constructor_conflict_previous_using);
7256 }
7257 continue;
7258 }
7259
7260 // OK, we're there, now add the constructor.
7261 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007262 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007263 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7264 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007265 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7266 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007267 /*ImplicitlyDeclared=*/true,
7268 // FIXME: Due to a defect in the standard, we treat inherited
7269 // constructors as constexpr even if that makes them ill-formed.
7270 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007271 NewCtor->setAccess(BaseCtor->getAccess());
7272
7273 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007274 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007275 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007276 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7277 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007278 /*IdentifierInfo=*/0,
7279 BaseCtorType->getArgType(i),
7280 /*TInfo=*/0, SC_None,
7281 SC_None, /*DefaultArg=*/0));
7282 }
David Blaikie4278c652011-09-21 18:16:56 +00007283 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007284 NewCtor->setInheritedConstructor(BaseCtor);
7285
7286 PushOnScopeChains(NewCtor, S, false);
7287 ClassDecl->addDecl(NewCtor);
7288 result.first->second.second = NewCtor;
7289 }
7290 }
7291 }
7292}
7293
Sean Huntcb45a0f2011-05-12 22:46:25 +00007294Sema::ImplicitExceptionSpecification
7295Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007296 // C++ [except.spec]p14:
7297 // An implicitly declared special member function (Clause 12) shall have
7298 // an exception-specification.
7299 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007300 if (ClassDecl->isInvalidDecl())
7301 return ExceptSpec;
7302
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007303 // Direct base-class destructors.
7304 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7305 BEnd = ClassDecl->bases_end();
7306 B != BEnd; ++B) {
7307 if (B->isVirtual()) // Handled below.
7308 continue;
7309
7310 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7311 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007312 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007313 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007314
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007315 // Virtual base-class destructors.
7316 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7317 BEnd = ClassDecl->vbases_end();
7318 B != BEnd; ++B) {
7319 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7320 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007321 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007322 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007323
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007324 // Field destructors.
7325 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7326 FEnd = ClassDecl->field_end();
7327 F != FEnd; ++F) {
7328 if (const RecordType *RecordTy
7329 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7330 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007331 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007332 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007333
Sean Huntcb45a0f2011-05-12 22:46:25 +00007334 return ExceptSpec;
7335}
7336
7337CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7338 // C++ [class.dtor]p2:
7339 // If a class has no user-declared destructor, a destructor is
7340 // declared implicitly. An implicitly-declared destructor is an
7341 // inline public member of its class.
7342
7343 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007344 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007345 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7346
Douglas Gregor4923aa22010-07-02 20:37:36 +00007347 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007348 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007349
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007350 CanQualType ClassType
7351 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007352 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007353 DeclarationName Name
7354 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007355 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007356 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007357 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7358 /*isInline=*/true,
7359 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007360 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007361 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007362 Destructor->setImplicit();
7363 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007364
7365 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007366 ++ASTContext::NumImplicitDestructorsDeclared;
7367
7368 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007369 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007370 PushOnScopeChains(Destructor, S, false);
7371 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007372
7373 // This could be uniqued if it ever proves significant.
7374 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007375
7376 if (ShouldDeleteDestructor(Destructor))
7377 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007378
7379 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007380
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007381 return Destructor;
7382}
7383
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007384void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007385 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007386 assert((Destructor->isDefaulted() &&
7387 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007388 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007389 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007390 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007391
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007392 if (Destructor->isInvalidDecl())
7393 return;
7394
Douglas Gregor39957dc2010-05-01 15:04:51 +00007395 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007396
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007397 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007398 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7399 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007400
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007401 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007402 Diag(CurrentLocation, diag::note_member_synthesized_at)
7403 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7404
7405 Destructor->setInvalidDecl();
7406 return;
7407 }
7408
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007409 SourceLocation Loc = Destructor->getLocation();
7410 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007411 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007412 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007413 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007414
7415 if (ASTMutationListener *L = getASTMutationListener()) {
7416 L->CompletedImplicitDefinition(Destructor);
7417 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007418}
7419
Sebastian Redl0ee33912011-05-19 05:13:44 +00007420void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7421 CXXDestructorDecl *destructor) {
7422 // C++11 [class.dtor]p3:
7423 // A declaration of a destructor that does not have an exception-
7424 // specification is implicitly considered to have the same exception-
7425 // specification as an implicit declaration.
7426 const FunctionProtoType *dtorType = destructor->getType()->
7427 getAs<FunctionProtoType>();
7428 if (dtorType->hasExceptionSpec())
7429 return;
7430
7431 ImplicitExceptionSpecification exceptSpec =
7432 ComputeDefaultedDtorExceptionSpec(classDecl);
7433
Chandler Carruth3f224b22011-09-20 04:55:26 +00007434 // Replace the destructor's type, building off the existing one. Fortunately,
7435 // the only thing of interest in the destructor type is its extended info.
7436 // The return and arguments are fixed.
7437 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007438 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7439 epi.NumExceptions = exceptSpec.size();
7440 epi.Exceptions = exceptSpec.data();
7441 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7442
7443 destructor->setType(ty);
7444
7445 // FIXME: If the destructor has a body that could throw, and the newly created
7446 // spec doesn't allow exceptions, we should emit a warning, because this
7447 // change in behavior can break conforming C++03 programs at runtime.
7448 // However, we don't have a body yet, so it needs to be done somewhere else.
7449}
7450
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007451/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007452/// \c To.
7453///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007454/// This routine is used to copy/move the members of a class with an
7455/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007456/// copied are arrays, this routine builds for loops to copy them.
7457///
7458/// \param S The Sema object used for type-checking.
7459///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007460/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007461///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007462/// \param T The type of the expressions being copied/moved. Both expressions
7463/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007464///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007465/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007466///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007467/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007468///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007469/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007470/// Otherwise, it's a non-static member subobject.
7471///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007472/// \param Copying Whether we're copying or moving.
7473///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007474/// \param Depth Internal parameter recording the depth of the recursion.
7475///
7476/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007477static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007478BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007479 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007480 bool CopyingBaseSubobject, bool Copying,
7481 unsigned Depth = 0) {
7482 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007483 // Each subobject is assigned in the manner appropriate to its type:
7484 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007485 // - if the subobject is of class type, as if by a call to operator= with
7486 // the subobject as the object expression and the corresponding
7487 // subobject of x as a single function argument (as if by explicit
7488 // qualification; that is, ignoring any possible virtual overriding
7489 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007490 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7491 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7492
7493 // Look for operator=.
7494 DeclarationName Name
7495 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7496 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7497 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7498
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007499 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007500 LookupResult::Filter F = OpLookup.makeFilter();
7501 while (F.hasNext()) {
7502 NamedDecl *D = F.next();
7503 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007504 if (Copying ? Method->isCopyAssignmentOperator() :
7505 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007506 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007507
Douglas Gregor06a9f362010-05-01 20:49:11 +00007508 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007509 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007510 F.done();
7511
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007512 // Suppress the protected check (C++ [class.protected]) for each of the
7513 // assignment operators we found. This strange dance is required when
7514 // we're assigning via a base classes's copy-assignment operator. To
7515 // ensure that we're getting the right base class subobject (without
7516 // ambiguities), we need to cast "this" to that subobject type; to
7517 // ensure that we don't go through the virtual call mechanism, we need
7518 // to qualify the operator= name with the base class (see below). However,
7519 // this means that if the base class has a protected copy assignment
7520 // operator, the protected member access check will fail. So, we
7521 // rewrite "protected" access to "public" access in this case, since we
7522 // know by construction that we're calling from a derived class.
7523 if (CopyingBaseSubobject) {
7524 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7525 L != LEnd; ++L) {
7526 if (L.getAccess() == AS_protected)
7527 L.setAccess(AS_public);
7528 }
7529 }
7530
Douglas Gregor06a9f362010-05-01 20:49:11 +00007531 // Create the nested-name-specifier that will be used to qualify the
7532 // reference to operator=; this is required to suppress the virtual
7533 // call mechanism.
7534 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007535 SS.MakeTrivial(S.Context,
7536 NestedNameSpecifier::Create(S.Context, 0, false,
7537 T.getTypePtr()),
7538 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007539
7540 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007541 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007542 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007543 /*FirstQualifierInScope=*/0, OpLookup,
7544 /*TemplateArgs=*/0,
7545 /*SuppressQualifierCheck=*/true);
7546 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007547 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007548
7549 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007550
John McCall60d7b3a2010-08-24 06:29:42 +00007551 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007552 OpEqualRef.takeAs<Expr>(),
7553 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007554 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007555 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007556
7557 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007558 }
John McCallb0207482010-03-16 06:11:48 +00007559
Douglas Gregor06a9f362010-05-01 20:49:11 +00007560 // - if the subobject is of scalar type, the built-in assignment
7561 // operator is used.
7562 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7563 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007564 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007565 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007566 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007567
7568 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007569 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007570
7571 // - if the subobject is an array, each element is assigned, in the
7572 // manner appropriate to the element type;
7573
7574 // Construct a loop over the array bounds, e.g.,
7575 //
7576 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7577 //
7578 // that will copy each of the array elements.
7579 QualType SizeType = S.Context.getSizeType();
7580
7581 // Create the iteration variable.
7582 IdentifierInfo *IterationVarName = 0;
7583 {
7584 llvm::SmallString<8> Str;
7585 llvm::raw_svector_ostream OS(Str);
7586 OS << "__i" << Depth;
7587 IterationVarName = &S.Context.Idents.get(OS.str());
7588 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007589 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007590 IterationVarName, SizeType,
7591 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007592 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007593
7594 // Initialize the iteration variable to zero.
7595 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007596 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007597
7598 // Create a reference to the iteration variable; we'll use this several
7599 // times throughout.
7600 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00007601 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007602 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7603
7604 // Create the DeclStmt that holds the iteration variable.
7605 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7606
7607 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007608 llvm::APInt Upper
7609 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007610 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00007611 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00007612 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7613 BO_NE, S.Context.BoolTy,
7614 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007615
7616 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007617 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007618 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7619 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007620
7621 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007622 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7623 IterationVarRef, Loc));
7624 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7625 IterationVarRef, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007626 if (!Copying) // Cast to rvalue
7627 From = CastForMoving(S, From);
7628
7629 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007630 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7631 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007632 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007633 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007634 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007635
7636 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007637 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007638 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007639 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007640 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007641}
7642
Sean Hunt30de05c2011-05-14 05:23:20 +00007643std::pair<Sema::ImplicitExceptionSpecification, bool>
7644Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7645 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007646 if (ClassDecl->isInvalidDecl())
7647 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7648
Douglas Gregord3c35902010-07-01 16:36:15 +00007649 // C++ [class.copy]p10:
7650 // If the class definition does not explicitly declare a copy
7651 // assignment operator, one is declared implicitly.
7652 // The implicitly-defined copy assignment operator for a class X
7653 // will have the form
7654 //
7655 // X& X::operator=(const X&)
7656 //
7657 // if
7658 bool HasConstCopyAssignment = true;
7659
7660 // -- each direct base class B of X has a copy assignment operator
7661 // whose parameter is of type const B&, const volatile B& or B,
7662 // and
7663 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7664 BaseEnd = ClassDecl->bases_end();
7665 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007666 // We'll handle this below
7667 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7668 continue;
7669
Douglas Gregord3c35902010-07-01 16:36:15 +00007670 assert(!Base->getType()->isDependentType() &&
7671 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007672 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7673 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7674 &HasConstCopyAssignment);
7675 }
7676
7677 // In C++0x, the above citation has "or virtual added"
7678 if (LangOpts.CPlusPlus0x) {
7679 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7680 BaseEnd = ClassDecl->vbases_end();
7681 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7682 assert(!Base->getType()->isDependentType() &&
7683 "Cannot generate implicit members for class with dependent bases.");
7684 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7685 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7686 &HasConstCopyAssignment);
7687 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007688 }
7689
7690 // -- for all the nonstatic data members of X that are of a class
7691 // type M (or array thereof), each such class type has a copy
7692 // assignment operator whose parameter is of type const M&,
7693 // const volatile M& or M.
7694 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7695 FieldEnd = ClassDecl->field_end();
7696 HasConstCopyAssignment && Field != FieldEnd;
7697 ++Field) {
7698 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007699 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7700 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7701 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007702 }
7703 }
7704
7705 // Otherwise, the implicitly declared copy assignment operator will
7706 // have the form
7707 //
7708 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007709
Douglas Gregorb87786f2010-07-01 17:48:08 +00007710 // C++ [except.spec]p14:
7711 // An implicitly declared special member function (Clause 12) shall have an
7712 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007713
7714 // It is unspecified whether or not an implicit copy assignment operator
7715 // attempts to deduplicate calls to assignment operators of virtual bases are
7716 // made. As such, this exception specification is effectively unspecified.
7717 // Based on a similar decision made for constness in C++0x, we're erring on
7718 // the side of assuming such calls to be made regardless of whether they
7719 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007720 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007721 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007722 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7723 BaseEnd = ClassDecl->bases_end();
7724 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007725 if (Base->isVirtual())
7726 continue;
7727
Douglas Gregora376d102010-07-02 21:50:04 +00007728 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007729 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007730 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7731 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007732 ExceptSpec.CalledDecl(CopyAssign);
7733 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007734
7735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7736 BaseEnd = ClassDecl->vbases_end();
7737 Base != BaseEnd; ++Base) {
7738 CXXRecordDecl *BaseClassDecl
7739 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7740 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7741 ArgQuals, false, 0))
7742 ExceptSpec.CalledDecl(CopyAssign);
7743 }
7744
Douglas Gregorb87786f2010-07-01 17:48:08 +00007745 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7746 FieldEnd = ClassDecl->field_end();
7747 Field != FieldEnd;
7748 ++Field) {
7749 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007750 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7751 if (CXXMethodDecl *CopyAssign =
7752 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7753 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007754 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007755 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007756
Sean Hunt30de05c2011-05-14 05:23:20 +00007757 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7758}
7759
7760CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7761 // Note: The following rules are largely analoguous to the copy
7762 // constructor rules. Note that virtual bases are not taken into account
7763 // for determining the argument type of the operator. Note also that
7764 // operators taking an object instead of a reference are allowed.
7765
7766 ImplicitExceptionSpecification Spec(Context);
7767 bool Const;
7768 llvm::tie(Spec, Const) =
7769 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7770
7771 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7772 QualType RetType = Context.getLValueReferenceType(ArgType);
7773 if (Const)
7774 ArgType = ArgType.withConst();
7775 ArgType = Context.getLValueReferenceType(ArgType);
7776
Douglas Gregord3c35902010-07-01 16:36:15 +00007777 // An implicitly-declared copy assignment operator is an inline public
7778 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007779 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007780 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007781 SourceLocation ClassLoc = ClassDecl->getLocation();
7782 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007783 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007784 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007785 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007786 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007787 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007788 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007789 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007790 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007791 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007792 CopyAssignment->setImplicit();
7793 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007794
7795 // Add the parameter to the operator.
7796 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007797 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007798 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007799 SC_None,
7800 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007801 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007802
Douglas Gregora376d102010-07-02 21:50:04 +00007803 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007804 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007805
Douglas Gregor23c94db2010-07-02 17:43:08 +00007806 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007807 PushOnScopeChains(CopyAssignment, S, false);
7808 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007809
Sean Hunt1ccbc542011-06-22 01:05:13 +00007810 // C++0x [class.copy]p18:
7811 // ... If the class definition declares a move constructor or move
7812 // assignment operator, the implicitly declared copy assignment operator is
7813 // defined as deleted; ...
7814 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7815 ClassDecl->hasUserDeclaredMoveAssignment() ||
7816 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007817 CopyAssignment->setDeletedAsWritten();
7818
Douglas Gregord3c35902010-07-01 16:36:15 +00007819 AddOverriddenMethods(ClassDecl, CopyAssignment);
7820 return CopyAssignment;
7821}
7822
Douglas Gregor06a9f362010-05-01 20:49:11 +00007823void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7824 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007825 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007826 CopyAssignOperator->isOverloadedOperator() &&
7827 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007828 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007829 "DefineImplicitCopyAssignment called for wrong function");
7830
7831 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7832
7833 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7834 CopyAssignOperator->setInvalidDecl();
7835 return;
7836 }
7837
7838 CopyAssignOperator->setUsed();
7839
7840 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007841 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007842
7843 // C++0x [class.copy]p30:
7844 // The implicitly-defined or explicitly-defaulted copy assignment operator
7845 // for a non-union class X performs memberwise copy assignment of its
7846 // subobjects. The direct base classes of X are assigned first, in the
7847 // order of their declaration in the base-specifier-list, and then the
7848 // immediate non-static data members of X are assigned, in the order in
7849 // which they were declared in the class definition.
7850
7851 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007852 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007853
7854 // The parameter for the "other" object, which we are copying from.
7855 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7856 Qualifiers OtherQuals = Other->getType().getQualifiers();
7857 QualType OtherRefType = Other->getType();
7858 if (const LValueReferenceType *OtherRef
7859 = OtherRefType->getAs<LValueReferenceType>()) {
7860 OtherRefType = OtherRef->getPointeeType();
7861 OtherQuals = OtherRefType.getQualifiers();
7862 }
7863
7864 // Our location for everything implicitly-generated.
7865 SourceLocation Loc = CopyAssignOperator->getLocation();
7866
7867 // Construct a reference to the "other" object. We'll be using this
7868 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007869 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007870 assert(OtherRef && "Reference to parameter cannot fail!");
7871
7872 // Construct the "this" pointer. We'll be using this throughout the generated
7873 // ASTs.
7874 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7875 assert(This && "Reference to this cannot fail!");
7876
7877 // Assign base classes.
7878 bool Invalid = false;
7879 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7880 E = ClassDecl->bases_end(); Base != E; ++Base) {
7881 // Form the assignment:
7882 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7883 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007884 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007885 Invalid = true;
7886 continue;
7887 }
7888
John McCallf871d0c2010-08-07 06:22:56 +00007889 CXXCastPath BasePath;
7890 BasePath.push_back(Base);
7891
Douglas Gregor06a9f362010-05-01 20:49:11 +00007892 // Construct the "from" expression, which is an implicit cast to the
7893 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007894 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007895 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7896 CK_UncheckedDerivedToBase,
7897 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007898
7899 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007900 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007901
7902 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007903 To = ImpCastExprToType(To.take(),
7904 Context.getCVRQualifiedType(BaseType,
7905 CopyAssignOperator->getTypeQualifiers()),
7906 CK_UncheckedDerivedToBase,
7907 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007908
7909 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007910 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007911 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007912 /*CopyingBaseSubobject=*/true,
7913 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007914 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007915 Diag(CurrentLocation, diag::note_member_synthesized_at)
7916 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7917 CopyAssignOperator->setInvalidDecl();
7918 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007919 }
7920
7921 // Success! Record the copy.
7922 Statements.push_back(Copy.takeAs<Expr>());
7923 }
7924
7925 // \brief Reference to the __builtin_memcpy function.
7926 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007927 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007928 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007929
7930 // Assign non-static members.
7931 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7932 FieldEnd = ClassDecl->field_end();
7933 Field != FieldEnd; ++Field) {
7934 // Check for members of reference type; we can't copy those.
7935 if (Field->getType()->isReferenceType()) {
7936 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7937 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7938 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007939 Diag(CurrentLocation, diag::note_member_synthesized_at)
7940 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007941 Invalid = true;
7942 continue;
7943 }
7944
7945 // Check for members of const-qualified, non-class type.
7946 QualType BaseType = Context.getBaseElementType(Field->getType());
7947 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7948 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7949 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7950 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007951 Diag(CurrentLocation, diag::note_member_synthesized_at)
7952 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007953 Invalid = true;
7954 continue;
7955 }
John McCallb77115d2011-06-17 00:18:42 +00007956
7957 // Suppress assigning zero-width bitfields.
7958 if (const Expr *Width = Field->getBitWidth())
7959 if (Width->EvaluateAsInt(Context) == 0)
7960 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007961
7962 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007963 if (FieldType->isIncompleteArrayType()) {
7964 assert(ClassDecl->hasFlexibleArrayMember() &&
7965 "Incomplete array type is not valid");
7966 continue;
7967 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007968
7969 // Build references to the field in the object we're copying from and to.
7970 CXXScopeSpec SS; // Intentionally empty
7971 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7972 LookupMemberName);
7973 MemberLookup.addDecl(*Field);
7974 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007975 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007976 Loc, /*IsArrow=*/false,
7977 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007978 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007979 Loc, /*IsArrow=*/true,
7980 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007981 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7982 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7983
7984 // If the field should be copied with __builtin_memcpy rather than via
7985 // explicit assignments, do so. This optimization only applies for arrays
7986 // of scalars and arrays of class type with trivial copy-assignment
7987 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007988 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007989 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007990 // Compute the size of the memory buffer to be copied.
7991 QualType SizeType = Context.getSizeType();
7992 llvm::APInt Size(Context.getTypeSize(SizeType),
7993 Context.getTypeSizeInChars(BaseType).getQuantity());
7994 for (const ConstantArrayType *Array
7995 = Context.getAsConstantArrayType(FieldType);
7996 Array;
7997 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007998 llvm::APInt ArraySize
7999 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008000 Size *= ArraySize;
8001 }
8002
8003 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008004 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8005 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008006
8007 bool NeedsCollectableMemCpy =
8008 (BaseType->isRecordType() &&
8009 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8010
8011 if (NeedsCollectableMemCpy) {
8012 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008013 // Create a reference to the __builtin_objc_memmove_collectable function.
8014 LookupResult R(*this,
8015 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008016 Loc, LookupOrdinaryName);
8017 LookupName(R, TUScope, true);
8018
8019 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8020 if (!CollectableMemCpy) {
8021 // Something went horribly wrong earlier, and we will have
8022 // complained about it.
8023 Invalid = true;
8024 continue;
8025 }
8026
8027 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8028 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008029 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008030 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8031 }
8032 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008033 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008034 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008035 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8036 LookupOrdinaryName);
8037 LookupName(R, TUScope, true);
8038
8039 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8040 if (!BuiltinMemCpy) {
8041 // Something went horribly wrong earlier, and we will have complained
8042 // about it.
8043 Invalid = true;
8044 continue;
8045 }
8046
8047 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8048 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008049 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008050 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8051 }
8052
John McCallca0408f2010-08-23 06:44:23 +00008053 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008054 CallArgs.push_back(To.takeAs<Expr>());
8055 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008056 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008057 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008058 if (NeedsCollectableMemCpy)
8059 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008060 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008061 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008062 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008063 else
8064 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008065 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008066 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008067 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008068
Douglas Gregor06a9f362010-05-01 20:49:11 +00008069 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8070 Statements.push_back(Call.takeAs<Expr>());
8071 continue;
8072 }
8073
8074 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008075 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008076 To.get(), From.get(),
8077 /*CopyingBaseSubobject=*/false,
8078 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008079 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008080 Diag(CurrentLocation, diag::note_member_synthesized_at)
8081 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8082 CopyAssignOperator->setInvalidDecl();
8083 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008084 }
8085
8086 // Success! Record the copy.
8087 Statements.push_back(Copy.takeAs<Stmt>());
8088 }
8089
8090 if (!Invalid) {
8091 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008092 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008093
John McCall60d7b3a2010-08-24 06:29:42 +00008094 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008095 if (Return.isInvalid())
8096 Invalid = true;
8097 else {
8098 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008099
8100 if (Trap.hasErrorOccurred()) {
8101 Diag(CurrentLocation, diag::note_member_synthesized_at)
8102 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8103 Invalid = true;
8104 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008105 }
8106 }
8107
8108 if (Invalid) {
8109 CopyAssignOperator->setInvalidDecl();
8110 return;
8111 }
8112
John McCall60d7b3a2010-08-24 06:29:42 +00008113 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008114 /*isStmtExpr=*/false);
8115 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8116 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008117
8118 if (ASTMutationListener *L = getASTMutationListener()) {
8119 L->CompletedImplicitDefinition(CopyAssignOperator);
8120 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008121}
8122
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008123Sema::ImplicitExceptionSpecification
8124Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8125 ImplicitExceptionSpecification ExceptSpec(Context);
8126
8127 if (ClassDecl->isInvalidDecl())
8128 return ExceptSpec;
8129
8130 // C++0x [except.spec]p14:
8131 // An implicitly declared special member function (Clause 12) shall have an
8132 // exception-specification. [...]
8133
8134 // It is unspecified whether or not an implicit move assignment operator
8135 // attempts to deduplicate calls to assignment operators of virtual bases are
8136 // made. As such, this exception specification is effectively unspecified.
8137 // Based on a similar decision made for constness in C++0x, we're erring on
8138 // the side of assuming such calls to be made regardless of whether they
8139 // actually happen.
8140 // Note that a move constructor is not implicitly declared when there are
8141 // virtual bases, but it can still be user-declared and explicitly defaulted.
8142 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8143 BaseEnd = ClassDecl->bases_end();
8144 Base != BaseEnd; ++Base) {
8145 if (Base->isVirtual())
8146 continue;
8147
8148 CXXRecordDecl *BaseClassDecl
8149 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8150 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8151 false, 0))
8152 ExceptSpec.CalledDecl(MoveAssign);
8153 }
8154
8155 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8156 BaseEnd = ClassDecl->vbases_end();
8157 Base != BaseEnd; ++Base) {
8158 CXXRecordDecl *BaseClassDecl
8159 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8160 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8161 false, 0))
8162 ExceptSpec.CalledDecl(MoveAssign);
8163 }
8164
8165 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8166 FieldEnd = ClassDecl->field_end();
8167 Field != FieldEnd;
8168 ++Field) {
8169 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8170 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8171 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8172 false, 0))
8173 ExceptSpec.CalledDecl(MoveAssign);
8174 }
8175 }
8176
8177 return ExceptSpec;
8178}
8179
8180CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8181 // Note: The following rules are largely analoguous to the move
8182 // constructor rules.
8183
8184 ImplicitExceptionSpecification Spec(
8185 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8186
8187 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8188 QualType RetType = Context.getLValueReferenceType(ArgType);
8189 ArgType = Context.getRValueReferenceType(ArgType);
8190
8191 // An implicitly-declared move assignment operator is an inline public
8192 // member of its class.
8193 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8194 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8195 SourceLocation ClassLoc = ClassDecl->getLocation();
8196 DeclarationNameInfo NameInfo(Name, ClassLoc);
8197 CXXMethodDecl *MoveAssignment
8198 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8199 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8200 /*TInfo=*/0, /*isStatic=*/false,
8201 /*StorageClassAsWritten=*/SC_None,
8202 /*isInline=*/true,
8203 /*isConstexpr=*/false,
8204 SourceLocation());
8205 MoveAssignment->setAccess(AS_public);
8206 MoveAssignment->setDefaulted();
8207 MoveAssignment->setImplicit();
8208 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8209
8210 // Add the parameter to the operator.
8211 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8212 ClassLoc, ClassLoc, /*Id=*/0,
8213 ArgType, /*TInfo=*/0,
8214 SC_None,
8215 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008216 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008217
8218 // Note that we have added this copy-assignment operator.
8219 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8220
8221 // C++0x [class.copy]p9:
8222 // If the definition of a class X does not explicitly declare a move
8223 // assignment operator, one will be implicitly declared as defaulted if and
8224 // only if:
8225 // [...]
8226 // - the move assignment operator would not be implicitly defined as
8227 // deleted.
8228 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8229 // Cache this result so that we don't try to generate this over and over
8230 // on every lookup, leaking memory and wasting time.
8231 ClassDecl->setFailedImplicitMoveAssignment();
8232 return 0;
8233 }
8234
8235 if (Scope *S = getScopeForContext(ClassDecl))
8236 PushOnScopeChains(MoveAssignment, S, false);
8237 ClassDecl->addDecl(MoveAssignment);
8238
8239 AddOverriddenMethods(ClassDecl, MoveAssignment);
8240 return MoveAssignment;
8241}
8242
8243void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8244 CXXMethodDecl *MoveAssignOperator) {
8245 assert((MoveAssignOperator->isDefaulted() &&
8246 MoveAssignOperator->isOverloadedOperator() &&
8247 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8248 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8249 "DefineImplicitMoveAssignment called for wrong function");
8250
8251 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8252
8253 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8254 MoveAssignOperator->setInvalidDecl();
8255 return;
8256 }
8257
8258 MoveAssignOperator->setUsed();
8259
8260 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8261 DiagnosticErrorTrap Trap(Diags);
8262
8263 // C++0x [class.copy]p28:
8264 // The implicitly-defined or move assignment operator for a non-union class
8265 // X performs memberwise move assignment of its subobjects. The direct base
8266 // classes of X are assigned first, in the order of their declaration in the
8267 // base-specifier-list, and then the immediate non-static data members of X
8268 // are assigned, in the order in which they were declared in the class
8269 // definition.
8270
8271 // The statements that form the synthesized function body.
8272 ASTOwningVector<Stmt*> Statements(*this);
8273
8274 // The parameter for the "other" object, which we are move from.
8275 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8276 QualType OtherRefType = Other->getType()->
8277 getAs<RValueReferenceType>()->getPointeeType();
8278 assert(OtherRefType.getQualifiers() == 0 &&
8279 "Bad argument type of defaulted move assignment");
8280
8281 // Our location for everything implicitly-generated.
8282 SourceLocation Loc = MoveAssignOperator->getLocation();
8283
8284 // Construct a reference to the "other" object. We'll be using this
8285 // throughout the generated ASTs.
8286 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8287 assert(OtherRef && "Reference to parameter cannot fail!");
8288 // Cast to rvalue.
8289 OtherRef = CastForMoving(*this, OtherRef);
8290
8291 // Construct the "this" pointer. We'll be using this throughout the generated
8292 // ASTs.
8293 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8294 assert(This && "Reference to this cannot fail!");
8295
8296 // Assign base classes.
8297 bool Invalid = false;
8298 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8299 E = ClassDecl->bases_end(); Base != E; ++Base) {
8300 // Form the assignment:
8301 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8302 QualType BaseType = Base->getType().getUnqualifiedType();
8303 if (!BaseType->isRecordType()) {
8304 Invalid = true;
8305 continue;
8306 }
8307
8308 CXXCastPath BasePath;
8309 BasePath.push_back(Base);
8310
8311 // Construct the "from" expression, which is an implicit cast to the
8312 // appropriately-qualified base type.
8313 Expr *From = OtherRef;
8314 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008315 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008316
8317 // Dereference "this".
8318 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8319
8320 // Implicitly cast "this" to the appropriately-qualified base type.
8321 To = ImpCastExprToType(To.take(),
8322 Context.getCVRQualifiedType(BaseType,
8323 MoveAssignOperator->getTypeQualifiers()),
8324 CK_UncheckedDerivedToBase,
8325 VK_LValue, &BasePath);
8326
8327 // Build the move.
8328 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8329 To.get(), From,
8330 /*CopyingBaseSubobject=*/true,
8331 /*Copying=*/false);
8332 if (Move.isInvalid()) {
8333 Diag(CurrentLocation, diag::note_member_synthesized_at)
8334 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8335 MoveAssignOperator->setInvalidDecl();
8336 return;
8337 }
8338
8339 // Success! Record the move.
8340 Statements.push_back(Move.takeAs<Expr>());
8341 }
8342
8343 // \brief Reference to the __builtin_memcpy function.
8344 Expr *BuiltinMemCpyRef = 0;
8345 // \brief Reference to the __builtin_objc_memmove_collectable function.
8346 Expr *CollectableMemCpyRef = 0;
8347
8348 // Assign non-static members.
8349 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8350 FieldEnd = ClassDecl->field_end();
8351 Field != FieldEnd; ++Field) {
8352 // Check for members of reference type; we can't move those.
8353 if (Field->getType()->isReferenceType()) {
8354 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8355 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8356 Diag(Field->getLocation(), diag::note_declared_at);
8357 Diag(CurrentLocation, diag::note_member_synthesized_at)
8358 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8359 Invalid = true;
8360 continue;
8361 }
8362
8363 // Check for members of const-qualified, non-class type.
8364 QualType BaseType = Context.getBaseElementType(Field->getType());
8365 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8366 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8367 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8368 Diag(Field->getLocation(), diag::note_declared_at);
8369 Diag(CurrentLocation, diag::note_member_synthesized_at)
8370 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8371 Invalid = true;
8372 continue;
8373 }
8374
8375 // Suppress assigning zero-width bitfields.
8376 if (const Expr *Width = Field->getBitWidth())
8377 if (Width->EvaluateAsInt(Context) == 0)
8378 continue;
8379
8380 QualType FieldType = Field->getType().getNonReferenceType();
8381 if (FieldType->isIncompleteArrayType()) {
8382 assert(ClassDecl->hasFlexibleArrayMember() &&
8383 "Incomplete array type is not valid");
8384 continue;
8385 }
8386
8387 // Build references to the field in the object we're copying from and to.
8388 CXXScopeSpec SS; // Intentionally empty
8389 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8390 LookupMemberName);
8391 MemberLookup.addDecl(*Field);
8392 MemberLookup.resolveKind();
8393 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8394 Loc, /*IsArrow=*/false,
8395 SS, 0, MemberLookup, 0);
8396 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8397 Loc, /*IsArrow=*/true,
8398 SS, 0, MemberLookup, 0);
8399 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8400 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8401
8402 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8403 "Member reference with rvalue base must be rvalue except for reference "
8404 "members, which aren't allowed for move assignment.");
8405
8406 // If the field should be copied with __builtin_memcpy rather than via
8407 // explicit assignments, do so. This optimization only applies for arrays
8408 // of scalars and arrays of class type with trivial move-assignment
8409 // operators.
8410 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8411 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8412 // Compute the size of the memory buffer to be copied.
8413 QualType SizeType = Context.getSizeType();
8414 llvm::APInt Size(Context.getTypeSize(SizeType),
8415 Context.getTypeSizeInChars(BaseType).getQuantity());
8416 for (const ConstantArrayType *Array
8417 = Context.getAsConstantArrayType(FieldType);
8418 Array;
8419 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8420 llvm::APInt ArraySize
8421 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8422 Size *= ArraySize;
8423 }
8424
Douglas Gregor45d3d712011-09-01 02:09:07 +00008425 // Take the address of the field references for "from" and "to". We
8426 // directly construct UnaryOperators here because semantic analysis
8427 // does not permit us to take the address of an xvalue.
8428 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8429 Context.getPointerType(From.get()->getType()),
8430 VK_RValue, OK_Ordinary, Loc);
8431 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8432 Context.getPointerType(To.get()->getType()),
8433 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008434
8435 bool NeedsCollectableMemCpy =
8436 (BaseType->isRecordType() &&
8437 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8438
8439 if (NeedsCollectableMemCpy) {
8440 if (!CollectableMemCpyRef) {
8441 // Create a reference to the __builtin_objc_memmove_collectable function.
8442 LookupResult R(*this,
8443 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8444 Loc, LookupOrdinaryName);
8445 LookupName(R, TUScope, true);
8446
8447 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8448 if (!CollectableMemCpy) {
8449 // Something went horribly wrong earlier, and we will have
8450 // complained about it.
8451 Invalid = true;
8452 continue;
8453 }
8454
8455 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8456 CollectableMemCpy->getType(),
8457 VK_LValue, Loc, 0).take();
8458 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8459 }
8460 }
8461 // Create a reference to the __builtin_memcpy builtin function.
8462 else if (!BuiltinMemCpyRef) {
8463 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8464 LookupOrdinaryName);
8465 LookupName(R, TUScope, true);
8466
8467 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8468 if (!BuiltinMemCpy) {
8469 // Something went horribly wrong earlier, and we will have complained
8470 // about it.
8471 Invalid = true;
8472 continue;
8473 }
8474
8475 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8476 BuiltinMemCpy->getType(),
8477 VK_LValue, Loc, 0).take();
8478 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8479 }
8480
8481 ASTOwningVector<Expr*> CallArgs(*this);
8482 CallArgs.push_back(To.takeAs<Expr>());
8483 CallArgs.push_back(From.takeAs<Expr>());
8484 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8485 ExprResult Call = ExprError();
8486 if (NeedsCollectableMemCpy)
8487 Call = ActOnCallExpr(/*Scope=*/0,
8488 CollectableMemCpyRef,
8489 Loc, move_arg(CallArgs),
8490 Loc);
8491 else
8492 Call = ActOnCallExpr(/*Scope=*/0,
8493 BuiltinMemCpyRef,
8494 Loc, move_arg(CallArgs),
8495 Loc);
8496
8497 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8498 Statements.push_back(Call.takeAs<Expr>());
8499 continue;
8500 }
8501
8502 // Build the move of this field.
8503 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8504 To.get(), From.get(),
8505 /*CopyingBaseSubobject=*/false,
8506 /*Copying=*/false);
8507 if (Move.isInvalid()) {
8508 Diag(CurrentLocation, diag::note_member_synthesized_at)
8509 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8510 MoveAssignOperator->setInvalidDecl();
8511 return;
8512 }
8513
8514 // Success! Record the copy.
8515 Statements.push_back(Move.takeAs<Stmt>());
8516 }
8517
8518 if (!Invalid) {
8519 // Add a "return *this;"
8520 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8521
8522 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8523 if (Return.isInvalid())
8524 Invalid = true;
8525 else {
8526 Statements.push_back(Return.takeAs<Stmt>());
8527
8528 if (Trap.hasErrorOccurred()) {
8529 Diag(CurrentLocation, diag::note_member_synthesized_at)
8530 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8531 Invalid = true;
8532 }
8533 }
8534 }
8535
8536 if (Invalid) {
8537 MoveAssignOperator->setInvalidDecl();
8538 return;
8539 }
8540
8541 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8542 /*isStmtExpr=*/false);
8543 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8544 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8545
8546 if (ASTMutationListener *L = getASTMutationListener()) {
8547 L->CompletedImplicitDefinition(MoveAssignOperator);
8548 }
8549}
8550
Sean Hunt49634cf2011-05-13 06:10:58 +00008551std::pair<Sema::ImplicitExceptionSpecification, bool>
8552Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008553 if (ClassDecl->isInvalidDecl())
8554 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8555
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008556 // C++ [class.copy]p5:
8557 // The implicitly-declared copy constructor for a class X will
8558 // have the form
8559 //
8560 // X::X(const X&)
8561 //
8562 // if
Sean Huntc530d172011-06-10 04:44:37 +00008563 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008564 bool HasConstCopyConstructor = true;
8565
8566 // -- each direct or virtual base class B of X has a copy
8567 // constructor whose first parameter is of type const B& or
8568 // const volatile B&, and
8569 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8570 BaseEnd = ClassDecl->bases_end();
8571 HasConstCopyConstructor && Base != BaseEnd;
8572 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008573 // Virtual bases are handled below.
8574 if (Base->isVirtual())
8575 continue;
8576
Douglas Gregor22584312010-07-02 23:41:54 +00008577 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008578 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008579 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8580 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008581 }
8582
8583 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8584 BaseEnd = ClassDecl->vbases_end();
8585 HasConstCopyConstructor && Base != BaseEnd;
8586 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008587 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008588 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008589 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8590 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008591 }
8592
8593 // -- for all the nonstatic data members of X that are of a
8594 // class type M (or array thereof), each such class type
8595 // has a copy constructor whose first parameter is of type
8596 // const M& or const volatile M&.
8597 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8598 FieldEnd = ClassDecl->field_end();
8599 HasConstCopyConstructor && Field != FieldEnd;
8600 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008601 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008602 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008603 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8604 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008605 }
8606 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008607 // Otherwise, the implicitly declared copy constructor will have
8608 // the form
8609 //
8610 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008611
Douglas Gregor0d405db2010-07-01 20:59:04 +00008612 // C++ [except.spec]p14:
8613 // An implicitly declared special member function (Clause 12) shall have an
8614 // exception-specification. [...]
8615 ImplicitExceptionSpecification ExceptSpec(Context);
8616 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8617 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8618 BaseEnd = ClassDecl->bases_end();
8619 Base != BaseEnd;
8620 ++Base) {
8621 // Virtual bases are handled below.
8622 if (Base->isVirtual())
8623 continue;
8624
Douglas Gregor22584312010-07-02 23:41:54 +00008625 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008626 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008627 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008628 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008629 ExceptSpec.CalledDecl(CopyConstructor);
8630 }
8631 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8632 BaseEnd = ClassDecl->vbases_end();
8633 Base != BaseEnd;
8634 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008635 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008636 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008637 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008638 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008639 ExceptSpec.CalledDecl(CopyConstructor);
8640 }
8641 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8642 FieldEnd = ClassDecl->field_end();
8643 Field != FieldEnd;
8644 ++Field) {
8645 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008646 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8647 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008648 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008649 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008650 }
8651 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008652
Sean Hunt49634cf2011-05-13 06:10:58 +00008653 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8654}
8655
8656CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8657 CXXRecordDecl *ClassDecl) {
8658 // C++ [class.copy]p4:
8659 // If the class definition does not explicitly declare a copy
8660 // constructor, one is declared implicitly.
8661
8662 ImplicitExceptionSpecification Spec(Context);
8663 bool Const;
8664 llvm::tie(Spec, Const) =
8665 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8666
8667 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8668 QualType ArgType = ClassType;
8669 if (Const)
8670 ArgType = ArgType.withConst();
8671 ArgType = Context.getLValueReferenceType(ArgType);
8672
8673 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8674
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008675 DeclarationName Name
8676 = Context.DeclarationNames.getCXXConstructorName(
8677 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008678 SourceLocation ClassLoc = ClassDecl->getLocation();
8679 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008680
8681 // An implicitly-declared copy constructor is an inline public
8682 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008683 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008684 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008685 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00008686 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008687 /*TInfo=*/0,
8688 /*isExplicit=*/false,
8689 /*isInline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008690 /*isImplicitlyDeclared=*/true,
8691 // FIXME: apply the rules for definitions here
8692 /*isConstexpr=*/false);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008693 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008694 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008695 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8696
Douglas Gregor22584312010-07-02 23:41:54 +00008697 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008698 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8699
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008700 // Add the parameter to the constructor.
8701 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008702 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008703 /*IdentifierInfo=*/0,
8704 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008705 SC_None,
8706 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008707 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008708
Douglas Gregor23c94db2010-07-02 17:43:08 +00008709 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008710 PushOnScopeChains(CopyConstructor, S, false);
8711 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008712
Sean Hunt1ccbc542011-06-22 01:05:13 +00008713 // C++0x [class.copy]p7:
8714 // ... If the class definition declares a move constructor or move
8715 // assignment operator, the implicitly declared constructor is defined as
8716 // deleted; ...
8717 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8718 ClassDecl->hasUserDeclaredMoveAssignment() ||
8719 ShouldDeleteCopyConstructor(CopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008720 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008721
8722 return CopyConstructor;
8723}
8724
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008725void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008726 CXXConstructorDecl *CopyConstructor) {
8727 assert((CopyConstructor->isDefaulted() &&
8728 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008729 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008730 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008731
Anders Carlsson63010a72010-04-23 16:24:12 +00008732 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008733 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008734
Douglas Gregor39957dc2010-05-01 15:04:51 +00008735 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008736 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008737
Sean Huntcbb67482011-01-08 20:30:50 +00008738 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008739 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008740 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008741 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008742 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008743 } else {
8744 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8745 CopyConstructor->getLocation(),
8746 MultiStmtArg(*this, 0, 0),
8747 /*isStmtExpr=*/false)
8748 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008749 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008750 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008751
8752 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008753 if (ASTMutationListener *L = getASTMutationListener()) {
8754 L->CompletedImplicitDefinition(CopyConstructor);
8755 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008756}
8757
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008758Sema::ImplicitExceptionSpecification
8759Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8760 // C++ [except.spec]p14:
8761 // An implicitly declared special member function (Clause 12) shall have an
8762 // exception-specification. [...]
8763 ImplicitExceptionSpecification ExceptSpec(Context);
8764 if (ClassDecl->isInvalidDecl())
8765 return ExceptSpec;
8766
8767 // Direct base-class constructors.
8768 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8769 BEnd = ClassDecl->bases_end();
8770 B != BEnd; ++B) {
8771 if (B->isVirtual()) // Handled below.
8772 continue;
8773
8774 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8775 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8776 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8777 // If this is a deleted function, add it anyway. This might be conformant
8778 // with the standard. This might not. I'm not sure. It might not matter.
8779 if (Constructor)
8780 ExceptSpec.CalledDecl(Constructor);
8781 }
8782 }
8783
8784 // Virtual base-class constructors.
8785 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8786 BEnd = ClassDecl->vbases_end();
8787 B != BEnd; ++B) {
8788 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8789 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8790 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8791 // If this is a deleted function, add it anyway. This might be conformant
8792 // with the standard. This might not. I'm not sure. It might not matter.
8793 if (Constructor)
8794 ExceptSpec.CalledDecl(Constructor);
8795 }
8796 }
8797
8798 // Field constructors.
8799 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8800 FEnd = ClassDecl->field_end();
8801 F != FEnd; ++F) {
8802 if (F->hasInClassInitializer()) {
8803 if (Expr *E = F->getInClassInitializer())
8804 ExceptSpec.CalledExpr(E);
8805 else if (!F->isInvalidDecl())
8806 ExceptSpec.SetDelayed();
8807 } else if (const RecordType *RecordTy
8808 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8809 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8810 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8811 // If this is a deleted function, add it anyway. This might be conformant
8812 // with the standard. This might not. I'm not sure. It might not matter.
8813 // In particular, the problem is that this function never gets called. It
8814 // might just be ill-formed because this function attempts to refer to
8815 // a deleted function here.
8816 if (Constructor)
8817 ExceptSpec.CalledDecl(Constructor);
8818 }
8819 }
8820
8821 return ExceptSpec;
8822}
8823
8824CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8825 CXXRecordDecl *ClassDecl) {
8826 ImplicitExceptionSpecification Spec(
8827 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8828
8829 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8830 QualType ArgType = Context.getRValueReferenceType(ClassType);
8831
8832 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8833
8834 DeclarationName Name
8835 = Context.DeclarationNames.getCXXConstructorName(
8836 Context.getCanonicalType(ClassType));
8837 SourceLocation ClassLoc = ClassDecl->getLocation();
8838 DeclarationNameInfo NameInfo(Name, ClassLoc);
8839
8840 // C++0x [class.copy]p11:
8841 // An implicitly-declared copy/move constructor is an inline public
8842 // member of its class.
8843 CXXConstructorDecl *MoveConstructor
8844 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8845 Context.getFunctionType(Context.VoidTy,
8846 &ArgType, 1, EPI),
8847 /*TInfo=*/0,
8848 /*isExplicit=*/false,
8849 /*isInline=*/true,
8850 /*isImplicitlyDeclared=*/true,
8851 // FIXME: apply the rules for definitions here
8852 /*isConstexpr=*/false);
8853 MoveConstructor->setAccess(AS_public);
8854 MoveConstructor->setDefaulted();
8855 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8856
8857 // Add the parameter to the constructor.
8858 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8859 ClassLoc, ClassLoc,
8860 /*IdentifierInfo=*/0,
8861 ArgType, /*TInfo=*/0,
8862 SC_None,
8863 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008864 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008865
8866 // C++0x [class.copy]p9:
8867 // If the definition of a class X does not explicitly declare a move
8868 // constructor, one will be implicitly declared as defaulted if and only if:
8869 // [...]
8870 // - the move constructor would not be implicitly defined as deleted.
8871 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8872 // Cache this result so that we don't try to generate this over and over
8873 // on every lookup, leaking memory and wasting time.
8874 ClassDecl->setFailedImplicitMoveConstructor();
8875 return 0;
8876 }
8877
8878 // Note that we have declared this constructor.
8879 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8880
8881 if (Scope *S = getScopeForContext(ClassDecl))
8882 PushOnScopeChains(MoveConstructor, S, false);
8883 ClassDecl->addDecl(MoveConstructor);
8884
8885 return MoveConstructor;
8886}
8887
8888void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8889 CXXConstructorDecl *MoveConstructor) {
8890 assert((MoveConstructor->isDefaulted() &&
8891 MoveConstructor->isMoveConstructor() &&
8892 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8893 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8894
8895 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8896 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8897
8898 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8899 DiagnosticErrorTrap Trap(Diags);
8900
8901 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8902 Trap.hasErrorOccurred()) {
8903 Diag(CurrentLocation, diag::note_member_synthesized_at)
8904 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8905 MoveConstructor->setInvalidDecl();
8906 } else {
8907 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8908 MoveConstructor->getLocation(),
8909 MultiStmtArg(*this, 0, 0),
8910 /*isStmtExpr=*/false)
8911 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008912 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008913 }
8914
8915 MoveConstructor->setUsed();
8916
8917 if (ASTMutationListener *L = getASTMutationListener()) {
8918 L->CompletedImplicitDefinition(MoveConstructor);
8919 }
8920}
8921
John McCall60d7b3a2010-08-24 06:29:42 +00008922ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008923Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008924 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008925 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008926 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008927 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008928 unsigned ConstructKind,
8929 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008930 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008931
Douglas Gregor2f599792010-04-02 18:24:57 +00008932 // C++0x [class.copy]p34:
8933 // When certain criteria are met, an implementation is allowed to
8934 // omit the copy/move construction of a class object, even if the
8935 // copy/move constructor and/or destructor for the object have
8936 // side effects. [...]
8937 // - when a temporary class object that has not been bound to a
8938 // reference (12.2) would be copied/moved to a class object
8939 // with the same cv-unqualified type, the copy/move operation
8940 // can be omitted by constructing the temporary object
8941 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00008942 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00008943 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00008944 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00008945 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008946 }
Mike Stump1eb44332009-09-09 15:08:12 +00008947
8948 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008949 Elidable, move(ExprArgs), HadMultipleCandidates,
8950 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00008951}
8952
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008953/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8954/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00008955ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008956Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8957 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00008958 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008959 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008960 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008961 unsigned ConstructKind,
8962 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00008963 unsigned NumExprs = ExprArgs.size();
8964 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00008965
Nick Lewycky909a70d2011-03-25 01:44:32 +00008966 for (specific_attr_iterator<NonNullAttr>
8967 i = Constructor->specific_attr_begin<NonNullAttr>(),
8968 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8969 const NonNullAttr *NonNull = *i;
8970 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8971 }
8972
Douglas Gregor7edfb692009-11-23 12:27:39 +00008973 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00008974 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008975 Constructor, Elidable, Exprs, NumExprs,
8976 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008977 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8978 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008979}
8980
Mike Stump1eb44332009-09-09 15:08:12 +00008981bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00008982 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008983 MultiExprArg Exprs,
8984 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00008985 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00008986 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00008987 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008988 move(Exprs), HadMultipleCandidates, false,
8989 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00008990 if (TempResult.isInvalid())
8991 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008992
Anders Carlssonda3f4e22009-08-25 05:12:04 +00008993 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00008994 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008995 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00008996 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00008997 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00008998
Anders Carlssonfe2de492009-08-25 05:18:00 +00008999 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009000}
9001
John McCall68c6c9a2010-02-02 09:10:11 +00009002void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009003 if (VD->isInvalidDecl()) return;
9004
John McCall68c6c9a2010-02-02 09:10:11 +00009005 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009006 if (ClassDecl->isInvalidDecl()) return;
9007 if (ClassDecl->hasTrivialDestructor()) return;
9008 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009009
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009010 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9011 MarkDeclarationReferenced(VD->getLocation(), Destructor);
9012 CheckDestructorAccess(VD->getLocation(), Destructor,
9013 PDiag(diag::err_access_dtor_var)
9014 << VD->getDeclName()
9015 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009016
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009017 if (!VD->hasGlobalStorage()) return;
9018
9019 // Emit warning for non-trivial dtor in global scope (a real global,
9020 // class-static, function-static).
9021 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9022
9023 // TODO: this should be re-enabled for static locals by !CXAAtExit
9024 if (!VD->isStaticLocal())
9025 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009026}
9027
Mike Stump1eb44332009-09-09 15:08:12 +00009028/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009029/// ActOnDeclarator, when a C++ direct initializer is present.
9030/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00009031void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00009032 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009033 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00009034 SourceLocation RParenLoc,
9035 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00009036 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009037
9038 // If there is no declaration, there was an error parsing it. Just ignore
9039 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00009040 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009041 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009042
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009043 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9044 if (!VDecl) {
9045 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9046 RealDecl->setInvalidDecl();
9047 return;
9048 }
9049
Richard Smith34b41d92011-02-20 03:19:35 +00009050 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9051 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00009052 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
9053 if (Exprs.size() > 1) {
9054 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9055 diag::err_auto_var_init_multiple_expressions)
9056 << VDecl->getDeclName() << VDecl->getType()
9057 << VDecl->getSourceRange();
9058 RealDecl->setInvalidDecl();
9059 return;
9060 }
9061
9062 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00009063 TypeSourceInfo *DeducedType = 0;
9064 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00009065 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
9066 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
9067 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00009068 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00009069 RealDecl->setInvalidDecl();
9070 return;
9071 }
Richard Smitha085da82011-03-17 16:11:59 +00009072 VDecl->setTypeSourceInfo(DeducedType);
9073 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00009074
John McCallf85e1932011-06-15 23:02:42 +00009075 // In ARC, infer lifetime.
9076 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9077 VDecl->setInvalidDecl();
9078
Richard Smith34b41d92011-02-20 03:19:35 +00009079 // If this is a redeclaration, check that the type we just deduced matches
9080 // the previously declared type.
9081 if (VarDecl *Old = VDecl->getPreviousDeclaration())
9082 MergeVarDeclTypes(VDecl, Old);
9083 }
9084
Douglas Gregor83ddad32009-08-26 21:14:46 +00009085 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009086 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009087 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9088 //
9089 // Clients that want to distinguish between the two forms, can check for
9090 // direct initializer using VarDecl::hasCXXDirectInitializer().
9091 // A major benefit is that clients that don't particularly care about which
9092 // exactly form was it (like the CodeGen) can handle both cases without
9093 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009094
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009095 // C++ 8.5p11:
9096 // The form of initialization (using parentheses or '=') is generally
9097 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009098 // class type.
9099
Douglas Gregor4dffad62010-02-11 22:55:30 +00009100 if (!VDecl->getType()->isDependentType() &&
9101 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00009102 diag::err_typecheck_decl_incomplete_type)) {
9103 VDecl->setInvalidDecl();
9104 return;
9105 }
9106
Douglas Gregor90f93822009-12-22 22:17:25 +00009107 // The variable can not have an abstract class type.
9108 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9109 diag::err_abstract_type_in_decl,
9110 AbstractVariableType))
9111 VDecl->setInvalidDecl();
9112
Sebastian Redl31310a22010-02-01 20:16:42 +00009113 const VarDecl *Def;
9114 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009115 Diag(VDecl->getLocation(), diag::err_redefinition)
9116 << VDecl->getDeclName();
9117 Diag(Def->getLocation(), diag::note_previous_definition);
9118 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009119 return;
9120 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009121
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009122 // C++ [class.static.data]p4
9123 // If a static data member is of const integral or const
9124 // enumeration type, its declaration in the class definition can
9125 // specify a constant-initializer which shall be an integral
9126 // constant expression (5.19). In that case, the member can appear
9127 // in integral constant expressions. The member shall still be
9128 // defined in a namespace scope if it is used in the program and the
9129 // namespace scope definition shall not contain an initializer.
9130 //
9131 // We already performed a redefinition check above, but for static
9132 // data members we also need to check whether there was an in-class
9133 // declaration with an initializer.
9134 const VarDecl* PrevInit = 0;
9135 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9136 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9137 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9138 return;
9139 }
9140
Douglas Gregora31040f2010-12-16 01:31:22 +00009141 bool IsDependent = false;
9142 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9143 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9144 VDecl->setInvalidDecl();
9145 return;
9146 }
9147
9148 if (Exprs.get()[I]->isTypeDependent())
9149 IsDependent = true;
9150 }
9151
Douglas Gregor4dffad62010-02-11 22:55:30 +00009152 // If either the declaration has a dependent type or if any of the
9153 // expressions is type-dependent, we represent the initialization
9154 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009155 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009156 // Let clients know that initialization was done with a direct initializer.
9157 VDecl->setCXXDirectInitializer(true);
9158
9159 // Store the initialization expressions as a ParenListExpr.
9160 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009161 VDecl->setInit(new (Context) ParenListExpr(
9162 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9163 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009164 return;
9165 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009166
9167 // Capture the variable that is being initialized and the style of
9168 // initialization.
9169 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9170
9171 // FIXME: Poor source location information.
9172 InitializationKind Kind
9173 = InitializationKind::CreateDirect(VDecl->getLocation(),
9174 LParenLoc, RParenLoc);
9175
9176 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009177 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00009178 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00009179 if (Result.isInvalid()) {
9180 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009181 return;
9182 }
John McCallb4eb64d2010-10-08 02:01:28 +00009183
Richard Smithc6d990a2011-09-29 19:11:37 +00009184 Expr *Init = Result.get();
9185 CheckImplicitConversions(Init, LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00009186
Richard Smithc6d990a2011-09-29 19:11:37 +00009187 if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() &&
9188 !Init->isValueDependent() &&
9189 !Init->isConstantInitializer(Context,
9190 VDecl->getType()->isReferenceType())) {
9191 // FIXME: Improve this diagnostic to explain why the initializer is not
9192 // a constant expression.
9193 Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init)
9194 << VDecl << Init->getSourceRange();
9195 }
9196
9197 Init = MaybeCreateExprWithCleanups(Init);
9198 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009199 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009200
John McCall2998d6b2011-01-19 11:48:09 +00009201 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009202}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009203
Douglas Gregor39da0b82009-09-09 23:08:42 +00009204/// \brief Given a constructor and the set of arguments provided for the
9205/// constructor, convert the arguments and add any required default arguments
9206/// to form a proper call to this constructor.
9207///
9208/// \returns true if an error occurred, false otherwise.
9209bool
9210Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9211 MultiExprArg ArgsPtr,
9212 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009213 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009214 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9215 unsigned NumArgs = ArgsPtr.size();
9216 Expr **Args = (Expr **)ArgsPtr.get();
9217
9218 const FunctionProtoType *Proto
9219 = Constructor->getType()->getAs<FunctionProtoType>();
9220 assert(Proto && "Constructor without a prototype?");
9221 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009222
9223 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009224 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009225 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009226 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009227 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009228
9229 VariadicCallType CallType =
9230 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009231 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009232 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9233 Proto, 0, Args, NumArgs, AllArgs,
9234 CallType);
9235 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9236 ConvertedArgs.push_back(AllArgs[i]);
9237 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009238}
9239
Anders Carlsson20d45d22009-12-12 00:32:00 +00009240static inline bool
9241CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9242 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009243 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009244 if (isa<NamespaceDecl>(DC)) {
9245 return SemaRef.Diag(FnDecl->getLocation(),
9246 diag::err_operator_new_delete_declared_in_namespace)
9247 << FnDecl->getDeclName();
9248 }
9249
9250 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009251 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009252 return SemaRef.Diag(FnDecl->getLocation(),
9253 diag::err_operator_new_delete_declared_static)
9254 << FnDecl->getDeclName();
9255 }
9256
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009257 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009258}
9259
Anders Carlsson156c78e2009-12-13 17:53:43 +00009260static inline bool
9261CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9262 CanQualType ExpectedResultType,
9263 CanQualType ExpectedFirstParamType,
9264 unsigned DependentParamTypeDiag,
9265 unsigned InvalidParamTypeDiag) {
9266 QualType ResultType =
9267 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9268
9269 // Check that the result type is not dependent.
9270 if (ResultType->isDependentType())
9271 return SemaRef.Diag(FnDecl->getLocation(),
9272 diag::err_operator_new_delete_dependent_result_type)
9273 << FnDecl->getDeclName() << ExpectedResultType;
9274
9275 // Check that the result type is what we expect.
9276 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9277 return SemaRef.Diag(FnDecl->getLocation(),
9278 diag::err_operator_new_delete_invalid_result_type)
9279 << FnDecl->getDeclName() << ExpectedResultType;
9280
9281 // A function template must have at least 2 parameters.
9282 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9283 return SemaRef.Diag(FnDecl->getLocation(),
9284 diag::err_operator_new_delete_template_too_few_parameters)
9285 << FnDecl->getDeclName();
9286
9287 // The function decl must have at least 1 parameter.
9288 if (FnDecl->getNumParams() == 0)
9289 return SemaRef.Diag(FnDecl->getLocation(),
9290 diag::err_operator_new_delete_too_few_parameters)
9291 << FnDecl->getDeclName();
9292
9293 // Check the the first parameter type is not dependent.
9294 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9295 if (FirstParamType->isDependentType())
9296 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9297 << FnDecl->getDeclName() << ExpectedFirstParamType;
9298
9299 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009300 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009301 ExpectedFirstParamType)
9302 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9303 << FnDecl->getDeclName() << ExpectedFirstParamType;
9304
9305 return false;
9306}
9307
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009308static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009309CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009310 // C++ [basic.stc.dynamic.allocation]p1:
9311 // A program is ill-formed if an allocation function is declared in a
9312 // namespace scope other than global scope or declared static in global
9313 // scope.
9314 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9315 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009316
9317 CanQualType SizeTy =
9318 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9319
9320 // C++ [basic.stc.dynamic.allocation]p1:
9321 // The return type shall be void*. The first parameter shall have type
9322 // std::size_t.
9323 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9324 SizeTy,
9325 diag::err_operator_new_dependent_param_type,
9326 diag::err_operator_new_param_type))
9327 return true;
9328
9329 // C++ [basic.stc.dynamic.allocation]p1:
9330 // The first parameter shall not have an associated default argument.
9331 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009332 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009333 diag::err_operator_new_default_arg)
9334 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9335
9336 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009337}
9338
9339static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009340CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9341 // C++ [basic.stc.dynamic.deallocation]p1:
9342 // A program is ill-formed if deallocation functions are declared in a
9343 // namespace scope other than global scope or declared static in global
9344 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009345 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9346 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009347
9348 // C++ [basic.stc.dynamic.deallocation]p2:
9349 // Each deallocation function shall return void and its first parameter
9350 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009351 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9352 SemaRef.Context.VoidPtrTy,
9353 diag::err_operator_delete_dependent_param_type,
9354 diag::err_operator_delete_param_type))
9355 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009356
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009357 return false;
9358}
9359
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009360/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9361/// of this overloaded operator is well-formed. If so, returns false;
9362/// otherwise, emits appropriate diagnostics and returns true.
9363bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009364 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009365 "Expected an overloaded operator declaration");
9366
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009367 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9368
Mike Stump1eb44332009-09-09 15:08:12 +00009369 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009370 // The allocation and deallocation functions, operator new,
9371 // operator new[], operator delete and operator delete[], are
9372 // described completely in 3.7.3. The attributes and restrictions
9373 // found in the rest of this subclause do not apply to them unless
9374 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009375 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009376 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009377
Anders Carlssona3ccda52009-12-12 00:26:23 +00009378 if (Op == OO_New || Op == OO_Array_New)
9379 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009380
9381 // C++ [over.oper]p6:
9382 // An operator function shall either be a non-static member
9383 // function or be a non-member function and have at least one
9384 // parameter whose type is a class, a reference to a class, an
9385 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009386 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9387 if (MethodDecl->isStatic())
9388 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009389 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009390 } else {
9391 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009392 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9393 ParamEnd = FnDecl->param_end();
9394 Param != ParamEnd; ++Param) {
9395 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009396 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9397 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009398 ClassOrEnumParam = true;
9399 break;
9400 }
9401 }
9402
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009403 if (!ClassOrEnumParam)
9404 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009405 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009406 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009407 }
9408
9409 // C++ [over.oper]p8:
9410 // An operator function cannot have default arguments (8.3.6),
9411 // except where explicitly stated below.
9412 //
Mike Stump1eb44332009-09-09 15:08:12 +00009413 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009414 // (C++ [over.call]p1).
9415 if (Op != OO_Call) {
9416 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9417 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009418 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009419 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009420 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009421 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009422 }
9423 }
9424
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009425 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9426 { false, false, false }
9427#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9428 , { Unary, Binary, MemberOnly }
9429#include "clang/Basic/OperatorKinds.def"
9430 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009431
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009432 bool CanBeUnaryOperator = OperatorUses[Op][0];
9433 bool CanBeBinaryOperator = OperatorUses[Op][1];
9434 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009435
9436 // C++ [over.oper]p8:
9437 // [...] Operator functions cannot have more or fewer parameters
9438 // than the number required for the corresponding operator, as
9439 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009440 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009441 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009442 if (Op != OO_Call &&
9443 ((NumParams == 1 && !CanBeUnaryOperator) ||
9444 (NumParams == 2 && !CanBeBinaryOperator) ||
9445 (NumParams < 1) || (NumParams > 2))) {
9446 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009447 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009448 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009449 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009450 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009451 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009452 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009453 assert(CanBeBinaryOperator &&
9454 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009455 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009456 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009457
Chris Lattner416e46f2008-11-21 07:57:12 +00009458 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009459 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009460 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009461
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009462 // Overloaded operators other than operator() cannot be variadic.
9463 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009464 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009465 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009466 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009467 }
9468
9469 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009470 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9471 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009472 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009473 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009474 }
9475
9476 // C++ [over.inc]p1:
9477 // The user-defined function called operator++ implements the
9478 // prefix and postfix ++ operator. If this function is a member
9479 // function with no parameters, or a non-member function with one
9480 // parameter of class or enumeration type, it defines the prefix
9481 // increment operator ++ for objects of that type. If the function
9482 // is a member function with one parameter (which shall be of type
9483 // int) or a non-member function with two parameters (the second
9484 // of which shall be of type int), it defines the postfix
9485 // increment operator ++ for objects of that type.
9486 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9487 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9488 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009489 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009490 ParamIsInt = BT->getKind() == BuiltinType::Int;
9491
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009492 if (!ParamIsInt)
9493 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009494 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009495 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009496 }
9497
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009498 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009499}
Chris Lattner5a003a42008-12-17 07:09:26 +00009500
Sean Hunta6c058d2010-01-13 09:01:02 +00009501/// CheckLiteralOperatorDeclaration - Check whether the declaration
9502/// of this literal operator function is well-formed. If so, returns
9503/// false; otherwise, emits appropriate diagnostics and returns true.
9504bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9505 DeclContext *DC = FnDecl->getDeclContext();
9506 Decl::Kind Kind = DC->getDeclKind();
9507 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9508 Kind != Decl::LinkageSpec) {
9509 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9510 << FnDecl->getDeclName();
9511 return true;
9512 }
9513
9514 bool Valid = false;
9515
Sean Hunt216c2782010-04-07 23:11:06 +00009516 // template <char...> type operator "" name() is the only valid template
9517 // signature, and the only valid signature with no parameters.
9518 if (FnDecl->param_size() == 0) {
9519 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9520 // Must have only one template parameter
9521 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9522 if (Params->size() == 1) {
9523 NonTypeTemplateParmDecl *PmDecl =
9524 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009525
Sean Hunt216c2782010-04-07 23:11:06 +00009526 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009527 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9528 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9529 Valid = true;
9530 }
9531 }
9532 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009533 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009534 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9535
Sean Hunta6c058d2010-01-13 09:01:02 +00009536 QualType T = (*Param)->getType();
9537
Sean Hunt30019c02010-04-07 22:57:35 +00009538 // unsigned long long int, long double, and any character type are allowed
9539 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009540 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9541 Context.hasSameType(T, Context.LongDoubleTy) ||
9542 Context.hasSameType(T, Context.CharTy) ||
9543 Context.hasSameType(T, Context.WCharTy) ||
9544 Context.hasSameType(T, Context.Char16Ty) ||
9545 Context.hasSameType(T, Context.Char32Ty)) {
9546 if (++Param == FnDecl->param_end())
9547 Valid = true;
9548 goto FinishedParams;
9549 }
9550
Sean Hunt30019c02010-04-07 22:57:35 +00009551 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009552 const PointerType *PT = T->getAs<PointerType>();
9553 if (!PT)
9554 goto FinishedParams;
9555 T = PT->getPointeeType();
9556 if (!T.isConstQualified())
9557 goto FinishedParams;
9558 T = T.getUnqualifiedType();
9559
9560 // Move on to the second parameter;
9561 ++Param;
9562
9563 // If there is no second parameter, the first must be a const char *
9564 if (Param == FnDecl->param_end()) {
9565 if (Context.hasSameType(T, Context.CharTy))
9566 Valid = true;
9567 goto FinishedParams;
9568 }
9569
9570 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9571 // are allowed as the first parameter to a two-parameter function
9572 if (!(Context.hasSameType(T, Context.CharTy) ||
9573 Context.hasSameType(T, Context.WCharTy) ||
9574 Context.hasSameType(T, Context.Char16Ty) ||
9575 Context.hasSameType(T, Context.Char32Ty)))
9576 goto FinishedParams;
9577
9578 // The second and final parameter must be an std::size_t
9579 T = (*Param)->getType().getUnqualifiedType();
9580 if (Context.hasSameType(T, Context.getSizeType()) &&
9581 ++Param == FnDecl->param_end())
9582 Valid = true;
9583 }
9584
9585 // FIXME: This diagnostic is absolutely terrible.
9586FinishedParams:
9587 if (!Valid) {
9588 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9589 << FnDecl->getDeclName();
9590 return true;
9591 }
9592
Douglas Gregor1155c422011-08-30 22:40:35 +00009593 StringRef LiteralName
9594 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9595 if (LiteralName[0] != '_') {
9596 // C++0x [usrlit.suffix]p1:
9597 // Literal suffix identifiers that do not start with an underscore are
9598 // reserved for future standardization.
9599 bool IsHexFloat = true;
9600 if (LiteralName.size() > 1 &&
9601 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9602 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9603 if (!isdigit(LiteralName[I])) {
9604 IsHexFloat = false;
9605 break;
9606 }
9607 }
9608 }
9609
9610 if (IsHexFloat)
9611 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9612 << LiteralName;
9613 else
9614 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9615 }
9616
Sean Hunta6c058d2010-01-13 09:01:02 +00009617 return false;
9618}
9619
Douglas Gregor074149e2009-01-05 19:45:36 +00009620/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9621/// linkage specification, including the language and (if present)
9622/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9623/// the location of the language string literal, which is provided
9624/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9625/// the '{' brace. Otherwise, this linkage specification does not
9626/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009627Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9628 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009629 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009630 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009631 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009632 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009633 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009634 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009635 Language = LinkageSpecDecl::lang_cxx;
9636 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009637 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009638 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009639 }
Mike Stump1eb44332009-09-09 15:08:12 +00009640
Chris Lattnercc98eac2008-12-17 07:13:27 +00009641 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009642
Douglas Gregor074149e2009-01-05 19:45:36 +00009643 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009644 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009645 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009646 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009647 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009648}
9649
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009650/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009651/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9652/// valid, it's the position of the closing '}' brace in a linkage
9653/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009654Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009655 Decl *LinkageSpec,
9656 SourceLocation RBraceLoc) {
9657 if (LinkageSpec) {
9658 if (RBraceLoc.isValid()) {
9659 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9660 LSDecl->setRBraceLoc(RBraceLoc);
9661 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009662 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009663 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009664 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009665}
9666
Douglas Gregord308e622009-05-18 20:51:54 +00009667/// \brief Perform semantic analysis for the variable declaration that
9668/// occurs within a C++ catch clause, returning the newly-created
9669/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009670VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009671 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009672 SourceLocation StartLoc,
9673 SourceLocation Loc,
9674 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009675 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009676 QualType ExDeclType = TInfo->getType();
9677
Sebastian Redl4b07b292008-12-22 19:15:10 +00009678 // Arrays and functions decay.
9679 if (ExDeclType->isArrayType())
9680 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9681 else if (ExDeclType->isFunctionType())
9682 ExDeclType = Context.getPointerType(ExDeclType);
9683
9684 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9685 // The exception-declaration shall not denote a pointer or reference to an
9686 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009687 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009688 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009689 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009690 Invalid = true;
9691 }
Douglas Gregord308e622009-05-18 20:51:54 +00009692
Douglas Gregora2762912010-03-08 01:47:36 +00009693 // GCC allows catching pointers and references to incomplete types
9694 // as an extension; so do we, but we warn by default.
9695
Sebastian Redl4b07b292008-12-22 19:15:10 +00009696 QualType BaseType = ExDeclType;
9697 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009698 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00009699 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00009700 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009701 BaseType = Ptr->getPointeeType();
9702 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00009703 DK = diag::ext_catch_incomplete_ptr;
9704 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009705 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009706 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009707 BaseType = Ref->getPointeeType();
9708 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00009709 DK = diag::ext_catch_incomplete_ref;
9710 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009711 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009712 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00009713 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9714 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00009715 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009716
Mike Stump1eb44332009-09-09 15:08:12 +00009717 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009718 RequireNonAbstractType(Loc, ExDeclType,
9719 diag::err_abstract_type_in_decl,
9720 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009721 Invalid = true;
9722
John McCall5a180392010-07-24 00:37:23 +00009723 // Only the non-fragile NeXT runtime currently supports C++ catches
9724 // of ObjC types, and no runtime supports catching ObjC types by value.
9725 if (!Invalid && getLangOptions().ObjC1) {
9726 QualType T = ExDeclType;
9727 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9728 T = RT->getPointeeType();
9729
9730 if (T->isObjCObjectType()) {
9731 Diag(Loc, diag::err_objc_object_catch);
9732 Invalid = true;
9733 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009734 if (!getLangOptions().ObjCNonFragileABI)
9735 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009736 }
9737 }
9738
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009739 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9740 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009741 ExDecl->setExceptionVariable(true);
9742
Douglas Gregorc41b8782011-07-06 18:14:43 +00009743 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009744 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009745 // C++ [except.handle]p16:
9746 // The object declared in an exception-declaration or, if the
9747 // exception-declaration does not specify a name, a temporary (12.2) is
9748 // copy-initialized (8.5) from the exception object. [...]
9749 // The object is destroyed when the handler exits, after the destruction
9750 // of any automatic objects initialized within the handler.
9751 //
9752 // We just pretend to initialize the object with itself, then make sure
9753 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009754 QualType initType = ExDeclType;
9755
9756 InitializedEntity entity =
9757 InitializedEntity::InitializeVariable(ExDecl);
9758 InitializationKind initKind =
9759 InitializationKind::CreateCopy(Loc, SourceLocation());
9760
9761 Expr *opaqueValue =
9762 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9763 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9764 ExprResult result = sequence.Perform(*this, entity, initKind,
9765 MultiExprArg(&opaqueValue, 1));
9766 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009767 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009768 else {
9769 // If the constructor used was non-trivial, set this as the
9770 // "initializer".
9771 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9772 if (!construct->getConstructor()->isTrivial()) {
9773 Expr *init = MaybeCreateExprWithCleanups(construct);
9774 ExDecl->setInit(init);
9775 }
9776
9777 // And make sure it's destructable.
9778 FinalizeVarWithDestructor(ExDecl, recordType);
9779 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009780 }
9781 }
9782
Douglas Gregord308e622009-05-18 20:51:54 +00009783 if (Invalid)
9784 ExDecl->setInvalidDecl();
9785
9786 return ExDecl;
9787}
9788
9789/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9790/// handler.
John McCalld226f652010-08-21 09:40:31 +00009791Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009792 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009793 bool Invalid = D.isInvalidType();
9794
9795 // Check for unexpanded parameter packs.
9796 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9797 UPPC_ExceptionType)) {
9798 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9799 D.getIdentifierLoc());
9800 Invalid = true;
9801 }
9802
Sebastian Redl4b07b292008-12-22 19:15:10 +00009803 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009804 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009805 LookupOrdinaryName,
9806 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009807 // The scope should be freshly made just for us. There is just no way
9808 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009809 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009810 if (PrevDecl->isTemplateParameter()) {
9811 // Maybe we will complain about the shadowed template parameter.
9812 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009813 }
9814 }
9815
Chris Lattnereaaebc72009-04-25 08:06:05 +00009816 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009817 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9818 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009819 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009820 }
9821
Douglas Gregor83cb9422010-09-09 17:09:21 +00009822 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009823 D.getSourceRange().getBegin(),
9824 D.getIdentifierLoc(),
9825 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009826 if (Invalid)
9827 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009828
Sebastian Redl4b07b292008-12-22 19:15:10 +00009829 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009830 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009831 PushOnScopeChains(ExDecl, S);
9832 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009833 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009834
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009835 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009836 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009837}
Anders Carlssonfb311762009-03-14 00:25:26 +00009838
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009839Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009840 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009841 Expr *AssertMessageExpr_,
9842 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009843 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009844
Anders Carlssonc3082412009-03-14 00:33:21 +00009845 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9846 llvm::APSInt Value(32);
9847 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009848 Diag(StaticAssertLoc,
9849 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00009850 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00009851 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00009852 }
Anders Carlssonfb311762009-03-14 00:25:26 +00009853
Anders Carlssonc3082412009-03-14 00:33:21 +00009854 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009855 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009856 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009857 }
9858 }
Mike Stump1eb44332009-09-09 15:08:12 +00009859
Douglas Gregor399ad972010-12-15 23:55:21 +00009860 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9861 return 0;
9862
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009863 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9864 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009865
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009866 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009867 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009868}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009869
Douglas Gregor1d869352010-04-07 16:53:43 +00009870/// \brief Perform semantic analysis of the given friend type declaration.
9871///
9872/// \returns A friend declaration that.
9873FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9874 TypeSourceInfo *TSInfo) {
9875 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9876
9877 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009878 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009879
Douglas Gregor06245bf2010-04-07 17:57:12 +00009880 if (!getLangOptions().CPlusPlus0x) {
9881 // C++03 [class.friend]p2:
9882 // An elaborated-type-specifier shall be used in a friend declaration
9883 // for a class.*
9884 //
9885 // * The class-key of the elaborated-type-specifier is required.
9886 if (!ActiveTemplateInstantiations.empty()) {
9887 // Do not complain about the form of friend template types during
9888 // template instantiation; we will already have complained when the
9889 // template was declared.
9890 } else if (!T->isElaboratedTypeSpecifier()) {
9891 // If we evaluated the type to a record type, suggest putting
9892 // a tag in front.
9893 if (const RecordType *RT = T->getAs<RecordType>()) {
9894 RecordDecl *RD = RT->getDecl();
9895
9896 std::string InsertionText = std::string(" ") + RD->getKindName();
9897
9898 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9899 << (unsigned) RD->getTagKind()
9900 << T
9901 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9902 InsertionText);
9903 } else {
9904 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9905 << T
9906 << SourceRange(FriendLoc, TypeRange.getEnd());
9907 }
9908 } else if (T->getAs<EnumType>()) {
9909 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009910 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009911 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009912 }
9913 }
9914
Douglas Gregor06245bf2010-04-07 17:57:12 +00009915 // C++0x [class.friend]p3:
9916 // If the type specifier in a friend declaration designates a (possibly
9917 // cv-qualified) class type, that class is declared as a friend; otherwise,
9918 // the friend declaration is ignored.
9919
9920 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9921 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009922
9923 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9924}
9925
John McCall9a34edb2010-10-19 01:40:49 +00009926/// Handle a friend tag declaration where the scope specifier was
9927/// templated.
9928Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9929 unsigned TagSpec, SourceLocation TagLoc,
9930 CXXScopeSpec &SS,
9931 IdentifierInfo *Name, SourceLocation NameLoc,
9932 AttributeList *Attr,
9933 MultiTemplateParamsArg TempParamLists) {
9934 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9935
9936 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009937 bool Invalid = false;
9938
9939 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009940 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009941 TempParamLists.get(),
9942 TempParamLists.size(),
9943 /*friend*/ true,
9944 isExplicitSpecialization,
9945 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009946 if (TemplateParams->size() > 0) {
9947 // This is a declaration of a class template.
9948 if (Invalid)
9949 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009950
Eric Christopher4110e132011-07-21 05:34:24 +00009951 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9952 SS, Name, NameLoc, Attr,
9953 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009954 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009955 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009956 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009957 } else {
9958 // The "template<>" header is extraneous.
9959 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9960 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9961 isExplicitSpecialization = true;
9962 }
9963 }
9964
9965 if (Invalid) return 0;
9966
9967 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9968
9969 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009970 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009971 if (TempParamLists.get()[I]->size()) {
9972 isAllExplicitSpecializations = false;
9973 break;
9974 }
9975 }
9976
9977 // FIXME: don't ignore attributes.
9978
9979 // If it's explicit specializations all the way down, just forget
9980 // about the template header and build an appropriate non-templated
9981 // friend. TODO: for source fidelity, remember the headers.
9982 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00009983 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009984 ElaboratedTypeKeyword Keyword
9985 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009986 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009987 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009988 if (T.isNull())
9989 return 0;
9990
9991 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9992 if (isa<DependentNameType>(T)) {
9993 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9994 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009995 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009996 TL.setNameLoc(NameLoc);
9997 } else {
9998 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9999 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010000 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010001 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10002 }
10003
10004 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10005 TSI, FriendLoc);
10006 Friend->setAccess(AS_public);
10007 CurContext->addDecl(Friend);
10008 return Friend;
10009 }
10010
10011 // Handle the case of a templated-scope friend class. e.g.
10012 // template <class T> class A<T>::B;
10013 // FIXME: we don't support these right now.
10014 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10015 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10016 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10017 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10018 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010019 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010020 TL.setNameLoc(NameLoc);
10021
10022 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10023 TSI, FriendLoc);
10024 Friend->setAccess(AS_public);
10025 Friend->setUnsupportedFriend(true);
10026 CurContext->addDecl(Friend);
10027 return Friend;
10028}
10029
10030
John McCalldd4a3b02009-09-16 22:47:08 +000010031/// Handle a friend type declaration. This works in tandem with
10032/// ActOnTag.
10033///
10034/// Notes on friend class templates:
10035///
10036/// We generally treat friend class declarations as if they were
10037/// declaring a class. So, for example, the elaborated type specifier
10038/// in a friend declaration is required to obey the restrictions of a
10039/// class-head (i.e. no typedefs in the scope chain), template
10040/// parameters are required to match up with simple template-ids, &c.
10041/// However, unlike when declaring a template specialization, it's
10042/// okay to refer to a template specialization without an empty
10043/// template parameter declaration, e.g.
10044/// friend class A<T>::B<unsigned>;
10045/// We permit this as a special case; if there are any template
10046/// parameters present at all, require proper matching, i.e.
10047/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010048Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010049 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010050 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010051
10052 assert(DS.isFriendSpecified());
10053 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10054
John McCalldd4a3b02009-09-16 22:47:08 +000010055 // Try to convert the decl specifier to a type. This works for
10056 // friend templates because ActOnTag never produces a ClassTemplateDecl
10057 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010058 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010059 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10060 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010061 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010062 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010063
Douglas Gregor6ccab972010-12-16 01:14:37 +000010064 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10065 return 0;
10066
John McCalldd4a3b02009-09-16 22:47:08 +000010067 // This is definitely an error in C++98. It's probably meant to
10068 // be forbidden in C++0x, too, but the specification is just
10069 // poorly written.
10070 //
10071 // The problem is with declarations like the following:
10072 // template <T> friend A<T>::foo;
10073 // where deciding whether a class C is a friend or not now hinges
10074 // on whether there exists an instantiation of A that causes
10075 // 'foo' to equal C. There are restrictions on class-heads
10076 // (which we declare (by fiat) elaborated friend declarations to
10077 // be) that makes this tractable.
10078 //
10079 // FIXME: handle "template <> friend class A<T>;", which
10080 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010081 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010082 Diag(Loc, diag::err_tagless_friend_type_template)
10083 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010084 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010085 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010086
John McCall02cace72009-08-28 07:59:38 +000010087 // C++98 [class.friend]p1: A friend of a class is a function
10088 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010089 // This is fixed in DR77, which just barely didn't make the C++03
10090 // deadline. It's also a very silly restriction that seriously
10091 // affects inner classes and which nobody else seems to implement;
10092 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010093 //
10094 // But note that we could warn about it: it's always useless to
10095 // friend one of your own members (it's not, however, worthless to
10096 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010097
John McCalldd4a3b02009-09-16 22:47:08 +000010098 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010099 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010100 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010101 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010102 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010103 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010104 DS.getFriendSpecLoc());
10105 else
Douglas Gregor1d869352010-04-07 16:53:43 +000010106 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
10107
10108 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010109 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010110
John McCalldd4a3b02009-09-16 22:47:08 +000010111 D->setAccess(AS_public);
10112 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010113
John McCalld226f652010-08-21 09:40:31 +000010114 return D;
John McCall02cace72009-08-28 07:59:38 +000010115}
10116
John McCall337ec3d2010-10-12 23:13:28 +000010117Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
10118 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010119 const DeclSpec &DS = D.getDeclSpec();
10120
10121 assert(DS.isFriendSpecified());
10122 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10123
10124 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010125 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10126 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +000010127
10128 // C++ [class.friend]p1
10129 // A friend of a class is a function or class....
10130 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010131 // It *doesn't* see through dependent types, which is correct
10132 // according to [temp.arg.type]p3:
10133 // If a declaration acquires a function type through a
10134 // type dependent on a template-parameter and this causes
10135 // a declaration that does not use the syntactic form of a
10136 // function declarator to have a function type, the program
10137 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +000010138 if (!T->isFunctionType()) {
10139 Diag(Loc, diag::err_unexpected_friend);
10140
10141 // It might be worthwhile to try to recover by creating an
10142 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010143 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010144 }
10145
10146 // C++ [namespace.memdef]p3
10147 // - If a friend declaration in a non-local class first declares a
10148 // class or function, the friend class or function is a member
10149 // of the innermost enclosing namespace.
10150 // - The name of the friend is not found by simple name lookup
10151 // until a matching declaration is provided in that namespace
10152 // scope (either before or after the class declaration granting
10153 // friendship).
10154 // - If a friend function is called, its name may be found by the
10155 // name lookup that considers functions from namespaces and
10156 // classes associated with the types of the function arguments.
10157 // - When looking for a prior declaration of a class or a function
10158 // declared as a friend, scopes outside the innermost enclosing
10159 // namespace scope are not considered.
10160
John McCall337ec3d2010-10-12 23:13:28 +000010161 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010162 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10163 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010164 assert(Name);
10165
Douglas Gregor6ccab972010-12-16 01:14:37 +000010166 // Check for unexpanded parameter packs.
10167 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10168 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10169 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10170 return 0;
10171
John McCall67d1a672009-08-06 02:15:43 +000010172 // The context we found the declaration in, or in which we should
10173 // create the declaration.
10174 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010175 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010176 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010177 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010178
John McCall337ec3d2010-10-12 23:13:28 +000010179 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010180
John McCall337ec3d2010-10-12 23:13:28 +000010181 // There are four cases here.
10182 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010183 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010184 // there as appropriate.
10185 // Recover from invalid scope qualifiers as if they just weren't there.
10186 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010187 // C++0x [namespace.memdef]p3:
10188 // If the name in a friend declaration is neither qualified nor
10189 // a template-id and the declaration is a function or an
10190 // elaborated-type-specifier, the lookup to determine whether
10191 // the entity has been previously declared shall not consider
10192 // any scopes outside the innermost enclosing namespace.
10193 // C++0x [class.friend]p11:
10194 // If a friend declaration appears in a local class and the name
10195 // specified is an unqualified name, a prior declaration is
10196 // looked up without considering scopes that are outside the
10197 // innermost enclosing non-class scope. For a friend function
10198 // declaration, if there is no prior declaration, the program is
10199 // ill-formed.
10200 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010201 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010202
John McCall29ae6e52010-10-13 05:45:15 +000010203 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010204 DC = CurContext;
10205 while (true) {
10206 // Skip class contexts. If someone can cite chapter and verse
10207 // for this behavior, that would be nice --- it's what GCC and
10208 // EDG do, and it seems like a reasonable intent, but the spec
10209 // really only says that checks for unqualified existing
10210 // declarations should stop at the nearest enclosing namespace,
10211 // not that they should only consider the nearest enclosing
10212 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010213 while (DC->isRecord())
10214 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010215
John McCall68263142009-11-18 22:49:29 +000010216 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010217
10218 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010219 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010220 break;
John McCall29ae6e52010-10-13 05:45:15 +000010221
John McCall8a407372010-10-14 22:22:28 +000010222 if (isTemplateId) {
10223 if (isa<TranslationUnitDecl>(DC)) break;
10224 } else {
10225 if (DC->isFileContext()) break;
10226 }
John McCall67d1a672009-08-06 02:15:43 +000010227 DC = DC->getParent();
10228 }
10229
10230 // C++ [class.friend]p1: A friend of a class is a function or
10231 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +000010232 // C++0x changes this for both friend types and functions.
10233 // Most C++ 98 compilers do seem to give an error here, so
10234 // we do, too.
John McCall68263142009-11-18 22:49:29 +000010235 if (!Previous.empty() && DC->Equals(CurContext)
10236 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +000010237 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010238
John McCall380aaa42010-10-13 06:22:15 +000010239 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +000010240
Douglas Gregor883af832011-10-10 01:11:59 +000010241 // C++ [class.friend]p6:
10242 // A function can be defined in a friend declaration of a class if and
10243 // only if the class is a non-local class (9.8), the function name is
10244 // unqualified, and the function has namespace scope.
10245 if (isLocal && IsDefinition) {
10246 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10247 }
10248
John McCall337ec3d2010-10-12 23:13:28 +000010249 // - There's a non-dependent scope specifier, in which case we
10250 // compute it and do a previous lookup there for a function
10251 // or function template.
10252 } else if (!SS.getScopeRep()->isDependent()) {
10253 DC = computeDeclContext(SS);
10254 if (!DC) return 0;
10255
10256 if (RequireCompleteDeclContext(SS, DC)) return 0;
10257
10258 LookupQualifiedName(Previous, DC);
10259
10260 // Ignore things found implicitly in the wrong scope.
10261 // TODO: better diagnostics for this case. Suggesting the right
10262 // qualified scope would be nice...
10263 LookupResult::Filter F = Previous.makeFilter();
10264 while (F.hasNext()) {
10265 NamedDecl *D = F.next();
10266 if (!DC->InEnclosingNamespaceSetOf(
10267 D->getDeclContext()->getRedeclContext()))
10268 F.erase();
10269 }
10270 F.done();
10271
10272 if (Previous.empty()) {
10273 D.setInvalidType();
10274 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
10275 return 0;
10276 }
10277
10278 // C++ [class.friend]p1: A friend of a class is a function or
10279 // class that is not a member of the class . . .
10280 if (DC->Equals(CurContext))
10281 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010282
10283 if (IsDefinition) {
10284 // C++ [class.friend]p6:
10285 // A function can be defined in a friend declaration of a class if and
10286 // only if the class is a non-local class (9.8), the function name is
10287 // unqualified, and the function has namespace scope.
10288 SemaDiagnosticBuilder DB
10289 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10290
10291 DB << SS.getScopeRep();
10292 if (DC->isFileContext())
10293 DB << FixItHint::CreateRemoval(SS.getRange());
10294 SS.clear();
10295 }
John McCall337ec3d2010-10-12 23:13:28 +000010296
10297 // - There's a scope specifier that does not match any template
10298 // parameter lists, in which case we use some arbitrary context,
10299 // create a method or method template, and wait for instantiation.
10300 // - There's a scope specifier that does match some template
10301 // parameter lists, which we don't handle right now.
10302 } else {
Douglas Gregor883af832011-10-10 01:11:59 +000010303 if (IsDefinition) {
10304 // C++ [class.friend]p6:
10305 // A function can be defined in a friend declaration of a class if and
10306 // only if the class is a non-local class (9.8), the function name is
10307 // unqualified, and the function has namespace scope.
10308 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10309 << SS.getScopeRep();
10310 }
10311
John McCall337ec3d2010-10-12 23:13:28 +000010312 DC = CurContext;
10313 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010314 }
Douglas Gregor883af832011-10-10 01:11:59 +000010315
John McCall29ae6e52010-10-13 05:45:15 +000010316 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010317 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010318 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10319 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10320 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010321 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010322 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10323 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010324 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010325 }
John McCall67d1a672009-08-06 02:15:43 +000010326 }
Douglas Gregor883af832011-10-10 01:11:59 +000010327
Douglas Gregor182ddf02009-09-28 00:08:27 +000010328 bool Redeclaration = false;
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010329 bool AddToScope = true;
John McCall380aaa42010-10-13 06:22:15 +000010330 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +000010331 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +000010332 IsDefinition,
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010333 Redeclaration, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010334 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010335
Douglas Gregor182ddf02009-09-28 00:08:27 +000010336 assert(ND->getDeclContext() == DC);
10337 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010338
John McCallab88d972009-08-31 22:39:49 +000010339 // Add the function declaration to the appropriate lookup tables,
10340 // adjusting the redeclarations list as necessary. We don't
10341 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010342 //
John McCallab88d972009-08-31 22:39:49 +000010343 // Also update the scope-based lookup if the target context's
10344 // lookup context is in lexical scope.
10345 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010346 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010347 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010348 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010349 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010350 }
John McCall02cace72009-08-28 07:59:38 +000010351
10352 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010353 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010354 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010355 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010356 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010357
John McCall337ec3d2010-10-12 23:13:28 +000010358 if (ND->isInvalidDecl())
10359 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010360 else {
10361 FunctionDecl *FD;
10362 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10363 FD = FTD->getTemplatedDecl();
10364 else
10365 FD = cast<FunctionDecl>(ND);
10366
10367 // Mark templated-scope function declarations as unsupported.
10368 if (FD->getNumTemplateParameterLists())
10369 FrD->setUnsupportedFriend(true);
10370 }
John McCall337ec3d2010-10-12 23:13:28 +000010371
John McCalld226f652010-08-21 09:40:31 +000010372 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010373}
10374
John McCalld226f652010-08-21 09:40:31 +000010375void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10376 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010377
Sebastian Redl50de12f2009-03-24 22:27:57 +000010378 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10379 if (!Fn) {
10380 Diag(DelLoc, diag::err_deleted_non_function);
10381 return;
10382 }
10383 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
10384 Diag(DelLoc, diag::err_deleted_decl_not_first);
10385 Diag(Prev->getLocation(), diag::note_previous_declaration);
10386 // If the declaration wasn't the first, we delete the function anyway for
10387 // recovery.
10388 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010389 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010390}
Sebastian Redl13e88542009-04-27 21:33:24 +000010391
Sean Hunte4246a62011-05-12 06:15:49 +000010392void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10393 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10394
10395 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010396 if (MD->getParent()->isDependentType()) {
10397 MD->setDefaulted();
10398 MD->setExplicitlyDefaulted();
10399 return;
10400 }
10401
Sean Hunte4246a62011-05-12 06:15:49 +000010402 CXXSpecialMember Member = getSpecialMember(MD);
10403 if (Member == CXXInvalid) {
10404 Diag(DefaultLoc, diag::err_default_special_members);
10405 return;
10406 }
10407
10408 MD->setDefaulted();
10409 MD->setExplicitlyDefaulted();
10410
Sean Huntcd10dec2011-05-23 23:14:04 +000010411 // If this definition appears within the record, do the checking when
10412 // the record is complete.
10413 const FunctionDecl *Primary = MD;
10414 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10415 // Find the uninstantiated declaration that actually had the '= default'
10416 // on it.
10417 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10418
10419 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010420 return;
10421
10422 switch (Member) {
10423 case CXXDefaultConstructor: {
10424 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10425 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010426 if (!CD->isInvalidDecl())
10427 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10428 break;
10429 }
10430
10431 case CXXCopyConstructor: {
10432 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10433 CheckExplicitlyDefaultedCopyConstructor(CD);
10434 if (!CD->isInvalidDecl())
10435 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010436 break;
10437 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010438
Sean Hunt2b188082011-05-14 05:23:28 +000010439 case CXXCopyAssignment: {
10440 CheckExplicitlyDefaultedCopyAssignment(MD);
10441 if (!MD->isInvalidDecl())
10442 DefineImplicitCopyAssignment(DefaultLoc, MD);
10443 break;
10444 }
10445
Sean Huntcb45a0f2011-05-12 22:46:25 +000010446 case CXXDestructor: {
10447 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10448 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010449 if (!DD->isInvalidDecl())
10450 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010451 break;
10452 }
10453
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010454 case CXXMoveConstructor: {
10455 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10456 CheckExplicitlyDefaultedMoveConstructor(CD);
10457 if (!CD->isInvalidDecl())
10458 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010459 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010460 }
Sean Hunt82713172011-05-25 23:16:36 +000010461
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010462 case CXXMoveAssignment: {
10463 CheckExplicitlyDefaultedMoveAssignment(MD);
10464 if (!MD->isInvalidDecl())
10465 DefineImplicitMoveAssignment(DefaultLoc, MD);
10466 break;
10467 }
10468
10469 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010470 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010471 }
10472 } else {
10473 Diag(DefaultLoc, diag::err_default_special_members);
10474 }
10475}
10476
Sebastian Redl13e88542009-04-27 21:33:24 +000010477static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010478 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010479 Stmt *SubStmt = *CI;
10480 if (!SubStmt)
10481 continue;
10482 if (isa<ReturnStmt>(SubStmt))
10483 Self.Diag(SubStmt->getSourceRange().getBegin(),
10484 diag::err_return_in_constructor_handler);
10485 if (!isa<Expr>(SubStmt))
10486 SearchForReturnInStmt(Self, SubStmt);
10487 }
10488}
10489
10490void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10491 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10492 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10493 SearchForReturnInStmt(*this, Handler);
10494 }
10495}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010496
Mike Stump1eb44332009-09-09 15:08:12 +000010497bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010498 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010499 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10500 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010501
Chandler Carruth73857792010-02-15 11:53:20 +000010502 if (Context.hasSameType(NewTy, OldTy) ||
10503 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010504 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010505
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010506 // Check if the return types are covariant
10507 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010508
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010509 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010510 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10511 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010512 NewClassTy = NewPT->getPointeeType();
10513 OldClassTy = OldPT->getPointeeType();
10514 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010515 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10516 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10517 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10518 NewClassTy = NewRT->getPointeeType();
10519 OldClassTy = OldRT->getPointeeType();
10520 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010521 }
10522 }
Mike Stump1eb44332009-09-09 15:08:12 +000010523
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010524 // The return types aren't either both pointers or references to a class type.
10525 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010526 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010527 diag::err_different_return_type_for_overriding_virtual_function)
10528 << New->getDeclName() << NewTy << OldTy;
10529 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010530
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010531 return true;
10532 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010533
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010534 // C++ [class.virtual]p6:
10535 // If the return type of D::f differs from the return type of B::f, the
10536 // class type in the return type of D::f shall be complete at the point of
10537 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010538 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10539 if (!RT->isBeingDefined() &&
10540 RequireCompleteType(New->getLocation(), NewClassTy,
10541 PDiag(diag::err_covariant_return_incomplete)
10542 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010543 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010544 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010545
Douglas Gregora4923eb2009-11-16 21:35:15 +000010546 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010547 // Check if the new class derives from the old class.
10548 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10549 Diag(New->getLocation(),
10550 diag::err_covariant_return_not_derived)
10551 << New->getDeclName() << NewTy << OldTy;
10552 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10553 return true;
10554 }
Mike Stump1eb44332009-09-09 15:08:12 +000010555
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010556 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010557 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010558 diag::err_covariant_return_inaccessible_base,
10559 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10560 // FIXME: Should this point to the return type?
10561 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010562 // FIXME: this note won't trigger for delayed access control
10563 // diagnostics, and it's impossible to get an undelayed error
10564 // here from access control during the original parse because
10565 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010566 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10567 return true;
10568 }
10569 }
Mike Stump1eb44332009-09-09 15:08:12 +000010570
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010571 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010572 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010573 Diag(New->getLocation(),
10574 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010575 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010576 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10577 return true;
10578 };
Mike Stump1eb44332009-09-09 15:08:12 +000010579
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010580
10581 // The new class type must have the same or less qualifiers as the old type.
10582 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10583 Diag(New->getLocation(),
10584 diag::err_covariant_return_type_class_type_more_qualified)
10585 << New->getDeclName() << NewTy << OldTy;
10586 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10587 return true;
10588 };
Mike Stump1eb44332009-09-09 15:08:12 +000010589
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010590 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010591}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010592
Douglas Gregor4ba31362009-12-01 17:24:26 +000010593/// \brief Mark the given method pure.
10594///
10595/// \param Method the method to be marked pure.
10596///
10597/// \param InitRange the source range that covers the "0" initializer.
10598bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010599 SourceLocation EndLoc = InitRange.getEnd();
10600 if (EndLoc.isValid())
10601 Method->setRangeEnd(EndLoc);
10602
Douglas Gregor4ba31362009-12-01 17:24:26 +000010603 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10604 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010605 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010606 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010607
10608 if (!Method->isInvalidDecl())
10609 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10610 << Method->getDeclName() << InitRange;
10611 return true;
10612}
10613
John McCall731ad842009-12-19 09:28:58 +000010614/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10615/// an initializer for the out-of-line declaration 'Dcl'. The scope
10616/// is a fresh scope pushed for just this purpose.
10617///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010618/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10619/// static data member of class X, names should be looked up in the scope of
10620/// class X.
John McCalld226f652010-08-21 09:40:31 +000010621void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010622 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010623 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010624
John McCall731ad842009-12-19 09:28:58 +000010625 // We should only get called for declarations with scope specifiers, like:
10626 // int foo::bar;
10627 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010628 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010629}
10630
10631/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010632/// initializer for the out-of-line declaration 'D'.
10633void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010634 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010635 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010636
John McCall731ad842009-12-19 09:28:58 +000010637 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010638 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010639}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010640
10641/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10642/// C++ if/switch/while/for statement.
10643/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010644DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010645 // C++ 6.4p2:
10646 // The declarator shall not specify a function or an array.
10647 // The type-specifier-seq shall not contain typedef and shall not declare a
10648 // new class or enumeration.
10649 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10650 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010651
10652 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010653 if (!Dcl)
10654 return true;
10655
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010656 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10657 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010658 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010659 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010660 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010661
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010662 return Dcl;
10663}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010664
Douglas Gregordfe65432011-07-28 19:11:31 +000010665void Sema::LoadExternalVTableUses() {
10666 if (!ExternalSource)
10667 return;
10668
10669 SmallVector<ExternalVTableUse, 4> VTables;
10670 ExternalSource->ReadUsedVTables(VTables);
10671 SmallVector<VTableUse, 4> NewUses;
10672 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10673 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10674 = VTablesUsed.find(VTables[I].Record);
10675 // Even if a definition wasn't required before, it may be required now.
10676 if (Pos != VTablesUsed.end()) {
10677 if (!Pos->second && VTables[I].DefinitionRequired)
10678 Pos->second = true;
10679 continue;
10680 }
10681
10682 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10683 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10684 }
10685
10686 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10687}
10688
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010689void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10690 bool DefinitionRequired) {
10691 // Ignore any vtable uses in unevaluated operands or for classes that do
10692 // not have a vtable.
10693 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10694 CurContext->isDependentContext() ||
10695 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010696 return;
10697
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010698 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010699 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010700 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10701 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10702 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10703 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010704 // If we already had an entry, check to see if we are promoting this vtable
10705 // to required a definition. If so, we need to reappend to the VTableUses
10706 // list, since we may have already processed the first entry.
10707 if (DefinitionRequired && !Pos.first->second) {
10708 Pos.first->second = true;
10709 } else {
10710 // Otherwise, we can early exit.
10711 return;
10712 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010713 }
10714
10715 // Local classes need to have their virtual members marked
10716 // immediately. For all other classes, we mark their virtual members
10717 // at the end of the translation unit.
10718 if (Class->isLocalClass())
10719 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010720 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010721 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010722}
10723
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010724bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010725 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010726 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010727 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010728
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010729 // Note: The VTableUses vector could grow as a result of marking
10730 // the members of a class as "used", so we check the size each
10731 // time through the loop and prefer indices (with are stable) to
10732 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010733 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010734 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010735 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010736 if (!Class)
10737 continue;
10738
10739 SourceLocation Loc = VTableUses[I].second;
10740
10741 // If this class has a key function, but that key function is
10742 // defined in another translation unit, we don't need to emit the
10743 // vtable even though we're using it.
10744 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010745 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010746 switch (KeyFunction->getTemplateSpecializationKind()) {
10747 case TSK_Undeclared:
10748 case TSK_ExplicitSpecialization:
10749 case TSK_ExplicitInstantiationDeclaration:
10750 // The key function is in another translation unit.
10751 continue;
10752
10753 case TSK_ExplicitInstantiationDefinition:
10754 case TSK_ImplicitInstantiation:
10755 // We will be instantiating the key function.
10756 break;
10757 }
10758 } else if (!KeyFunction) {
10759 // If we have a class with no key function that is the subject
10760 // of an explicit instantiation declaration, suppress the
10761 // vtable; it will live with the explicit instantiation
10762 // definition.
10763 bool IsExplicitInstantiationDeclaration
10764 = Class->getTemplateSpecializationKind()
10765 == TSK_ExplicitInstantiationDeclaration;
10766 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10767 REnd = Class->redecls_end();
10768 R != REnd; ++R) {
10769 TemplateSpecializationKind TSK
10770 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10771 if (TSK == TSK_ExplicitInstantiationDeclaration)
10772 IsExplicitInstantiationDeclaration = true;
10773 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10774 IsExplicitInstantiationDeclaration = false;
10775 break;
10776 }
10777 }
10778
10779 if (IsExplicitInstantiationDeclaration)
10780 continue;
10781 }
10782
10783 // Mark all of the virtual members of this class as referenced, so
10784 // that we can build a vtable. Then, tell the AST consumer that a
10785 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010786 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010787 MarkVirtualMembersReferenced(Loc, Class);
10788 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10789 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10790
10791 // Optionally warn if we're emitting a weak vtable.
10792 if (Class->getLinkage() == ExternalLinkage &&
10793 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010794 const FunctionDecl *KeyFunctionDef = 0;
10795 if (!KeyFunction ||
10796 (KeyFunction->hasBody(KeyFunctionDef) &&
10797 KeyFunctionDef->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010798 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10799 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010800 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010801 VTableUses.clear();
10802
Douglas Gregor78844032011-04-22 22:25:37 +000010803 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010804}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010805
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010806void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10807 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010808 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10809 e = RD->method_end(); i != e; ++i) {
10810 CXXMethodDecl *MD = *i;
10811
10812 // C++ [basic.def.odr]p2:
10813 // [...] A virtual member function is used if it is not pure. [...]
10814 if (MD->isVirtual() && !MD->isPure())
10815 MarkDeclarationReferenced(Loc, MD);
10816 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010817
10818 // Only classes that have virtual bases need a VTT.
10819 if (RD->getNumVBases() == 0)
10820 return;
10821
10822 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10823 e = RD->bases_end(); i != e; ++i) {
10824 const CXXRecordDecl *Base =
10825 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010826 if (Base->getNumVBases() == 0)
10827 continue;
10828 MarkVirtualMembersReferenced(Loc, Base);
10829 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010830}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010831
10832/// SetIvarInitializers - This routine builds initialization ASTs for the
10833/// Objective-C implementation whose ivars need be initialized.
10834void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10835 if (!getLangOptions().CPlusPlus)
10836 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010837 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010838 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010839 CollectIvarsToConstructOrDestruct(OID, ivars);
10840 if (ivars.empty())
10841 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010842 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010843 for (unsigned i = 0; i < ivars.size(); i++) {
10844 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010845 if (Field->isInvalidDecl())
10846 continue;
10847
Sean Huntcbb67482011-01-08 20:30:50 +000010848 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010849 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10850 InitializationKind InitKind =
10851 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10852
10853 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010854 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010855 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010856 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010857 // Note, MemberInit could actually come back empty if no initialization
10858 // is required (e.g., because it would call a trivial default constructor)
10859 if (!MemberInit.get() || MemberInit.isInvalid())
10860 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010861
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010862 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010863 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10864 SourceLocation(),
10865 MemberInit.takeAs<Expr>(),
10866 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010867 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010868
10869 // Be sure that the destructor is accessible and is marked as referenced.
10870 if (const RecordType *RecordTy
10871 = Context.getBaseElementType(Field->getType())
10872 ->getAs<RecordType>()) {
10873 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010874 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010875 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10876 CheckDestructorAccess(Field->getLocation(), Destructor,
10877 PDiag(diag::err_access_dtor_ivar)
10878 << Context.getBaseElementType(Field->getType()));
10879 }
10880 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010881 }
10882 ObjCImplementation->setIvarInitializers(Context,
10883 AllToInit.data(), AllToInit.size());
10884 }
10885}
Sean Huntfe57eef2011-05-04 05:57:24 +000010886
Sean Huntebcbe1d2011-05-04 23:29:54 +000010887static
10888void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10889 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10890 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10891 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10892 Sema &S) {
10893 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10894 CE = Current.end();
10895 if (Ctor->isInvalidDecl())
10896 return;
10897
10898 const FunctionDecl *FNTarget = 0;
10899 CXXConstructorDecl *Target;
10900
10901 // We ignore the result here since if we don't have a body, Target will be
10902 // null below.
10903 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10904 Target
10905= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10906
10907 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10908 // Avoid dereferencing a null pointer here.
10909 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10910
10911 if (!Current.insert(Canonical))
10912 return;
10913
10914 // We know that beyond here, we aren't chaining into a cycle.
10915 if (!Target || !Target->isDelegatingConstructor() ||
10916 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10917 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10918 Valid.insert(*CI);
10919 Current.clear();
10920 // We've hit a cycle.
10921 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10922 Current.count(TCanonical)) {
10923 // If we haven't diagnosed this cycle yet, do so now.
10924 if (!Invalid.count(TCanonical)) {
10925 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010926 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010927 << Ctor;
10928
10929 // Don't add a note for a function delegating directo to itself.
10930 if (TCanonical != Canonical)
10931 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10932
10933 CXXConstructorDecl *C = Target;
10934 while (C->getCanonicalDecl() != Canonical) {
10935 (void)C->getTargetConstructor()->hasBody(FNTarget);
10936 assert(FNTarget && "Ctor cycle through bodiless function");
10937
10938 C
10939 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10940 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10941 }
10942 }
10943
10944 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10945 Invalid.insert(*CI);
10946 Current.clear();
10947 } else {
10948 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10949 }
10950}
10951
10952
Sean Huntfe57eef2011-05-04 05:57:24 +000010953void Sema::CheckDelegatingCtorCycles() {
10954 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10955
Sean Huntebcbe1d2011-05-04 23:29:54 +000010956 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10957 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000010958
Douglas Gregor0129b562011-07-27 21:57:17 +000010959 for (DelegatingCtorDeclsType::iterator
10960 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000010961 E = DelegatingCtorDecls.end();
10962 I != E; ++I) {
10963 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000010964 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010965
10966 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10967 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000010968}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000010969
10970/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10971Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10972 // Implicitly declared functions (e.g. copy constructors) are
10973 // __host__ __device__
10974 if (D->isImplicit())
10975 return CFT_HostDevice;
10976
10977 if (D->hasAttr<CUDAGlobalAttr>())
10978 return CFT_Global;
10979
10980 if (D->hasAttr<CUDADeviceAttr>()) {
10981 if (D->hasAttr<CUDAHostAttr>())
10982 return CFT_HostDevice;
10983 else
10984 return CFT_Device;
10985 }
10986
10987 return CFT_Host;
10988}
10989
10990bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10991 CUDAFunctionTarget CalleeTarget) {
10992 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10993 // Callable from the device only."
10994 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10995 return true;
10996
10997 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10998 // Callable from the host only."
10999 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11000 // Callable from the host only."
11001 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11002 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11003 return true;
11004
11005 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11006 return true;
11007
11008 return false;
11009}