blob: ae31e61c4372f18385ae37f5619daf69478c625e [file] [log] [blame]
Chris Lattner199abbc2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000036#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000037#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner58258242008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000055
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 public:
Mike Stump11289f42009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000059
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 };
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-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 McCall8322c3a2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000071 }
72
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 }
Chris Lattner58258242008-04-10 02:22:51 +000099
Douglas Gregor8e12c382008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000102
Douglas Gregor97a9c812008-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 Lattner3b054132008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000111 }
Chris Lattner58258242008-04-10 02:22:51 +0000112}
113
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith938f40b2011-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)
Alexis Hunt6d5b96c2011-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 Smith938f40b2011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith938f40b2011-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
Alexis Hunt6d5b96c2011-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) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Alexis Hunt6d5b96c2011-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)
Alexis Hunt913820d2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith938f40b2011-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 Takumi53648472011-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 Smith938f40b2011-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 Carlssonc80a1272009-08-25 02:29:20 +0000210bool
John McCallb268a282010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-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 Jahanian8fb87ae2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000233 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000235
John McCallacf0ee52010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000238
Anders Carlssonc80a1272009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Douglas Gregor758cb672010-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 Carlsson4562f1f2009-08-25 03:18:48 +0000254 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000255}
256
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000260void
John McCall48871652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000264 return;
Mike Stump11289f42009-09-09 15:08:12 +0000265
John McCall48871652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6ff1fbf2010-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 Carlssonf1c26952009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump11289f42009-09-09 15:08:12 +0000289
John McCallb268a282010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000291}
292
Douglas Gregor58354032008-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 McCall48871652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000306
Anders Carlsson84613c42009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000308}
309
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump11289f42009-09-09 15:08:12 +0000315
John McCall48871652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000317
Anders Carlsson84613c42009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000319
Anders Carlsson84613c42009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000321}
322
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000388
Francois Pichet53fe2bb2011-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 Pichet0706d202011-09-17 17:15:52 +0000395 if (getLangOptions().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-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 Pichet93921652011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000409
Francois Pichet8cb243a2011-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 Gregor08dc5842010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregor4f15f4d2009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-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 McCall5d413782010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCalle61b02b2010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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();
Alexis Huntd051b872011-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 Gregorc732aba2009-09-11 18:44:32 +0000501 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000502 }
503 }
504
Douglas Gregorf40863c2010-02-12 07:32:17 +0000505 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000506 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000507
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000508 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000509}
510
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000511/// \brief Merge the exception specifications of two variable declarations.
512///
513/// This is called when there's a redeclaration of a VarDecl. The function
514/// checks if the redeclaration might have an exception specification and
515/// validates compatibility and merges the specs if necessary.
516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517 // Shortcut if exceptions are disabled.
518 if (!getLangOptions().CXXExceptions)
519 return;
520
521 assert(Context.hasSameType(New->getType(), Old->getType()) &&
522 "Should only be called if types are otherwise the same.");
523
524 QualType NewType = New->getType();
525 QualType OldType = Old->getType();
526
527 // We're only interested in pointers and references to functions, as well
528 // as pointers to member functions.
529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530 NewType = R->getPointeeType();
531 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533 NewType = P->getPointeeType();
534 OldType = OldType->getAs<PointerType>()->getPointeeType();
535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536 NewType = M->getPointeeType();
537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538 }
539
540 if (!NewType->isFunctionProtoType())
541 return;
542
543 // There's lots of special cases for functions. For function pointers, system
544 // libraries are hopefully not as broken so that we don't need these
545 // workarounds.
546 if (CheckEquivalentExceptionSpec(
547 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549 New->setInvalidDecl();
550 }
551}
552
Chris Lattner199abbc2008-04-08 05:04:30 +0000553/// CheckCXXDefaultArguments - Verify that the default arguments for a
554/// function declaration are well-formed according to C++
555/// [dcl.fct.default].
556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557 unsigned NumParams = FD->getNumParams();
558 unsigned p;
559
560 // Find first parameter with a default argument
561 for (p = 0; p < NumParams; ++p) {
562 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000563 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000564 break;
565 }
566
567 // C++ [dcl.fct.default]p4:
568 // In a given function declaration, all parameters
569 // subsequent to a parameter with a default argument shall
570 // have default arguments supplied in this or previous
571 // declarations. A default argument shall not be redefined
572 // by a later declaration (not even to the same value).
573 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000574 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000575 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000576 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000580 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000581 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000582 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000583 else
Mike Stump11289f42009-09-09 15:08:12 +0000584 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000585 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000586
Chris Lattner199abbc2008-04-08 05:04:30 +0000587 LastMissingDefaultArg = p;
588 }
589 }
590
591 if (LastMissingDefaultArg > 0) {
592 // Some default arguments were missing. Clear out all of the
593 // default arguments up to (and including) the last missing
594 // default argument, so that we leave the function parameters
595 // in a semantically valid state.
596 for (p = 0; p <= LastMissingDefaultArg; ++p) {
597 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000598 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000599 Param->setDefaultArg(0);
600 }
601 }
602 }
603}
Douglas Gregor556877c2008-04-13 21:30:24 +0000604
Douglas Gregor61956c42008-10-31 09:07:45 +0000605/// isCurrentClassName - Determine whether the identifier II is the
606/// name of the class type currently being defined. In the case of
607/// nested classes, this will only return true if II is the name of
608/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000613 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000614 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000615 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617 } else
618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000620 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624}
625
Mike Stump11289f42009-09-09 15:08:12 +0000626/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000627///
628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629/// and returns NULL otherwise.
630CXXBaseSpecifier *
631Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632 SourceRange SpecifierRange,
633 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000636 QualType BaseType = TInfo->getType();
637
Douglas Gregor463421d2009-03-03 04:44:36 +0000638 // C++ [class.union]p1:
639 // A union shall not have base classes.
640 if (Class->isUnion()) {
641 Diag(Class->getLocation(), diag::err_base_clause_on_union)
642 << SpecifierRange;
643 return 0;
644 }
645
Douglas Gregor752a5952011-01-03 22:36:02 +0000646 if (EllipsisLoc.isValid() &&
647 !TInfo->getType()->containsUnexpandedParameterPack()) {
648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649 << TInfo->getTypeLoc().getSourceRange();
650 EllipsisLoc = SourceLocation();
651 }
652
Douglas Gregor463421d2009-03-03 04:44:36 +0000653 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000655 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000656 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000659
660 // Base specifiers must be record types.
661 if (!BaseType->isRecordType()) {
662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663 return 0;
664 }
665
666 // C++ [class.union]p1:
667 // A union shall not be used as a base class.
668 if (BaseType->isUnionType()) {
669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670 return 0;
671 }
672
673 // C++ [class.derived]p2:
674 // The class-name in a base-specifier shall not be an incompletely
675 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000676 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000677 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000678 << SpecifierRange)) {
679 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000680 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000681 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000682
Eli Friedmanc96d4962009-08-15 21:55:26 +0000683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000685 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000686 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000690
Anders Carlsson65c76d32011-03-25 14:55:14 +0000691 // C++ [class]p3:
692 // If a class is marked final and it appears as a base-type-specifier in
693 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696 << CXXBaseDecl->getDeclName();
697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698 << CXXBaseDecl->getDeclName();
699 return 0;
700 }
701
John McCall3696dcb2010-08-17 07:23:57 +0000702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000704
705 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000707 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000708 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000709}
710
Douglas Gregor556877c2008-04-13 21:30:24 +0000711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000713/// example:
714/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000715/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000716BaseResult
John McCall48871652010-08-21 09:40:31 +0000717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000718 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000721 if (!classdecl)
722 return true;
723
Douglas Gregorc40290e2009-03-09 23:48:35 +0000724 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000726 if (!Class)
727 return true;
728
Nick Lewycky19b9f952010-07-26 16:56:01 +0000729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000731
Douglas Gregor752a5952011-01-03 22:36:02 +0000732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000734 UPPC_BaseType))
735 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000736
Douglas Gregor463421d2009-03-03 04:44:36 +0000737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000738 Virtual, Access, TInfo,
739 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000740 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000741
Douglas Gregor463421d2009-03-03 04:44:36 +0000742 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000743}
Douglas Gregor556877c2008-04-13 21:30:24 +0000744
Douglas Gregor463421d2009-03-03 04:44:36 +0000745/// \brief Performs the actual work of attaching the given base class
746/// specifiers to a C++ class.
747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748 unsigned NumBases) {
749 if (NumBases == 0)
750 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000751
752 // Used to keep track of which base types we have already seen, so
753 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000754 // that the key is always the unqualified canonical type of the base
755 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000759 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000760 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000761 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000762 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000763 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor29a92472008-10-22 17:49:05 +0000765 if (KnownBaseTypes[NewBaseType]) {
766 // C++ [class.mi]p3:
767 // A class shall not be specified as a direct base class of a
768 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000769 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000770 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000771 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000772 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000776 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000777
778 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000779 } else {
780 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000787 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000788
789 // Delete the remaining (good) base class specifiers, since their
790 // data has been copied into the CXXRecordDecl.
791 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000792 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000793
794 return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000807 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000808}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000809
John McCalle78aac42010-03-10 03:28:59 +0000810static CXXRecordDecl *GetClassForType(QualType T) {
811 if (const RecordType *RT = T->getAs<RecordType>())
812 return cast<CXXRecordDecl>(RT->getDecl());
813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814 return ICT->getDecl();
815 else
816 return 0;
817}
818
Douglas Gregor36d1b142009-10-06 17:59:45 +0000819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822 if (!getLangOptions().CPlusPlus)
823 return false;
John McCalle78aac42010-03-10 03:28:59 +0000824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000827 return false;
828
John McCalle78aac42010-03-10 03:28:59 +0000829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000831 return false;
832
John McCall67da35c2010-02-04 22:26:26 +0000833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840 if (!getLangOptions().CPlusPlus)
841 return false;
842
John McCalle78aac42010-03-10 03:28:59 +0000843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000845 return false;
846
John McCalle78aac42010-03-10 03:28:59 +0000847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000849 return false;
850
Douglas Gregor36d1b142009-10-06 17:59:45 +0000851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
Anders Carlssona70cff62010-04-24 19:06:50 +0000854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000855 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000856 assert(BasePathArray.empty() && "Base path array must be empty!");
857 assert(Paths.isRecordingPaths() && "Must record paths!");
858
859 const CXXBasePath &Path = Paths.front();
860
861 // We first go backward and check if we have a virtual base.
862 // FIXME: It would be better if CXXBasePath had the base specifier for
863 // the nearest virtual base.
864 unsigned Start = 0;
865 for (unsigned I = Path.size(); I != 0; --I) {
866 if (Path[I - 1].Base->isVirtual()) {
867 Start = I - 1;
868 break;
869 }
870 }
871
872 // Now add all bases.
873 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000875}
876
Douglas Gregor88d292c2010-05-13 16:44:06 +0000877/// \brief Determine whether the given base path includes a virtual
878/// base class.
John McCallcf142162010-08-07 06:22:56 +0000879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887}
888
Douglas Gregor36d1b142009-10-06 17:59:45 +0000889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000899 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000902 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000903 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000904 // First, determine whether the path from Derived to Base is
905 // ambiguous. This is slightly more expensive than checking whether
906 // the Derived to Base conversion exists, because here we need to
907 // explore multiple paths to determine if there is an ambiguity.
908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909 /*DetectVirtual=*/false);
910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911 assert(DerivationOkay &&
912 "Can only be used with a derived-to-base conversion");
913 (void)DerivationOkay;
914
915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000916 if (InaccessibleBaseID) {
917 // Check that the base class can be accessed.
918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919 InaccessibleBaseID)) {
920 case AR_inaccessible:
921 return true;
922 case AR_accessible:
923 case AR_dependent:
924 case AR_delayed:
925 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000926 }
John McCall5b0829a2010-02-10 09:31:12 +0000927 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000933 }
934
935 // We know that the derived-to-base conversion is ambiguous, and
936 // we're going to produce a diagnostic. Perform the derived-to-base
937 // search just one more time to compute all of the possible paths so
938 // that we can print them out. This is more expensive than any of
939 // the previous derived-to-base checks we've done, but at this point
940 // performance isn't as much of an issue.
941 Paths.clear();
942 Paths.setRecordingPaths(true);
943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944 assert(StillOkay && "Can only be used with a derived-to-base conversion");
945 (void)StillOkay;
946
947 // Build up a textual representation of the ambiguous paths, e.g.,
948 // D -> B -> A, that will be used to illustrate the ambiguous
949 // conversions in the diagnostic. We only print one of the paths
950 // to each base class subobject.
951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953 Diag(Loc, AmbigiousBaseConvID)
954 << Derived << Base << PathDisplayStr << Range << Name;
955 return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000960 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000961 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000962 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000963 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000966 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000967 Loc, Range, DeclarationName(),
968 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985 std::string PathDisplayStr;
986 std::set<unsigned> DisplayedPaths;
987 for (CXXBasePaths::paths_iterator Path = Paths.begin();
988 Path != Paths.end(); ++Path) {
989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990 // We haven't displayed a path to this particular base
991 // class subobject yet.
992 PathDisplayStr += "\n ";
993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994 for (CXXBasePath::const_iterator Element = Path->begin();
995 Element != Path->end(); ++Element)
996 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997 }
998 }
999
1000 return PathDisplayStr;
1001}
1002
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
Abramo Bagnarad7340582010-06-05 05:09:32 +00001007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +00001008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +00001015 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +00001016}
1017
Anders Carlssonfd835532011-01-20 05:57:14 +00001018/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001019void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001020 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfd835532011-01-20 05:57:14 +00001021 if (!MD || !MD->isVirtual())
1022 return;
1023
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001024 if (MD->isDependentContext())
1025 return;
1026
Anders Carlssonfd835532011-01-20 05:57:14 +00001027 // C++0x [class.virtual]p3:
1028 // If a virtual function is marked with the virt-specifier override and does
1029 // not override a member function of a base class,
1030 // the program is ill-formed.
1031 bool HasOverriddenMethods =
1032 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001034 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039}
1040
Anders Carlsson3f610c72011-01-20 16:25:36 +00001041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001046 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001047 return false;
1048
1049 Diag(New->getLocation(), diag::err_final_function_overridden)
1050 << New->getDeclName();
1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001053}
1054
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001060Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001062 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001063 Expr *BW, const VirtSpecifiers &VS,
1064 Expr *InitExpr, bool HasDeferredInit,
Richard Smith938f40b2011-06-11 17:19:42 +00001065 bool IsDefinition) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001066 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001070
1071 // For anonymous bitfields, the location should point to the type.
1072 if (Loc.isInvalid())
1073 Loc = D.getSourceRange().getBegin();
1074
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001077
John McCallb1cd7da2010-06-04 08:34:12 +00001078 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001079 assert(!DS.isFriendSpecified());
Richard Smith938f40b2011-06-11 17:19:42 +00001080 assert(!Init || !HasDeferredInit);
John McCall07e91c02009-08-06 02:15:43 +00001081
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001082 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001083
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001084 // C++ 9.2p6: A member shall not be declared to have automatic storage
1085 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001086 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087 // data members and cannot be applied to names declared const or static,
1088 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001089 switch (DS.getStorageClassSpec()) {
1090 case DeclSpec::SCS_unspecified:
1091 case DeclSpec::SCS_typedef:
1092 case DeclSpec::SCS_static:
1093 // FALL THROUGH.
1094 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001095 case DeclSpec::SCS_mutable:
1096 if (isFunc) {
1097 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001099 else
Chris Lattner3b054132008-11-19 05:08:23 +00001100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001101
Sebastian Redl8071edb2008-11-17 23:24:37 +00001102 // FIXME: It would be nicer if the keyword was ignored only for this
1103 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001104 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001105 }
1106 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001107 default:
1108 if (DS.getStorageClassSpecLoc().isValid())
1109 Diag(DS.getStorageClassSpecLoc(),
1110 diag::err_storageclass_invalid_for_member);
1111 else
1112 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113 D.getMutableDeclSpec().ClearStorageClassSpecs();
1114 }
1115
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001118 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001119
1120 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001121 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001122 CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
Douglas Gregor7c26c042011-09-21 14:40:46 +00001124 // FIXME: Check that the name is an identifier!
1125 IdentifierInfo *II = Name.getAsIdentifierInfo();
1126
1127 // Member field could not be with "template" keyword.
1128 // So TemplateParameterLists should be empty in this case.
1129 if (TemplateParameterLists.size()) {
1130 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1131 if (TemplateParams->size()) {
1132 // There is no such thing as a member field template.
1133 Diag(D.getIdentifierLoc(), diag::err_template_member)
1134 << II
1135 << SourceRange(TemplateParams->getTemplateLoc(),
1136 TemplateParams->getRAngleLoc());
1137 } else {
1138 // There is an extraneous 'template<>' for this member.
1139 Diag(TemplateParams->getTemplateLoc(),
1140 diag::err_template_member_noparams)
1141 << II
1142 << SourceRange(TemplateParams->getTemplateLoc(),
1143 TemplateParams->getRAngleLoc());
1144 }
1145 return 0;
1146 }
1147
Douglas Gregora007d362010-10-13 22:19:53 +00001148 if (SS.isSet() && !SS.isInvalid()) {
1149 // The user provided a superfluous scope specifier inside a class
1150 // definition:
1151 //
1152 // class X {
1153 // int X::member;
1154 // };
1155 DeclContext *DC = 0;
1156 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1157 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1158 << Name << FixItHint::CreateRemoval(SS.getRange());
1159 else
1160 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1161 << Name << SS.getRange();
1162
1163 SS.clear();
1164 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001165
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001166 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001167 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001168 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001169 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001170 assert(!HasDeferredInit);
1171
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001172 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001173 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001174 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001175 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001176
1177 // Non-instance-fields can't have a bitfield.
1178 if (BitWidth) {
1179 if (Member->isInvalidDecl()) {
1180 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001181 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001182 // C++ 9.6p3: A bit-field shall not be a static member.
1183 // "static member 'A' cannot be a bit-field"
1184 Diag(Loc, diag::err_static_not_bitfield)
1185 << Name << BitWidth->getSourceRange();
1186 } else if (isa<TypedefDecl>(Member)) {
1187 // "typedef member 'x' cannot be a bit-field"
1188 Diag(Loc, diag::err_typedef_not_bitfield)
1189 << Name << BitWidth->getSourceRange();
1190 } else {
1191 // A function typedef ("typedef int f(); f a;").
1192 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1193 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001194 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001195 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001196 }
Mike Stump11289f42009-09-09 15:08:12 +00001197
Chris Lattnerd26760a2009-03-05 23:01:03 +00001198 BitWidth = 0;
1199 Member->setInvalidDecl();
1200 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001201
1202 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001203
Douglas Gregor3447e762009-08-20 22:52:58 +00001204 // If we have declared a member function template, set the access of the
1205 // templated declaration as well.
1206 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1207 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001208 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001209
Anders Carlsson13a69102011-01-20 04:34:22 +00001210 if (VS.isOverrideSpecified()) {
1211 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1212 if (!MD || !MD->isVirtual()) {
1213 Diag(Member->getLocStart(),
1214 diag::override_keyword_only_allowed_on_virtual_member_functions)
1215 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001216 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001217 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001218 }
1219 if (VS.isFinalSpecified()) {
1220 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1221 if (!MD || !MD->isVirtual()) {
1222 Diag(Member->getLocStart(),
1223 diag::override_keyword_only_allowed_on_virtual_member_functions)
1224 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001225 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001226 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001227 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001228
Douglas Gregorf2f08062011-03-08 17:10:18 +00001229 if (VS.getLastLocation().isValid()) {
1230 // Update the end location of a method that has a virt-specifiers.
1231 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1232 MD->setRangeEnd(VS.getLastLocation());
1233 }
1234
Anders Carlssonc87f8612011-01-20 06:29:02 +00001235 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001236
Douglas Gregor92751d42008-11-17 22:58:34 +00001237 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001238
Douglas Gregor0c880302009-03-11 23:00:04 +00001239 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001240 AddInitializerToDecl(Member, Init, false,
1241 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith2316cd82011-09-29 19:11:37 +00001242 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1243 ActOnUninitializedDecl(Member, DS.getTypeSpecType() == DeclSpec::TST_auto);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001244
Richard Smithb2bc2e62011-02-21 20:05:19 +00001245 FinalizeDeclaration(Member);
1246
John McCall25849ca2011-02-15 07:12:36 +00001247 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001248 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001249 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001250}
1251
Richard Smith938f40b2011-06-11 17:19:42 +00001252/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00001253/// in-class initializer for a non-static C++ class member, and after
1254/// instantiating an in-class initializer in a class template. Such actions
1255/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00001256void
1257Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1258 Expr *InitExpr) {
1259 FieldDecl *FD = cast<FieldDecl>(D);
1260
1261 if (!InitExpr) {
1262 FD->setInvalidDecl();
1263 FD->removeInClassInitializer();
1264 return;
1265 }
1266
1267 ExprResult Init = InitExpr;
1268 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1269 // FIXME: if there is no EqualLoc, this is list-initialization.
1270 Init = PerformCopyInitialization(
1271 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1272 if (Init.isInvalid()) {
1273 FD->setInvalidDecl();
1274 return;
1275 }
1276
1277 CheckImplicitConversions(Init.get(), EqualLoc);
1278 }
1279
1280 // C++0x [class.base.init]p7:
1281 // The initialization of each base and member constitutes a
1282 // full-expression.
1283 Init = MaybeCreateExprWithCleanups(Init);
1284 if (Init.isInvalid()) {
1285 FD->setInvalidDecl();
1286 return;
1287 }
1288
1289 InitExpr = Init.release();
1290
1291 FD->setInClassInitializer(InitExpr);
1292}
1293
Douglas Gregor15e77a22009-12-31 09:10:24 +00001294/// \brief Find the direct and/or virtual base specifiers that
1295/// correspond to the given base type, for use in base initialization
1296/// within a constructor.
1297static bool FindBaseInitializer(Sema &SemaRef,
1298 CXXRecordDecl *ClassDecl,
1299 QualType BaseType,
1300 const CXXBaseSpecifier *&DirectBaseSpec,
1301 const CXXBaseSpecifier *&VirtualBaseSpec) {
1302 // First, check for a direct base class.
1303 DirectBaseSpec = 0;
1304 for (CXXRecordDecl::base_class_const_iterator Base
1305 = ClassDecl->bases_begin();
1306 Base != ClassDecl->bases_end(); ++Base) {
1307 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1308 // We found a direct base of this type. That's what we're
1309 // initializing.
1310 DirectBaseSpec = &*Base;
1311 break;
1312 }
1313 }
1314
1315 // Check for a virtual base class.
1316 // FIXME: We might be able to short-circuit this if we know in advance that
1317 // there are no virtual bases.
1318 VirtualBaseSpec = 0;
1319 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1320 // We haven't found a base yet; search the class hierarchy for a
1321 // virtual base class.
1322 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1323 /*DetectVirtual=*/false);
1324 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1325 BaseType, Paths)) {
1326 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1327 Path != Paths.end(); ++Path) {
1328 if (Path->back().Base->isVirtual()) {
1329 VirtualBaseSpec = Path->back().Base;
1330 break;
1331 }
1332 }
1333 }
1334 }
1335
1336 return DirectBaseSpec || VirtualBaseSpec;
1337}
1338
Sebastian Redla74948d2011-09-24 17:48:25 +00001339/// \brief Handle a C++ member initializer using braced-init-list syntax.
1340MemInitResult
1341Sema::ActOnMemInitializer(Decl *ConstructorD,
1342 Scope *S,
1343 CXXScopeSpec &SS,
1344 IdentifierInfo *MemberOrBase,
1345 ParsedType TemplateTypeTy,
1346 SourceLocation IdLoc,
1347 Expr *InitList,
1348 SourceLocation EllipsisLoc) {
1349 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1350 IdLoc, MultiInitializer(InitList), EllipsisLoc);
1351}
1352
1353/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00001354MemInitResult
John McCall48871652010-08-21 09:40:31 +00001355Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001356 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001357 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001358 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001359 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001360 SourceLocation IdLoc,
1361 SourceLocation LParenLoc,
Richard Trieu2bd04012011-09-09 02:00:50 +00001362 Expr **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001363 SourceLocation RParenLoc,
1364 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00001365 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1366 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs,
1367 RParenLoc),
1368 EllipsisLoc);
1369}
1370
1371/// \brief Handle a C++ member initializer.
1372MemInitResult
1373Sema::BuildMemInitializer(Decl *ConstructorD,
1374 Scope *S,
1375 CXXScopeSpec &SS,
1376 IdentifierInfo *MemberOrBase,
1377 ParsedType TemplateTypeTy,
1378 SourceLocation IdLoc,
1379 const MultiInitializer &Args,
1380 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001381 if (!ConstructorD)
1382 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001383
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001384 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001385
1386 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001387 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001388 if (!Constructor) {
1389 // The user wrote a constructor initializer on a function that is
1390 // not a C++ constructor. Ignore the error for now, because we may
1391 // have more member initializers coming; we'll diagnose it just
1392 // once in ActOnMemInitializers.
1393 return true;
1394 }
1395
1396 CXXRecordDecl *ClassDecl = Constructor->getParent();
1397
1398 // C++ [class.base.init]p2:
1399 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001400 // constructor's class and, if not found in that scope, are looked
1401 // up in the scope containing the constructor's definition.
1402 // [Note: if the constructor's class contains a member with the
1403 // same name as a direct or virtual base class of the class, a
1404 // mem-initializer-id naming the member or base class and composed
1405 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001406 // mem-initializer-id for the hidden base class may be specified
1407 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001408 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001409 // Look for a member, first.
1410 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001411 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001412 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001413 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001414 Member = dyn_cast<FieldDecl>(*Result.first);
Sebastian Redla74948d2011-09-24 17:48:25 +00001415
Douglas Gregor44e7df62011-01-04 00:32:56 +00001416 if (Member) {
1417 if (EllipsisLoc.isValid())
1418 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001419 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1420
1421 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001422 }
Sebastian Redla74948d2011-09-24 17:48:25 +00001423
Francois Pichetd583da02010-12-04 09:14:42 +00001424 // Handle anonymous union case.
1425 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001426 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1427 if (EllipsisLoc.isValid())
1428 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001429 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor44e7df62011-01-04 00:32:56 +00001430
Sebastian Redla74948d2011-09-24 17:48:25 +00001431 return BuildMemberInitializer(IndirectField, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001432 }
Francois Pichetd583da02010-12-04 09:14:42 +00001433 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001434 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001435 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001436 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001437 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001438
1439 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001440 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001441 } else {
1442 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1443 LookupParsedName(R, S, &SS);
1444
1445 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1446 if (!TyD) {
1447 if (R.isAmbiguous()) return true;
1448
John McCallda6841b2010-04-09 19:01:14 +00001449 // We don't want access-control diagnostics here.
1450 R.suppressDiagnostics();
1451
Douglas Gregora3b624a2010-01-19 06:46:48 +00001452 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1453 bool NotUnknownSpecialization = false;
1454 DeclContext *DC = computeDeclContext(SS, false);
1455 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1456 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1457
1458 if (!NotUnknownSpecialization) {
1459 // When the scope specifier can refer to a member of an unknown
1460 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001461 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1462 SS.getWithLocInContext(Context),
1463 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001464 if (BaseType.isNull())
1465 return true;
1466
Douglas Gregora3b624a2010-01-19 06:46:48 +00001467 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001468 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001469 }
1470 }
1471
Douglas Gregor15e77a22009-12-31 09:10:24 +00001472 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001473 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00001474 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001475 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1476 ClassDecl, false, CTC_NoKeywords))) {
1477 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1478 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1479 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001480 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001481 // We have found a non-static data member with a similar
1482 // name to what was typed; complain and initialize that
1483 // member.
1484 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001485 << MemberOrBase << true << CorrectedQuotedStr
1486 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor6da83622010-01-07 00:17:44 +00001487 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001488 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001489
Sebastian Redla74948d2011-09-24 17:48:25 +00001490 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor15e77a22009-12-31 09:10:24 +00001491 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001492 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001493 const CXXBaseSpecifier *DirectBaseSpec;
1494 const CXXBaseSpecifier *VirtualBaseSpec;
1495 if (FindBaseInitializer(*this, ClassDecl,
1496 Context.getTypeDeclType(Type),
1497 DirectBaseSpec, VirtualBaseSpec)) {
1498 // We have found a direct or virtual base class with a
1499 // similar name to what was typed; complain and initialize
1500 // that base class.
1501 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001502 << MemberOrBase << false << CorrectedQuotedStr
1503 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001504
1505 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1506 : VirtualBaseSpec;
1507 Diag(BaseSpec->getSourceRange().getBegin(),
1508 diag::note_base_class_specified_here)
1509 << BaseSpec->getType()
1510 << BaseSpec->getSourceRange();
1511
Douglas Gregor15e77a22009-12-31 09:10:24 +00001512 TyD = Type;
1513 }
1514 }
1515 }
1516
Douglas Gregora3b624a2010-01-19 06:46:48 +00001517 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001518 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla74948d2011-09-24 17:48:25 +00001519 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor15e77a22009-12-31 09:10:24 +00001520 return true;
1521 }
John McCallb5a0d312009-12-21 10:41:20 +00001522 }
1523
Douglas Gregora3b624a2010-01-19 06:46:48 +00001524 if (BaseType.isNull()) {
1525 BaseType = Context.getTypeDeclType(TyD);
1526 if (SS.isSet()) {
1527 NestedNameSpecifier *Qualifier =
1528 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001529
Douglas Gregora3b624a2010-01-19 06:46:48 +00001530 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001531 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001532 }
John McCallb5a0d312009-12-21 10:41:20 +00001533 }
1534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
John McCallbcd03502009-12-07 02:54:59 +00001536 if (!TInfo)
1537 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001538
Sebastian Redla74948d2011-09-24 17:48:25 +00001539 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001540}
1541
Chandler Carruth599deef2011-09-03 01:14:15 +00001542/// Checks a member initializer expression for cases where reference (or
1543/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00001544static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1545 Expr *Init,
1546 SourceLocation IdLoc) {
1547 QualType MemberTy = Member->getType();
1548
1549 // We only handle pointers and references currently.
1550 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1551 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1552 return;
1553
1554 const bool IsPointer = MemberTy->isPointerType();
1555 if (IsPointer) {
1556 if (const UnaryOperator *Op
1557 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1558 // The only case we're worried about with pointers requires taking the
1559 // address.
1560 if (Op->getOpcode() != UO_AddrOf)
1561 return;
1562
1563 Init = Op->getSubExpr();
1564 } else {
1565 // We only handle address-of expression initializers for pointers.
1566 return;
1567 }
1568 }
1569
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001570 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1571 // Taking the address of a temporary will be diagnosed as a hard error.
1572 if (IsPointer)
1573 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001574
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001575 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1576 << Member << Init->getSourceRange();
1577 } else if (const DeclRefExpr *DRE
1578 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1579 // We only warn when referring to a non-reference parameter declaration.
1580 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1581 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00001582 return;
1583
1584 S.Diag(Init->getExprLoc(),
1585 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1586 : diag::warn_bind_ref_member_to_parameter)
1587 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001588 } else {
1589 // Other initializers are fine.
1590 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001591 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001592
1593 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1594 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00001595}
1596
John McCalle22a04a2009-11-04 23:02:40 +00001597/// Checks an initializer expression for use of uninitialized fields, such as
1598/// containing the field that is being initialized. Returns true if there is an
1599/// uninitialized field was used an updates the SourceLocation parameter; false
1600/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001601static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001602 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001603 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001604 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1605
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001606 if (isa<CallExpr>(S)) {
1607 // Do not descend into function calls or constructors, as the use
1608 // of an uninitialized field may be valid. One would have to inspect
1609 // the contents of the function/ctor to determine if it is safe or not.
1610 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1611 // may be safe, depending on what the function/ctor does.
1612 return false;
1613 }
1614 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1615 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001616
1617 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1618 // The member expression points to a static data member.
1619 assert(VD->isStaticDataMember() &&
1620 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001621 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001622 return false;
1623 }
1624
1625 if (isa<EnumConstantDecl>(RhsField)) {
1626 // The member expression points to an enum.
1627 return false;
1628 }
1629
John McCalle22a04a2009-11-04 23:02:40 +00001630 if (RhsField == LhsField) {
1631 // Initializing a field with itself. Throw a warning.
1632 // But wait; there are exceptions!
1633 // Exception #1: The field may not belong to this record.
1634 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001635 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001636 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1637 // Even though the field matches, it does not belong to this record.
1638 return false;
1639 }
1640 // None of the exceptions triggered; return true to indicate an
1641 // uninitialized field was used.
1642 *L = ME->getMemberLoc();
1643 return true;
1644 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001645 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001646 // sizeof/alignof doesn't reference contents, do not warn.
1647 return false;
1648 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1649 // address-of doesn't reference contents (the pointer may be dereferenced
1650 // in the same expression but it would be rare; and weird).
1651 if (UOE->getOpcode() == UO_AddrOf)
1652 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001653 }
John McCall8322c3a2011-02-13 04:07:26 +00001654 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001655 if (!*it) {
1656 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001657 continue;
1658 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001659 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1660 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001661 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001662 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001663}
1664
John McCallfaf5fb42010-08-26 23:41:50 +00001665MemInitResult
Sebastian Redla74948d2011-09-24 17:48:25 +00001666Sema::BuildMemberInitializer(ValueDecl *Member,
1667 const MultiInitializer &Args,
1668 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001669 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1670 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1671 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001672 "Member must be a FieldDecl or IndirectFieldDecl");
1673
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001674 if (Member->isInvalidDecl())
1675 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001676
John McCalle22a04a2009-11-04 23:02:40 +00001677 // Diagnose value-uses of fields to initialize themselves, e.g.
1678 // foo(foo)
1679 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001680 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redla74948d2011-09-24 17:48:25 +00001681 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
1682 I != E; ++I) {
John McCalle22a04a2009-11-04 23:02:40 +00001683 SourceLocation L;
Sebastian Redla74948d2011-09-24 17:48:25 +00001684 Expr *Arg = *I;
1685 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
1686 Arg = DIE->getInit();
1687 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCalle22a04a2009-11-04 23:02:40 +00001688 // FIXME: Return true in the case when other fields are used before being
1689 // uninitialized. For example, let this field be the i'th field. When
1690 // initializing the i'th field, throw a warning if any of the >= i'th
1691 // fields are used, as they are not yet initialized.
1692 // Right now we are only handling the case where the i'th field uses
1693 // itself in its initializer.
1694 Diag(L, diag::warn_field_is_uninit);
1695 }
1696 }
1697
Sebastian Redla74948d2011-09-24 17:48:25 +00001698 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001699
Chandler Carruthd44c3102010-12-06 09:23:57 +00001700 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001701 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001702 // Can't check initialization for a member of dependent type or when
1703 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00001704 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001705
John McCall31168b02011-06-15 23:02:42 +00001706 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00001707 } else {
1708 // Initialize the member.
1709 InitializedEntity MemberEntity =
1710 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1711 : InitializedEntity::InitializeMember(IndirectMember, 0);
1712 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00001713 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
1714 Args.getEndLoc());
John McCallacf0ee52010-10-08 02:01:28 +00001715
Sebastian Redla74948d2011-09-24 17:48:25 +00001716 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001717 if (MemberInit.isInvalid())
1718 return true;
1719
Sebastian Redla74948d2011-09-24 17:48:25 +00001720 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001721
1722 // C++0x [class.base.init]p7:
1723 // The initialization of each base and member constitutes a
1724 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001725 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001726 if (MemberInit.isInvalid())
1727 return true;
1728
1729 // If we are in a dependent context, template instantiation will
1730 // perform this type-checking again. Just save the arguments that we
1731 // received in a ParenListExpr.
1732 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1733 // of the information that we have about the member
1734 // initializer. However, deconstructing the ASTs is a dicey process,
1735 // and this approach is far more likely to get the corner cases right.
Chandler Carruth599deef2011-09-03 01:14:15 +00001736 if (CurContext->isDependentContext()) {
Sebastian Redla74948d2011-09-24 17:48:25 +00001737 Init = Args.CreateInitExpr(Context,
1738 Member->getType().getNonReferenceType());
Chandler Carruth599deef2011-09-03 01:14:15 +00001739 } else {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001740 Init = MemberInit.get();
Chandler Carruth599deef2011-09-03 01:14:15 +00001741 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
1742 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001743 }
1744
Chandler Carruthd44c3102010-12-06 09:23:57 +00001745 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001746 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00001747 IdLoc, Args.getStartLoc(),
1748 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001749 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001750 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00001751 IdLoc, Args.getStartLoc(),
1752 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001753 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001754}
1755
John McCallfaf5fb42010-08-26 23:41:50 +00001756MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001757Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00001758 const MultiInitializer &Args,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001759 SourceLocation NameLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001760 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001761 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1762 if (!LangOpts.CPlusPlus0x)
1763 return Diag(Loc, diag::err_delegation_0x_only)
1764 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001765
Alexis Huntc5575cc2011-02-26 19:13:13 +00001766 // Initialize the object.
1767 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1768 QualType(ClassDecl->getTypeForDecl(), 0));
1769 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00001770 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
1771 Args.getEndLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00001772
Sebastian Redla74948d2011-09-24 17:48:25 +00001773 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Alexis Huntc5575cc2011-02-26 19:13:13 +00001774 if (DelegationInit.isInvalid())
1775 return true;
1776
1777 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00001778 CXXConstructorDecl *Constructor
1779 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00001780 assert(Constructor && "Delegating constructor with no target?");
1781
Sebastian Redla74948d2011-09-24 17:48:25 +00001782 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00001783
1784 // C++0x [class.base.init]p7:
1785 // The initialization of each base and member constitutes a
1786 // full-expression.
1787 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1788 if (DelegationInit.isInvalid())
1789 return true;
1790
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001791 assert(!CurContext->isDependentContext());
Sebastian Redla74948d2011-09-24 17:48:25 +00001792 return new (Context) CXXCtorInitializer(Context, Loc, Args.getStartLoc(),
1793 Constructor,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001794 DelegationInit.takeAs<Expr>(),
Sebastian Redla74948d2011-09-24 17:48:25 +00001795 Args.getEndLoc());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001796}
1797
1798MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001799Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00001800 const MultiInitializer &Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001801 CXXRecordDecl *ClassDecl,
1802 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00001803 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001804
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001805 SourceLocation BaseLoc
1806 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00001807
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001808 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1809 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1810 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1811
1812 // C++ [class.base.init]p2:
1813 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001814 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001815 // of that class, the mem-initializer is ill-formed. A
1816 // mem-initializer-list can initialize a base class using any
1817 // name that denotes that base class type.
1818 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1819
Douglas Gregor44e7df62011-01-04 00:32:56 +00001820 if (EllipsisLoc.isValid()) {
1821 // This is a pack expansion.
1822 if (!BaseType->containsUnexpandedParameterPack()) {
1823 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla74948d2011-09-24 17:48:25 +00001824 << SourceRange(BaseLoc, Args.getEndLoc());
1825
Douglas Gregor44e7df62011-01-04 00:32:56 +00001826 EllipsisLoc = SourceLocation();
1827 }
1828 } else {
1829 // Check for any unexpanded parameter packs.
1830 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1831 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00001832
1833 if (Args.DiagnoseUnexpandedParameterPack(*this))
1834 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001835 }
Sebastian Redla74948d2011-09-24 17:48:25 +00001836
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001837 // Check for direct and virtual base classes.
1838 const CXXBaseSpecifier *DirectBaseSpec = 0;
1839 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1840 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001841 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1842 BaseType))
Sebastian Redla74948d2011-09-24 17:48:25 +00001843 return BuildDelegatingInitializer(BaseTInfo, Args, BaseLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001844
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001845 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1846 VirtualBaseSpec);
1847
1848 // C++ [base.class.init]p2:
1849 // Unless the mem-initializer-id names a nonstatic data member of the
1850 // constructor's class or a direct or virtual base of that class, the
1851 // mem-initializer is ill-formed.
1852 if (!DirectBaseSpec && !VirtualBaseSpec) {
1853 // If the class has any dependent bases, then it's possible that
1854 // one of those types will resolve to the same type as
1855 // BaseType. Therefore, just treat this as a dependent base
1856 // class initialization. FIXME: Should we try to check the
1857 // initialization anyway? It seems odd.
1858 if (ClassDecl->hasAnyDependentBases())
1859 Dependent = true;
1860 else
1861 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1862 << BaseType << Context.getTypeDeclType(ClassDecl)
1863 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1864 }
1865 }
1866
1867 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001868 // Can't check initialization for a base of dependent type or when
1869 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00001870 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001871
John McCall31168b02011-06-15 23:02:42 +00001872 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001873
Sebastian Redla74948d2011-09-24 17:48:25 +00001874 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1875 /*IsVirtual=*/false,
1876 Args.getStartLoc(), BaseInit,
1877 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001878 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001879
1880 // C++ [base.class.init]p2:
1881 // If a mem-initializer-id is ambiguous because it designates both
1882 // a direct non-virtual base class and an inherited virtual base
1883 // class, the mem-initializer is ill-formed.
1884 if (DirectBaseSpec && VirtualBaseSpec)
1885 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001886 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001887
1888 CXXBaseSpecifier *BaseSpec
1889 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1890 if (!BaseSpec)
1891 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1892
1893 // Initialize the base.
1894 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001895 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001896 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00001897 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
1898 Args.getEndLoc());
1899
1900 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001901 if (BaseInit.isInvalid())
1902 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001903
Sebastian Redla74948d2011-09-24 17:48:25 +00001904 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
1905
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001906 // C++0x [class.base.init]p7:
1907 // The initialization of each base and member constitutes a
1908 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001909 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001910 if (BaseInit.isInvalid())
1911 return true;
1912
1913 // If we are in a dependent context, template instantiation will
1914 // perform this type-checking again. Just save the arguments that we
1915 // received in a ParenListExpr.
1916 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1917 // of the information that we have about the base
1918 // initializer. However, deconstructing the ASTs is a dicey process,
1919 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00001920 if (CurContext->isDependentContext())
1921 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001922
Alexis Hunt1d792652011-01-08 20:30:50 +00001923 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00001924 BaseSpec->isVirtual(),
1925 Args.getStartLoc(),
1926 BaseInit.takeAs<Expr>(),
1927 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001928}
1929
Sebastian Redl22653ba2011-08-30 19:58:05 +00001930// Create a static_cast\<T&&>(expr).
1931static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
1932 QualType ExprType = E->getType();
1933 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
1934 SourceLocation ExprLoc = E->getLocStart();
1935 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
1936 TargetType, ExprLoc);
1937
1938 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1939 SourceRange(ExprLoc, ExprLoc),
1940 E->getSourceRange()).take();
1941}
1942
Anders Carlsson1b00e242010-04-23 03:10:23 +00001943/// ImplicitInitializerKind - How an implicit base or member initializer should
1944/// initialize its base or member.
1945enum ImplicitInitializerKind {
1946 IIK_Default,
1947 IIK_Copy,
1948 IIK_Move
1949};
1950
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001951static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001952BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001953 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001954 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001955 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001956 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001957 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001958 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1959 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001960
John McCalldadc5752010-08-24 06:29:42 +00001961 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001962
1963 switch (ImplicitInitKind) {
1964 case IIK_Default: {
1965 InitializationKind InitKind
1966 = InitializationKind::CreateDefault(Constructor->getLocation());
1967 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1968 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001969 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001970 break;
1971 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001972
Sebastian Redl22653ba2011-08-30 19:58:05 +00001973 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00001974 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00001975 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001976 ParmVarDecl *Param = Constructor->getParamDecl(0);
1977 QualType ParamType = Param->getType().getNonReferenceType();
1978
1979 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001980 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001981 Constructor->getLocation(), ParamType,
1982 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00001983
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001984 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001985 QualType ArgTy =
1986 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1987 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001988
Sebastian Redl22653ba2011-08-30 19:58:05 +00001989 if (Moving) {
1990 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
1991 }
1992
John McCallcf142162010-08-07 06:22:56 +00001993 CXXCastPath BasePath;
1994 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001995 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1996 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00001997 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00001998 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001999
Anders Carlsson1b00e242010-04-23 03:10:23 +00002000 InitializationKind InitKind
2001 = InitializationKind::CreateDirect(Constructor->getLocation(),
2002 SourceLocation(), SourceLocation());
2003 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2004 &CopyCtorArg, 1);
2005 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002006 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002007 break;
2008 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002009 }
John McCallb268a282010-08-23 23:25:46 +00002010
Douglas Gregora40433a2010-12-07 00:41:46 +00002011 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002012 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002013 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002014
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002015 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002016 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002017 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2018 SourceLocation()),
2019 BaseSpec->isVirtual(),
2020 SourceLocation(),
2021 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002022 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002023 SourceLocation());
2024
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002025 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002026}
2027
Sebastian Redl22653ba2011-08-30 19:58:05 +00002028static bool RefersToRValueRef(Expr *MemRef) {
2029 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2030 return Referenced->getType()->isRValueReferenceType();
2031}
2032
Anders Carlsson3c1db572010-04-23 02:15:47 +00002033static bool
2034BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002035 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002036 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002037 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002038 if (Field->isInvalidDecl())
2039 return true;
2040
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002041 SourceLocation Loc = Constructor->getLocation();
2042
Sebastian Redl22653ba2011-08-30 19:58:05 +00002043 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2044 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002045 ParmVarDecl *Param = Constructor->getParamDecl(0);
2046 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002047
2048 // Suppress copying zero-width bitfields.
2049 if (const Expr *Width = Field->getBitWidth())
2050 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2051 return false;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002052
2053 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00002054 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002055 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002056
Sebastian Redl22653ba2011-08-30 19:58:05 +00002057 if (Moving) {
2058 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2059 }
2060
Douglas Gregor94f9a482010-05-05 05:51:00 +00002061 // Build a reference to this field within the parameter.
2062 CXXScopeSpec SS;
2063 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2064 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002065 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2066 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002067 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002068 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002069 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002070 ParamType, Loc,
2071 /*IsArrow=*/false,
2072 SS,
2073 /*FirstQualifierInScope=*/0,
2074 MemberLookup,
2075 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002076 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002077 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002078
2079 // C++11 [class.copy]p15:
2080 // - if a member m has rvalue reference type T&&, it is direct-initialized
2081 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002082 if (RefersToRValueRef(CtorArg.get())) {
2083 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002084 }
2085
Douglas Gregor94f9a482010-05-05 05:51:00 +00002086 // When the field we are copying is an array, create index variables for
2087 // each dimension of the array. We use these index variables to subscript
2088 // the source array, and other clients (e.g., CodeGen) will perform the
2089 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002090 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002091 QualType BaseType = Field->getType();
2092 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002093 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002094 while (const ConstantArrayType *Array
2095 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002096 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002097 // Create the iteration variable for this array index.
2098 IdentifierInfo *IterationVarName = 0;
2099 {
2100 llvm::SmallString<8> Str;
2101 llvm::raw_svector_ostream OS(Str);
2102 OS << "__i" << IndexVariables.size();
2103 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2104 }
2105 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002106 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002107 IterationVarName, SizeType,
2108 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002109 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002110 IndexVariables.push_back(IterationVar);
2111
2112 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002113 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00002114 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002115 assert(!IterationVarRef.isInvalid() &&
2116 "Reference to invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00002117
Douglas Gregor94f9a482010-05-05 05:51:00 +00002118 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00002119 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00002120 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00002121 Loc);
2122 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00002123 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002124
Douglas Gregor94f9a482010-05-05 05:51:00 +00002125 BaseType = Array->getElementType();
2126 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00002127
2128 // The array subscript expression is an lvalue, which is wrong for moving.
2129 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00002130 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002131
Douglas Gregor94f9a482010-05-05 05:51:00 +00002132 // Construct the entity that we will be initializing. For an array, this
2133 // will be first element in the array, which may require several levels
2134 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002135 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002136 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00002137 if (Indirect)
2138 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2139 else
2140 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00002141 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2142 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2143 0,
2144 Entities.back()));
2145
2146 // Direct-initialize to use the copy constructor.
2147 InitializationKind InitKind =
2148 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2149
Sebastian Redle9c4e842011-09-04 18:14:28 +00002150 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregor94f9a482010-05-05 05:51:00 +00002151 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002152 &CtorArgE, 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002153
John McCalldadc5752010-08-24 06:29:42 +00002154 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002155 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002156 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002157 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002158 if (MemberInit.isInvalid())
2159 return true;
2160
Douglas Gregor493627b2011-08-10 15:22:55 +00002161 if (Indirect) {
2162 assert(IndexVariables.size() == 0 &&
2163 "Indirect field improperly initialized");
2164 CXXMemberInit
2165 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2166 Loc, Loc,
2167 MemberInit.takeAs<Expr>(),
2168 Loc);
2169 } else
2170 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2171 Loc, MemberInit.takeAs<Expr>(),
2172 Loc,
2173 IndexVariables.data(),
2174 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002175 return false;
2176 }
2177
Anders Carlsson423f5d82010-04-23 16:04:08 +00002178 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2179
Anders Carlsson3c1db572010-04-23 02:15:47 +00002180 QualType FieldBaseElementType =
2181 SemaRef.Context.getBaseElementType(Field->getType());
2182
Anders Carlsson3c1db572010-04-23 02:15:47 +00002183 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002184 InitializedEntity InitEntity
2185 = Indirect? InitializedEntity::InitializeMember(Indirect)
2186 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002187 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002188 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002189
2190 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002191 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002192 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002193
Douglas Gregora40433a2010-12-07 00:41:46 +00002194 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002195 if (MemberInit.isInvalid())
2196 return true;
2197
Douglas Gregor493627b2011-08-10 15:22:55 +00002198 if (Indirect)
2199 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2200 Indirect, Loc,
2201 Loc,
2202 MemberInit.get(),
2203 Loc);
2204 else
2205 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2206 Field, Loc, Loc,
2207 MemberInit.get(),
2208 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002209 return false;
2210 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002211
Alexis Hunt8b455182011-05-17 00:19:05 +00002212 if (!Field->getParent()->isUnion()) {
2213 if (FieldBaseElementType->isReferenceType()) {
2214 SemaRef.Diag(Constructor->getLocation(),
2215 diag::err_uninitialized_member_in_ctor)
2216 << (int)Constructor->isImplicit()
2217 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2218 << 0 << Field->getDeclName();
2219 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2220 return true;
2221 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002222
Alexis Hunt8b455182011-05-17 00:19:05 +00002223 if (FieldBaseElementType.isConstQualified()) {
2224 SemaRef.Diag(Constructor->getLocation(),
2225 diag::err_uninitialized_member_in_ctor)
2226 << (int)Constructor->isImplicit()
2227 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2228 << 1 << Field->getDeclName();
2229 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2230 return true;
2231 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002232 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002233
John McCall31168b02011-06-15 23:02:42 +00002234 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2235 FieldBaseElementType->isObjCRetainableType() &&
2236 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2237 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2238 // Instant objects:
2239 // Default-initialize Objective-C pointers to NULL.
2240 CXXMemberInit
2241 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2242 Loc, Loc,
2243 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2244 Loc);
2245 return false;
2246 }
2247
Anders Carlsson3c1db572010-04-23 02:15:47 +00002248 // Nothing to initialize.
2249 CXXMemberInit = 0;
2250 return false;
2251}
John McCallbc83b3f2010-05-20 23:23:51 +00002252
2253namespace {
2254struct BaseAndFieldInfo {
2255 Sema &S;
2256 CXXConstructorDecl *Ctor;
2257 bool AnyErrorsInInits;
2258 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002259 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002260 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002261
2262 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2263 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002264 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2265 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00002266 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002267 else if (Generated && Ctor->isMoveConstructor())
2268 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00002269 else
2270 IIK = IIK_Default;
2271 }
2272};
2273}
2274
Richard Smithc94ec842011-09-19 13:34:43 +00002275/// \brief Determine whether the given indirect field declaration is somewhere
2276/// within an anonymous union.
2277static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2278 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2279 CEnd = F->chain_end();
2280 C != CEnd; ++C)
2281 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2282 if (Record->isUnion())
2283 return true;
2284
2285 return false;
2286}
2287
Richard Smith938f40b2011-06-11 17:19:42 +00002288static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00002289 FieldDecl *Field,
2290 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00002291
Chandler Carruth139e9622010-06-30 02:59:29 +00002292 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002293 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002294 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002295 return false;
2296 }
2297
Richard Smith938f40b2011-06-11 17:19:42 +00002298 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2299 // has a brace-or-equal-initializer, the entity is initialized as specified
2300 // in [dcl.init].
2301 if (Field->hasInClassInitializer()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002302 CXXCtorInitializer *Init;
2303 if (Indirect)
2304 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2305 SourceLocation(),
2306 SourceLocation(), 0,
2307 SourceLocation());
2308 else
2309 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2310 SourceLocation(),
2311 SourceLocation(), 0,
2312 SourceLocation());
2313 Info.AllToInit.push_back(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002314 return false;
2315 }
2316
Richard Smith12d5ed82011-09-18 11:14:50 +00002317 // Don't build an implicit initializer for union members if none was
2318 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00002319 if (Field->getParent()->isUnion() ||
2320 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00002321 return false;
2322
John McCallbc83b3f2010-05-20 23:23:51 +00002323 // Don't try to build an implicit initializer if there were semantic
2324 // errors in any of the initializers (and therefore we might be
2325 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002326 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002327 return false;
2328
Alexis Hunt1d792652011-01-08 20:30:50 +00002329 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00002330 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2331 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00002332 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002333
Francois Pichetd583da02010-12-04 09:14:42 +00002334 if (Init)
2335 Info.AllToInit.push_back(Init);
2336
John McCallbc83b3f2010-05-20 23:23:51 +00002337 return false;
2338}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002339
2340bool
2341Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2342 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002343 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002344 Constructor->setNumCtorInitializers(1);
2345 CXXCtorInitializer **initializer =
2346 new (Context) CXXCtorInitializer*[1];
2347 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2348 Constructor->setCtorInitializers(initializer);
2349
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002350 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2351 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2352 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2353 }
2354
Alexis Hunte2622992011-05-05 00:05:47 +00002355 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002356
Alexis Hunt61bc1732011-05-01 07:04:31 +00002357 return false;
2358}
Douglas Gregor493627b2011-08-10 15:22:55 +00002359
John McCall1b1a1db2011-06-17 00:18:42 +00002360bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2361 CXXCtorInitializer **Initializers,
2362 unsigned NumInitializers,
2363 bool AnyErrors) {
Douglas Gregor52235292011-09-22 23:04:35 +00002364 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002365 // Just store the initializers as written, they will be checked during
2366 // instantiation.
2367 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002368 Constructor->setNumCtorInitializers(NumInitializers);
2369 CXXCtorInitializer **baseOrMemberInitializers =
2370 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002371 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002372 NumInitializers * sizeof(CXXCtorInitializer*));
2373 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002374 }
2375
2376 return false;
2377 }
2378
John McCallbc83b3f2010-05-20 23:23:51 +00002379 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002380
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002381 // We need to build the initializer AST according to order of construction
2382 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002383 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002384 if (!ClassDecl)
2385 return true;
2386
Eli Friedman9cf6b592009-11-09 19:20:36 +00002387 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002388
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002389 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002390 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002391
2392 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002393 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002394 else
Francois Pichetd583da02010-12-04 09:14:42 +00002395 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002396 }
2397
Anders Carlsson43c64af2010-04-21 19:52:01 +00002398 // Keep track of the direct virtual bases.
2399 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2400 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2401 E = ClassDecl->bases_end(); I != E; ++I) {
2402 if (I->isVirtual())
2403 DirectVBases.insert(I);
2404 }
2405
Anders Carlssondb0a9652010-04-02 06:26:44 +00002406 // Push virtual bases before others.
2407 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2408 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2409
Alexis Hunt1d792652011-01-08 20:30:50 +00002410 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002411 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2412 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002413 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002414 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002415 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002416 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002417 VBase, IsInheritedVirtualBase,
2418 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002419 HadError = true;
2420 continue;
2421 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002422
John McCallbc83b3f2010-05-20 23:23:51 +00002423 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002424 }
2425 }
Mike Stump11289f42009-09-09 15:08:12 +00002426
John McCallbc83b3f2010-05-20 23:23:51 +00002427 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002428 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2429 E = ClassDecl->bases_end(); Base != E; ++Base) {
2430 // Virtuals are in the virtual base list and already constructed.
2431 if (Base->isVirtual())
2432 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002433
Alexis Hunt1d792652011-01-08 20:30:50 +00002434 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002435 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2436 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002437 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002438 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002439 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002440 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002441 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002442 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002443 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002444 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002445
John McCallbc83b3f2010-05-20 23:23:51 +00002446 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002447 }
2448 }
Mike Stump11289f42009-09-09 15:08:12 +00002449
John McCallbc83b3f2010-05-20 23:23:51 +00002450 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00002451 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2452 MemEnd = ClassDecl->decls_end();
2453 Mem != MemEnd; ++Mem) {
2454 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2455 if (F->getType()->isIncompleteArrayType()) {
2456 assert(ClassDecl->hasFlexibleArrayMember() &&
2457 "Incomplete array type is not valid");
2458 continue;
2459 }
2460
Sebastian Redl22653ba2011-08-30 19:58:05 +00002461 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00002462 // handle anonymous struct/union fields based on their individual
2463 // indirect fields.
2464 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2465 continue;
2466
2467 if (CollectFieldInitializer(*this, Info, F))
2468 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002469 continue;
2470 }
Douglas Gregor493627b2011-08-10 15:22:55 +00002471
2472 // Beyond this point, we only consider default initialization.
2473 if (Info.IIK != IIK_Default)
2474 continue;
2475
2476 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2477 if (F->getType()->isIncompleteArrayType()) {
2478 assert(ClassDecl->hasFlexibleArrayMember() &&
2479 "Incomplete array type is not valid");
2480 continue;
2481 }
2482
Douglas Gregor493627b2011-08-10 15:22:55 +00002483 // Initialize each field of an anonymous struct individually.
2484 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2485 HadError = true;
2486
2487 continue;
2488 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002489 }
Mike Stump11289f42009-09-09 15:08:12 +00002490
John McCallbc83b3f2010-05-20 23:23:51 +00002491 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002492 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002493 Constructor->setNumCtorInitializers(NumInitializers);
2494 CXXCtorInitializer **baseOrMemberInitializers =
2495 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002496 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002497 NumInitializers * sizeof(CXXCtorInitializer*));
2498 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002499
John McCalla6309952010-03-16 21:39:52 +00002500 // Constructors implicitly reference the base and member
2501 // destructors.
2502 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2503 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002504 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002505
2506 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002507}
2508
Eli Friedman952c15d2009-07-21 19:28:10 +00002509static void *GetKeyForTopLevelField(FieldDecl *Field) {
2510 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002511 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002512 if (RT->getDecl()->isAnonymousStructOrUnion())
2513 return static_cast<void *>(RT->getDecl());
2514 }
2515 return static_cast<void *>(Field);
2516}
2517
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002518static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002519 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002520}
2521
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002522static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002523 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002524 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002525 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002526
Eli Friedman952c15d2009-07-21 19:28:10 +00002527 // For fields injected into the class via declaration of an anonymous union,
2528 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002529 FieldDecl *Field = Member->getAnyMember();
2530
John McCall23eebd92010-04-10 09:28:51 +00002531 // If the field is a member of an anonymous struct or union, our key
2532 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002533 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002534 if (RD->isAnonymousStructOrUnion()) {
2535 while (true) {
2536 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2537 if (Parent->isAnonymousStructOrUnion())
2538 RD = Parent;
2539 else
2540 break;
2541 }
2542
Anders Carlsson83ac3122010-03-30 16:19:37 +00002543 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002544 }
Mike Stump11289f42009-09-09 15:08:12 +00002545
Anders Carlssona942dcd2010-03-30 15:39:27 +00002546 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002547}
2548
Anders Carlssone857b292010-04-02 03:37:03 +00002549static void
2550DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002551 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002552 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002553 unsigned NumInits) {
2554 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002555 return;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002557 // Don't check initializers order unless the warning is enabled at the
2558 // location of at least one initializer.
2559 bool ShouldCheckOrder = false;
2560 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002561 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002562 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2563 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00002564 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002565 ShouldCheckOrder = true;
2566 break;
2567 }
2568 }
2569 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002570 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002571
John McCallbb7b6582010-04-10 07:37:23 +00002572 // Build the list of bases and members in the order that they'll
2573 // actually be initialized. The explicit initializers should be in
2574 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002575 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002576
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002577 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2578
John McCallbb7b6582010-04-10 07:37:23 +00002579 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002580 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002581 ClassDecl->vbases_begin(),
2582 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002583 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002584
John McCallbb7b6582010-04-10 07:37:23 +00002585 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002586 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002587 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002588 if (Base->isVirtual())
2589 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002590 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002591 }
Mike Stump11289f42009-09-09 15:08:12 +00002592
John McCallbb7b6582010-04-10 07:37:23 +00002593 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002594 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2595 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002596 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002597
John McCallbb7b6582010-04-10 07:37:23 +00002598 unsigned NumIdealInits = IdealInitKeys.size();
2599 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002600
Alexis Hunt1d792652011-01-08 20:30:50 +00002601 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002602 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002603 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002604 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002605
2606 // Scan forward to try to find this initializer in the idealized
2607 // initializers list.
2608 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2609 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002610 break;
John McCallbb7b6582010-04-10 07:37:23 +00002611
2612 // If we didn't find this initializer, it must be because we
2613 // scanned past it on a previous iteration. That can only
2614 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002615 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002616 Sema::SemaDiagnosticBuilder D =
2617 SemaRef.Diag(PrevInit->getSourceLocation(),
2618 diag::warn_initializer_out_of_order);
2619
Francois Pichetd583da02010-12-04 09:14:42 +00002620 if (PrevInit->isAnyMemberInitializer())
2621 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002622 else
2623 D << 1 << PrevInit->getBaseClassInfo()->getType();
2624
Francois Pichetd583da02010-12-04 09:14:42 +00002625 if (Init->isAnyMemberInitializer())
2626 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002627 else
2628 D << 1 << Init->getBaseClassInfo()->getType();
2629
2630 // Move back to the initializer's location in the ideal list.
2631 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2632 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002633 break;
John McCallbb7b6582010-04-10 07:37:23 +00002634
2635 assert(IdealIndex != NumIdealInits &&
2636 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002637 }
John McCallbb7b6582010-04-10 07:37:23 +00002638
2639 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002640 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002641}
2642
John McCall23eebd92010-04-10 09:28:51 +00002643namespace {
2644bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002645 CXXCtorInitializer *Init,
2646 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002647 if (!PrevInit) {
2648 PrevInit = Init;
2649 return false;
2650 }
2651
2652 if (FieldDecl *Field = Init->getMember())
2653 S.Diag(Init->getSourceLocation(),
2654 diag::err_multiple_mem_initialization)
2655 << Field->getDeclName()
2656 << Init->getSourceRange();
2657 else {
John McCall424cec92011-01-19 06:33:43 +00002658 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002659 assert(BaseClass && "neither field nor base");
2660 S.Diag(Init->getSourceLocation(),
2661 diag::err_multiple_base_initialization)
2662 << QualType(BaseClass, 0)
2663 << Init->getSourceRange();
2664 }
2665 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2666 << 0 << PrevInit->getSourceRange();
2667
2668 return true;
2669}
2670
Alexis Hunt1d792652011-01-08 20:30:50 +00002671typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002672typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2673
2674bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002675 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002676 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002677 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002678 RecordDecl *Parent = Field->getParent();
2679 if (!Parent->isAnonymousStructOrUnion())
2680 return false;
2681
2682 NamedDecl *Child = Field;
2683 do {
2684 if (Parent->isUnion()) {
2685 UnionEntry &En = Unions[Parent];
2686 if (En.first && En.first != Child) {
2687 S.Diag(Init->getSourceLocation(),
2688 diag::err_multiple_mem_union_initialization)
2689 << Field->getDeclName()
2690 << Init->getSourceRange();
2691 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2692 << 0 << En.second->getSourceRange();
2693 return true;
2694 } else if (!En.first) {
2695 En.first = Child;
2696 En.second = Init;
2697 }
2698 }
2699
2700 Child = Parent;
2701 Parent = cast<RecordDecl>(Parent->getDeclContext());
2702 } while (Parent->isAnonymousStructOrUnion());
2703
2704 return false;
2705}
2706}
2707
Anders Carlssone857b292010-04-02 03:37:03 +00002708/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002709void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002710 SourceLocation ColonLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00002711 CXXCtorInitializer **meminits,
2712 unsigned NumMemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00002713 bool AnyErrors) {
2714 if (!ConstructorDecl)
2715 return;
2716
2717 AdjustDeclIfTemplate(ConstructorDecl);
2718
2719 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002720 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002721
2722 if (!Constructor) {
2723 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2724 return;
2725 }
2726
Alexis Hunt1d792652011-01-08 20:30:50 +00002727 CXXCtorInitializer **MemInits =
2728 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002729
2730 // Mapping for the duplicate initializers check.
2731 // For member initializers, this is keyed with a FieldDecl*.
2732 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002733 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002734
2735 // Mapping for the inconsistent anonymous-union initializers check.
2736 RedundantUnionMap MemberUnions;
2737
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002738 bool HadError = false;
2739 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002740 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002741
Abramo Bagnara341d7832010-05-26 18:09:23 +00002742 // Set the source order index.
2743 Init->setSourceOrder(i);
2744
Francois Pichetd583da02010-12-04 09:14:42 +00002745 if (Init->isAnyMemberInitializer()) {
2746 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002747 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2748 CheckRedundantUnionInit(*this, Init, MemberUnions))
2749 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002750 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002751 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2752 if (CheckRedundantInit(*this, Init, Members[Key]))
2753 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002754 } else {
2755 assert(Init->isDelegatingInitializer());
2756 // This must be the only initializer
2757 if (i != 0 || NumMemInits > 1) {
2758 Diag(MemInits[0]->getSourceLocation(),
2759 diag::err_delegating_initializer_alone)
2760 << MemInits[0]->getSourceRange();
2761 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002762 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002763 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002764 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002765 // Return immediately as the initializer is set.
2766 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002767 }
Anders Carlssone857b292010-04-02 03:37:03 +00002768 }
2769
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002770 if (HadError)
2771 return;
2772
Anders Carlssone857b292010-04-02 03:37:03 +00002773 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002774
Alexis Hunt1d792652011-01-08 20:30:50 +00002775 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002776}
2777
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002778void
John McCalla6309952010-03-16 21:39:52 +00002779Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2780 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00002781 // Ignore dependent contexts. Also ignore unions, since their members never
2782 // have destructors implicitly called.
2783 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00002784 return;
John McCall1064d7e2010-03-16 05:22:47 +00002785
2786 // FIXME: all the access-control diagnostics are positioned on the
2787 // field/base declaration. That's probably good; that said, the
2788 // user might reasonably want to know why the destructor is being
2789 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002790
Anders Carlssondee9a302009-11-17 04:44:12 +00002791 // Non-static data members.
2792 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2793 E = ClassDecl->field_end(); I != E; ++I) {
2794 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002795 if (Field->isInvalidDecl())
2796 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002797 QualType FieldType = Context.getBaseElementType(Field->getType());
2798
2799 const RecordType* RT = FieldType->getAs<RecordType>();
2800 if (!RT)
2801 continue;
2802
2803 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002804 if (FieldClassDecl->isInvalidDecl())
2805 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002806 if (FieldClassDecl->hasTrivialDestructor())
2807 continue;
2808
Douglas Gregore71edda2010-07-01 22:47:18 +00002809 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002810 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002811 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002812 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002813 << Field->getDeclName()
2814 << FieldType);
2815
John McCalla6309952010-03-16 21:39:52 +00002816 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002817 }
2818
John McCall1064d7e2010-03-16 05:22:47 +00002819 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2820
Anders Carlssondee9a302009-11-17 04:44:12 +00002821 // Bases.
2822 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2823 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002824 // Bases are always records in a well-formed non-dependent class.
2825 const RecordType *RT = Base->getType()->getAs<RecordType>();
2826
2827 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002828 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002829 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002830
John McCall1064d7e2010-03-16 05:22:47 +00002831 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002832 // If our base class is invalid, we probably can't get its dtor anyway.
2833 if (BaseClassDecl->isInvalidDecl())
2834 continue;
2835 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002836 if (BaseClassDecl->hasTrivialDestructor())
2837 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002838
Douglas Gregore71edda2010-07-01 22:47:18 +00002839 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002840 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002841
2842 // FIXME: caret should be on the start of the class name
2843 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002844 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002845 << Base->getType()
2846 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002847
John McCalla6309952010-03-16 21:39:52 +00002848 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002849 }
2850
2851 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002852 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2853 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002854
2855 // Bases are always records in a well-formed non-dependent class.
2856 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2857
2858 // Ignore direct virtual bases.
2859 if (DirectVirtualBases.count(RT))
2860 continue;
2861
John McCall1064d7e2010-03-16 05:22:47 +00002862 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002863 // If our base class is invalid, we probably can't get its dtor anyway.
2864 if (BaseClassDecl->isInvalidDecl())
2865 continue;
2866 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002867 if (BaseClassDecl->hasTrivialDestructor())
2868 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002869
Douglas Gregore71edda2010-07-01 22:47:18 +00002870 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002871 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002872 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002873 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002874 << VBase->getType());
2875
John McCalla6309952010-03-16 21:39:52 +00002876 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002877 }
2878}
2879
John McCall48871652010-08-21 09:40:31 +00002880void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002881 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002882 return;
Mike Stump11289f42009-09-09 15:08:12 +00002883
Mike Stump11289f42009-09-09 15:08:12 +00002884 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002885 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002886 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002887}
2888
Mike Stump11289f42009-09-09 15:08:12 +00002889bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002890 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002891 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002892 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002893 else
John McCall02db245d2010-08-18 09:41:07 +00002894 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002895}
2896
Anders Carlssoneabf7702009-08-27 00:13:57 +00002897bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002898 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002899 if (!getLangOptions().CPlusPlus)
2900 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002901
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002902 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002903 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002904
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002905 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002906 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002907 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002908 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002909
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002910 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002911 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002912 }
Mike Stump11289f42009-09-09 15:08:12 +00002913
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002914 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002915 if (!RT)
2916 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002917
John McCall67da35c2010-02-04 22:26:26 +00002918 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002919
John McCall02db245d2010-08-18 09:41:07 +00002920 // We can't answer whether something is abstract until it has a
2921 // definition. If it's currently being defined, we'll walk back
2922 // over all the declarations when we have a full definition.
2923 const CXXRecordDecl *Def = RD->getDefinition();
2924 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002925 return false;
2926
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002927 if (!RD->isAbstract())
2928 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002929
Anders Carlssoneabf7702009-08-27 00:13:57 +00002930 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002931 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002932
John McCall02db245d2010-08-18 09:41:07 +00002933 return true;
2934}
2935
2936void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2937 // Check if we've already emitted the list of pure virtual functions
2938 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002939 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002940 return;
Mike Stump11289f42009-09-09 15:08:12 +00002941
Douglas Gregor4165bd62010-03-23 23:47:56 +00002942 CXXFinalOverriderMap FinalOverriders;
2943 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002944
Anders Carlssona2f74f32010-06-03 01:00:02 +00002945 // Keep a set of seen pure methods so we won't diagnose the same method
2946 // more than once.
2947 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2948
Douglas Gregor4165bd62010-03-23 23:47:56 +00002949 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2950 MEnd = FinalOverriders.end();
2951 M != MEnd;
2952 ++M) {
2953 for (OverridingMethods::iterator SO = M->second.begin(),
2954 SOEnd = M->second.end();
2955 SO != SOEnd; ++SO) {
2956 // C++ [class.abstract]p4:
2957 // A class is abstract if it contains or inherits at least one
2958 // pure virtual function for which the final overrider is pure
2959 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002960
Douglas Gregor4165bd62010-03-23 23:47:56 +00002961 //
2962 if (SO->second.size() != 1)
2963 continue;
2964
2965 if (!SO->second.front().Method->isPure())
2966 continue;
2967
Anders Carlssona2f74f32010-06-03 01:00:02 +00002968 if (!SeenPureMethods.insert(SO->second.front().Method))
2969 continue;
2970
Douglas Gregor4165bd62010-03-23 23:47:56 +00002971 Diag(SO->second.front().Method->getLocation(),
2972 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002973 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002974 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002975 }
2976
2977 if (!PureVirtualClassDiagSet)
2978 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2979 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002980}
2981
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002982namespace {
John McCall02db245d2010-08-18 09:41:07 +00002983struct AbstractUsageInfo {
2984 Sema &S;
2985 CXXRecordDecl *Record;
2986 CanQualType AbstractType;
2987 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002988
John McCall02db245d2010-08-18 09:41:07 +00002989 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2990 : S(S), Record(Record),
2991 AbstractType(S.Context.getCanonicalType(
2992 S.Context.getTypeDeclType(Record))),
2993 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002994
John McCall02db245d2010-08-18 09:41:07 +00002995 void DiagnoseAbstractType() {
2996 if (Invalid) return;
2997 S.DiagnoseAbstractType(Record);
2998 Invalid = true;
2999 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00003000
John McCall02db245d2010-08-18 09:41:07 +00003001 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3002};
3003
3004struct CheckAbstractUsage {
3005 AbstractUsageInfo &Info;
3006 const NamedDecl *Ctx;
3007
3008 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3009 : Info(Info), Ctx(Ctx) {}
3010
3011 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3012 switch (TL.getTypeLocClass()) {
3013#define ABSTRACT_TYPELOC(CLASS, PARENT)
3014#define TYPELOC(CLASS, PARENT) \
3015 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3016#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003017 }
John McCall02db245d2010-08-18 09:41:07 +00003018 }
Mike Stump11289f42009-09-09 15:08:12 +00003019
John McCall02db245d2010-08-18 09:41:07 +00003020 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3021 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3022 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003023 if (!TL.getArg(I))
3024 continue;
3025
John McCall02db245d2010-08-18 09:41:07 +00003026 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3027 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003028 }
John McCall02db245d2010-08-18 09:41:07 +00003029 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003030
John McCall02db245d2010-08-18 09:41:07 +00003031 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3032 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3033 }
Mike Stump11289f42009-09-09 15:08:12 +00003034
John McCall02db245d2010-08-18 09:41:07 +00003035 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3036 // Visit the type parameters from a permissive context.
3037 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3038 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3039 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3040 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3041 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3042 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003043 }
John McCall02db245d2010-08-18 09:41:07 +00003044 }
Mike Stump11289f42009-09-09 15:08:12 +00003045
John McCall02db245d2010-08-18 09:41:07 +00003046 // Visit pointee types from a permissive context.
3047#define CheckPolymorphic(Type) \
3048 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3049 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3050 }
3051 CheckPolymorphic(PointerTypeLoc)
3052 CheckPolymorphic(ReferenceTypeLoc)
3053 CheckPolymorphic(MemberPointerTypeLoc)
3054 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00003055
John McCall02db245d2010-08-18 09:41:07 +00003056 /// Handle all the types we haven't given a more specific
3057 /// implementation for above.
3058 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3059 // Every other kind of type that we haven't called out already
3060 // that has an inner type is either (1) sugar or (2) contains that
3061 // inner type in some way as a subobject.
3062 if (TypeLoc Next = TL.getNextTypeLoc())
3063 return Visit(Next, Sel);
3064
3065 // If there's no inner type and we're in a permissive context,
3066 // don't diagnose.
3067 if (Sel == Sema::AbstractNone) return;
3068
3069 // Check whether the type matches the abstract type.
3070 QualType T = TL.getType();
3071 if (T->isArrayType()) {
3072 Sel = Sema::AbstractArrayType;
3073 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003074 }
John McCall02db245d2010-08-18 09:41:07 +00003075 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3076 if (CT != Info.AbstractType) return;
3077
3078 // It matched; do some magic.
3079 if (Sel == Sema::AbstractArrayType) {
3080 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3081 << T << TL.getSourceRange();
3082 } else {
3083 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3084 << Sel << T << TL.getSourceRange();
3085 }
3086 Info.DiagnoseAbstractType();
3087 }
3088};
3089
3090void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3091 Sema::AbstractDiagSelID Sel) {
3092 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3093}
3094
3095}
3096
3097/// Check for invalid uses of an abstract type in a method declaration.
3098static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3099 CXXMethodDecl *MD) {
3100 // No need to do the check on definitions, which require that
3101 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003102 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00003103 return;
3104
3105 // For safety's sake, just ignore it if we don't have type source
3106 // information. This should never happen for non-implicit methods,
3107 // but...
3108 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3109 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3110}
3111
3112/// Check for invalid uses of an abstract type within a class definition.
3113static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3114 CXXRecordDecl *RD) {
3115 for (CXXRecordDecl::decl_iterator
3116 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3117 Decl *D = *I;
3118 if (D->isImplicit()) continue;
3119
3120 // Methods and method templates.
3121 if (isa<CXXMethodDecl>(D)) {
3122 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3123 } else if (isa<FunctionTemplateDecl>(D)) {
3124 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3125 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3126
3127 // Fields and static variables.
3128 } else if (isa<FieldDecl>(D)) {
3129 FieldDecl *FD = cast<FieldDecl>(D);
3130 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3131 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3132 } else if (isa<VarDecl>(D)) {
3133 VarDecl *VD = cast<VarDecl>(D);
3134 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3135 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3136
3137 // Nested classes and class templates.
3138 } else if (isa<CXXRecordDecl>(D)) {
3139 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3140 } else if (isa<ClassTemplateDecl>(D)) {
3141 CheckAbstractClassUsage(Info,
3142 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3143 }
3144 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003145}
3146
Douglas Gregorc99f1552009-12-03 18:33:45 +00003147/// \brief Perform semantic checks on a class definition that has been
3148/// completing, introducing implicitly-declared members, checking for
3149/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003150void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003151 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003152 return;
3153
John McCall02db245d2010-08-18 09:41:07 +00003154 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3155 AbstractUsageInfo Info(*this, Record);
3156 CheckAbstractClassUsage(Info, Record);
3157 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003158
3159 // If this is not an aggregate type and has no user-declared constructor,
3160 // complain about any non-static data members of reference or const scalar
3161 // type, since they will never get initializers.
3162 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3163 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3164 bool Complained = false;
3165 for (RecordDecl::field_iterator F = Record->field_begin(),
3166 FEnd = Record->field_end();
3167 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00003168 if (F->hasInClassInitializer())
3169 continue;
3170
Douglas Gregor454a5b62010-04-15 00:00:53 +00003171 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003172 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003173 if (!Complained) {
3174 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3175 << Record->getTagKind() << Record;
3176 Complained = true;
3177 }
3178
3179 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3180 << F->getType()->isReferenceType()
3181 << F->getDeclName();
3182 }
3183 }
3184 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003185
Anders Carlssone771e762011-01-25 18:08:22 +00003186 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003187 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003188
3189 if (Record->getIdentifier()) {
3190 // C++ [class.mem]p13:
3191 // If T is the name of a class, then each of the following shall have a
3192 // name different from T:
3193 // - every member of every anonymous union that is a member of class T.
3194 //
3195 // C++ [class.mem]p14:
3196 // In addition, if class T has a user-declared constructor (12.1), every
3197 // non-static data member of class T shall have a name different from T.
3198 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003199 R.first != R.second; ++R.first) {
3200 NamedDecl *D = *R.first;
3201 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3202 isa<IndirectFieldDecl>(D)) {
3203 Diag(D->getLocation(), diag::err_member_name_of_class)
3204 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003205 break;
3206 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003207 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003208 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003209
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003210 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003211 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003212 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003213 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003214 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3215 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3216 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003217
3218 // See if a method overloads virtual methods in a base
3219 /// class without overriding any.
3220 if (!Record->isDependentType()) {
3221 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3222 MEnd = Record->method_end();
3223 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003224 if (!(*M)->isStatic())
3225 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003226 }
3227 }
Sebastian Redl08905022011-02-05 19:23:19 +00003228
3229 // Declare inherited constructors. We do this eagerly here because:
3230 // - The standard requires an eager diagnostic for conflicting inherited
3231 // constructors from different classes.
3232 // - The lazy declaration of the other implicit constructors is so as to not
3233 // waste space and performance on classes that are not meant to be
3234 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3235 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003236 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003237
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003238 if (!Record->isDependentType())
3239 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003240}
3241
3242void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003243 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3244 ME = Record->method_end();
3245 MI != ME; ++MI) {
3246 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3247 switch (getSpecialMember(*MI)) {
3248 case CXXDefaultConstructor:
3249 CheckExplicitlyDefaultedDefaultConstructor(
3250 cast<CXXConstructorDecl>(*MI));
3251 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003252
Alexis Huntf91729462011-05-12 22:46:25 +00003253 case CXXDestructor:
3254 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3255 break;
3256
3257 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003258 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3259 break;
3260
Alexis Huntf91729462011-05-12 22:46:25 +00003261 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003262 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003263 break;
3264
Alexis Hunt119c10e2011-05-25 23:16:36 +00003265 case CXXMoveConstructor:
Sebastian Redl22653ba2011-08-30 19:58:05 +00003266 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Alexis Hunt119c10e2011-05-25 23:16:36 +00003267 break;
3268
Sebastian Redl22653ba2011-08-30 19:58:05 +00003269 case CXXMoveAssignment:
3270 CheckExplicitlyDefaultedMoveAssignment(*MI);
3271 break;
3272
3273 case CXXInvalid:
Alexis Huntf91729462011-05-12 22:46:25 +00003274 llvm_unreachable("non-special member explicitly defaulted!");
3275 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003276 }
3277 }
3278
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003279}
3280
3281void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3282 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3283
3284 // Whether this was the first-declared instance of the constructor.
3285 // This affects whether we implicitly add an exception spec (and, eventually,
3286 // constexpr). It is also ill-formed to explicitly default a constructor such
3287 // that it would be deleted. (C++0x [decl.fct.def.default])
3288 bool First = CD == CD->getCanonicalDecl();
3289
Alexis Hunt913820d2011-05-13 06:10:58 +00003290 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003291 if (CD->getNumParams() != 0) {
3292 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3293 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003294 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003295 }
3296
3297 ImplicitExceptionSpecification Spec
3298 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3299 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003300 if (EPI.ExceptionSpecType == EST_Delayed) {
3301 // Exception specification depends on some deferred part of the class. We'll
3302 // try again when the class's definition has been fully processed.
3303 return;
3304 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003305 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3306 *ExceptionType = Context.getFunctionType(
3307 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3308
3309 if (CtorType->hasExceptionSpec()) {
3310 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003311 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003312 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003313 PDiag(),
3314 ExceptionType, SourceLocation(),
3315 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003316 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003317 }
3318 } else if (First) {
3319 // We set the declaration to have the computed exception spec here.
3320 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003321 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003322 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3323 }
Alexis Huntb3153022011-05-12 03:51:48 +00003324
Alexis Hunt913820d2011-05-13 06:10:58 +00003325 if (HadError) {
3326 CD->setInvalidDecl();
3327 return;
3328 }
3329
Alexis Huntb3153022011-05-12 03:51:48 +00003330 if (ShouldDeleteDefaultConstructor(CD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003331 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003332 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003333 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003334 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003335 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003336 CD->setInvalidDecl();
3337 }
3338 }
3339}
3340
3341void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3342 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3343
3344 // Whether this was the first-declared instance of the constructor.
3345 bool First = CD == CD->getCanonicalDecl();
3346
3347 bool HadError = false;
3348 if (CD->getNumParams() != 1) {
3349 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3350 << CD->getSourceRange();
3351 HadError = true;
3352 }
3353
3354 ImplicitExceptionSpecification Spec(Context);
3355 bool Const;
3356 llvm::tie(Spec, Const) =
3357 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3358
3359 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3360 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3361 *ExceptionType = Context.getFunctionType(
3362 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3363
3364 // Check for parameter type matching.
3365 // This is a copy ctor so we know it's a cv-qualified reference to T.
3366 QualType ArgType = CtorType->getArgType(0);
3367 if (ArgType->getPointeeType().isVolatileQualified()) {
3368 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3369 HadError = true;
3370 }
3371 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3372 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3373 HadError = true;
3374 }
3375
3376 if (CtorType->hasExceptionSpec()) {
3377 if (CheckEquivalentExceptionSpec(
3378 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003379 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003380 PDiag(),
3381 ExceptionType, SourceLocation(),
3382 CtorType, CD->getLocation())) {
3383 HadError = true;
3384 }
3385 } else if (First) {
3386 // We set the declaration to have the computed exception spec here.
3387 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003388 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003389 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3390 }
3391
3392 if (HadError) {
3393 CD->setInvalidDecl();
3394 return;
3395 }
3396
3397 if (ShouldDeleteCopyConstructor(CD)) {
3398 if (First) {
3399 CD->setDeletedAsWritten();
3400 } else {
3401 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003402 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003403 CD->setInvalidDecl();
3404 }
Alexis Huntb3153022011-05-12 03:51:48 +00003405 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003406}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003407
Alexis Huntc9a55732011-05-14 05:23:28 +00003408void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3409 assert(MD->isExplicitlyDefaulted());
3410
3411 // Whether this was the first-declared instance of the operator
3412 bool First = MD == MD->getCanonicalDecl();
3413
3414 bool HadError = false;
3415 if (MD->getNumParams() != 1) {
3416 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3417 << MD->getSourceRange();
3418 HadError = true;
3419 }
3420
3421 QualType ReturnType =
3422 MD->getType()->getAs<FunctionType>()->getResultType();
3423 if (!ReturnType->isLValueReferenceType() ||
3424 !Context.hasSameType(
3425 Context.getCanonicalType(ReturnType->getPointeeType()),
3426 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3427 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3428 HadError = true;
3429 }
3430
3431 ImplicitExceptionSpecification Spec(Context);
3432 bool Const;
3433 llvm::tie(Spec, Const) =
3434 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3435
3436 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3437 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3438 *ExceptionType = Context.getFunctionType(
3439 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3440
Alexis Huntc9a55732011-05-14 05:23:28 +00003441 QualType ArgType = OperType->getArgType(0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003442 if (!ArgType->isLValueReferenceType()) {
Alexis Hunt604aeb32011-05-17 20:44:43 +00003443 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003444 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003445 } else {
3446 if (ArgType->getPointeeType().isVolatileQualified()) {
3447 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3448 HadError = true;
3449 }
3450 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3451 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3452 HadError = true;
3453 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003454 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003455
Alexis Huntc9a55732011-05-14 05:23:28 +00003456 if (OperType->getTypeQuals()) {
3457 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3458 HadError = true;
3459 }
3460
3461 if (OperType->hasExceptionSpec()) {
3462 if (CheckEquivalentExceptionSpec(
3463 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003464 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003465 PDiag(),
3466 ExceptionType, SourceLocation(),
3467 OperType, MD->getLocation())) {
3468 HadError = true;
3469 }
3470 } else if (First) {
3471 // We set the declaration to have the computed exception spec here.
3472 // We duplicate the one parameter type.
3473 EPI.RefQualifier = OperType->getRefQualifier();
3474 EPI.ExtInfo = OperType->getExtInfo();
3475 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3476 }
3477
3478 if (HadError) {
3479 MD->setInvalidDecl();
3480 return;
3481 }
3482
3483 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3484 if (First) {
3485 MD->setDeletedAsWritten();
3486 } else {
3487 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003488 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003489 MD->setInvalidDecl();
3490 }
3491 }
3492}
3493
Sebastian Redl22653ba2011-08-30 19:58:05 +00003494void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3495 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3496
3497 // Whether this was the first-declared instance of the constructor.
3498 bool First = CD == CD->getCanonicalDecl();
3499
3500 bool HadError = false;
3501 if (CD->getNumParams() != 1) {
3502 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3503 << CD->getSourceRange();
3504 HadError = true;
3505 }
3506
3507 ImplicitExceptionSpecification Spec(
3508 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3509
3510 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3511 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3512 *ExceptionType = Context.getFunctionType(
3513 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3514
3515 // Check for parameter type matching.
3516 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3517 QualType ArgType = CtorType->getArgType(0);
3518 if (ArgType->getPointeeType().isVolatileQualified()) {
3519 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3520 HadError = true;
3521 }
3522 if (ArgType->getPointeeType().isConstQualified()) {
3523 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3524 HadError = true;
3525 }
3526
3527 if (CtorType->hasExceptionSpec()) {
3528 if (CheckEquivalentExceptionSpec(
3529 PDiag(diag::err_incorrect_defaulted_exception_spec)
3530 << CXXMoveConstructor,
3531 PDiag(),
3532 ExceptionType, SourceLocation(),
3533 CtorType, CD->getLocation())) {
3534 HadError = true;
3535 }
3536 } else if (First) {
3537 // We set the declaration to have the computed exception spec here.
3538 // We duplicate the one parameter type.
3539 EPI.ExtInfo = CtorType->getExtInfo();
3540 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3541 }
3542
3543 if (HadError) {
3544 CD->setInvalidDecl();
3545 return;
3546 }
3547
3548 if (ShouldDeleteMoveConstructor(CD)) {
3549 if (First) {
3550 CD->setDeletedAsWritten();
3551 } else {
3552 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3553 << CXXMoveConstructor;
3554 CD->setInvalidDecl();
3555 }
3556 }
3557}
3558
3559void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3560 assert(MD->isExplicitlyDefaulted());
3561
3562 // Whether this was the first-declared instance of the operator
3563 bool First = MD == MD->getCanonicalDecl();
3564
3565 bool HadError = false;
3566 if (MD->getNumParams() != 1) {
3567 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3568 << MD->getSourceRange();
3569 HadError = true;
3570 }
3571
3572 QualType ReturnType =
3573 MD->getType()->getAs<FunctionType>()->getResultType();
3574 if (!ReturnType->isLValueReferenceType() ||
3575 !Context.hasSameType(
3576 Context.getCanonicalType(ReturnType->getPointeeType()),
3577 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3578 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3579 HadError = true;
3580 }
3581
3582 ImplicitExceptionSpecification Spec(
3583 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3584
3585 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3586 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3587 *ExceptionType = Context.getFunctionType(
3588 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3589
3590 QualType ArgType = OperType->getArgType(0);
3591 if (!ArgType->isRValueReferenceType()) {
3592 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3593 HadError = true;
3594 } else {
3595 if (ArgType->getPointeeType().isVolatileQualified()) {
3596 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3597 HadError = true;
3598 }
3599 if (ArgType->getPointeeType().isConstQualified()) {
3600 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3601 HadError = true;
3602 }
3603 }
3604
3605 if (OperType->getTypeQuals()) {
3606 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3607 HadError = true;
3608 }
3609
3610 if (OperType->hasExceptionSpec()) {
3611 if (CheckEquivalentExceptionSpec(
3612 PDiag(diag::err_incorrect_defaulted_exception_spec)
3613 << CXXMoveAssignment,
3614 PDiag(),
3615 ExceptionType, SourceLocation(),
3616 OperType, MD->getLocation())) {
3617 HadError = true;
3618 }
3619 } else if (First) {
3620 // We set the declaration to have the computed exception spec here.
3621 // We duplicate the one parameter type.
3622 EPI.RefQualifier = OperType->getRefQualifier();
3623 EPI.ExtInfo = OperType->getExtInfo();
3624 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3625 }
3626
3627 if (HadError) {
3628 MD->setInvalidDecl();
3629 return;
3630 }
3631
3632 if (ShouldDeleteMoveAssignmentOperator(MD)) {
3633 if (First) {
3634 MD->setDeletedAsWritten();
3635 } else {
3636 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3637 << CXXMoveAssignment;
3638 MD->setInvalidDecl();
3639 }
3640 }
3641}
3642
Alexis Huntf91729462011-05-12 22:46:25 +00003643void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3644 assert(DD->isExplicitlyDefaulted());
3645
3646 // Whether this was the first-declared instance of the destructor.
3647 bool First = DD == DD->getCanonicalDecl();
3648
3649 ImplicitExceptionSpecification Spec
3650 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3651 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3652 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3653 *ExceptionType = Context.getFunctionType(
3654 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3655
3656 if (DtorType->hasExceptionSpec()) {
3657 if (CheckEquivalentExceptionSpec(
3658 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003659 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00003660 PDiag(),
3661 ExceptionType, SourceLocation(),
3662 DtorType, DD->getLocation())) {
3663 DD->setInvalidDecl();
3664 return;
3665 }
3666 } else if (First) {
3667 // We set the declaration to have the computed exception spec here.
3668 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003669 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00003670 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3671 }
3672
3673 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003674 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00003675 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003676 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00003677 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003678 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003679 DD->setInvalidDecl();
3680 }
Alexis Huntf91729462011-05-12 22:46:25 +00003681 }
Alexis Huntf91729462011-05-12 22:46:25 +00003682}
3683
Alexis Huntea6f0322011-05-11 22:34:38 +00003684bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3685 CXXRecordDecl *RD = CD->getParent();
3686 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00003687 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00003688 return false;
3689
Alexis Hunte77a28f2011-05-18 03:41:58 +00003690 SourceLocation Loc = CD->getLocation();
3691
Alexis Huntea6f0322011-05-11 22:34:38 +00003692 // Do access control from the constructor
3693 ContextRAII CtorContext(*this, CD);
3694
3695 bool Union = RD->isUnion();
3696 bool AllConst = true;
3697
Alexis Huntea6f0322011-05-11 22:34:38 +00003698 // We do this because we should never actually use an anonymous
3699 // union's constructor.
3700 if (Union && RD->isAnonymousStructOrUnion())
3701 return false;
3702
3703 // FIXME: We should put some diagnostic logic right into this function.
3704
3705 // C++0x [class.ctor]/5
Alexis Hunteef8ee02011-06-10 03:50:41 +00003706 // A defaulted default constructor for class X is defined as deleted if:
Alexis Huntea6f0322011-05-11 22:34:38 +00003707
3708 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3709 BE = RD->bases_end();
3710 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00003711 // We'll handle this one later
3712 if (BI->isVirtual())
3713 continue;
3714
Alexis Huntea6f0322011-05-11 22:34:38 +00003715 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3716 assert(BaseDecl && "base isn't a CXXRecordDecl");
3717
3718 // -- any [direct base class] has a type with a destructor that is
Alexis Hunteef8ee02011-06-10 03:50:41 +00003719 // deleted or inaccessible from the defaulted default constructor
Alexis Huntea6f0322011-05-11 22:34:38 +00003720 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3721 if (BaseDtor->isDeleted())
3722 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003723 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003724 AR_accessible)
3725 return true;
3726
Alexis Huntea6f0322011-05-11 22:34:38 +00003727 // -- any [direct base class either] has no default constructor or
3728 // overload resolution as applied to [its] default constructor
3729 // results in an ambiguity or in a function that is deleted or
3730 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003731 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3732 if (!BaseDefault || BaseDefault->isDeleted())
3733 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003734
Alexis Hunteef8ee02011-06-10 03:50:41 +00003735 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3736 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003737 return true;
3738 }
3739
3740 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3741 BE = RD->vbases_end();
3742 BI != BE; ++BI) {
3743 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3744 assert(BaseDecl && "base isn't a CXXRecordDecl");
3745
3746 // -- any [virtual base class] has a type with a destructor that is
3747 // delete or inaccessible from the defaulted default constructor
3748 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3749 if (BaseDtor->isDeleted())
3750 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003751 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003752 AR_accessible)
3753 return true;
3754
3755 // -- any [virtual base class either] has no default constructor or
3756 // overload resolution as applied to [its] default constructor
3757 // results in an ambiguity or in a function that is deleted or
3758 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003759 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3760 if (!BaseDefault || BaseDefault->isDeleted())
3761 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003762
Alexis Hunteef8ee02011-06-10 03:50:41 +00003763 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3764 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003765 return true;
3766 }
3767
3768 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3769 FE = RD->field_end();
3770 FI != FE; ++FI) {
Richard Smith938f40b2011-06-11 17:19:42 +00003771 if (FI->isInvalidDecl())
3772 continue;
3773
Alexis Huntea6f0322011-05-11 22:34:38 +00003774 QualType FieldType = Context.getBaseElementType(FI->getType());
3775 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00003776
Alexis Huntea6f0322011-05-11 22:34:38 +00003777 // -- any non-static data member with no brace-or-equal-initializer is of
3778 // reference type
Richard Smith938f40b2011-06-11 17:19:42 +00003779 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Alexis Huntea6f0322011-05-11 22:34:38 +00003780 return true;
3781
3782 // -- X is a union and all its variant members are of const-qualified type
3783 // (or array thereof)
3784 if (Union && !FieldType.isConstQualified())
3785 AllConst = false;
3786
3787 if (FieldRecord) {
3788 // -- X is a union-like class that has a variant member with a non-trivial
3789 // default constructor
3790 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3791 return true;
3792
3793 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3794 if (FieldDtor->isDeleted())
3795 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003796 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003797 AR_accessible)
3798 return true;
3799
3800 // -- any non-variant non-static data member of const-qualified type (or
3801 // array thereof) with no brace-or-equal-initializer does not have a
3802 // user-provided default constructor
3803 if (FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003804 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00003805 !FieldRecord->hasUserProvidedDefaultConstructor())
3806 return true;
3807
3808 if (!Union && FieldRecord->isUnion() &&
3809 FieldRecord->isAnonymousStructOrUnion()) {
3810 // We're okay to reuse AllConst here since we only care about the
3811 // value otherwise if we're in a union.
3812 AllConst = true;
3813
3814 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3815 UE = FieldRecord->field_end();
3816 UI != UE; ++UI) {
3817 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3818 CXXRecordDecl *UnionFieldRecord =
3819 UnionFieldType->getAsCXXRecordDecl();
3820
3821 if (!UnionFieldType.isConstQualified())
3822 AllConst = false;
3823
3824 if (UnionFieldRecord &&
3825 !UnionFieldRecord->hasTrivialDefaultConstructor())
3826 return true;
3827 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00003828
Alexis Huntea6f0322011-05-11 22:34:38 +00003829 if (AllConst)
3830 return true;
3831
3832 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00003833 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00003834 continue;
3835 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00003836
Richard Smith938f40b2011-06-11 17:19:42 +00003837 // -- any non-static data member with no brace-or-equal-initializer has
3838 // class type M (or array thereof) and either M has no default
3839 // constructor or overload resolution as applied to M's default
3840 // constructor results in an ambiguity or in a function that is deleted
3841 // or inaccessible from the defaulted default constructor.
3842 if (!FI->hasInClassInitializer()) {
3843 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3844 if (!FieldDefault || FieldDefault->isDeleted())
3845 return true;
3846 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3847 PDiag()) != AR_accessible)
3848 return true;
3849 }
3850 } else if (!Union && FieldType.isConstQualified() &&
3851 !FI->hasInClassInitializer()) {
Alexis Hunta671bca2011-05-20 21:43:47 +00003852 // -- any non-variant non-static data member of const-qualified type (or
3853 // array thereof) with no brace-or-equal-initializer does not have a
3854 // user-provided default constructor
3855 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003856 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003857 }
3858
3859 if (Union && AllConst)
3860 return true;
3861
3862 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003863}
3864
Alexis Hunt913820d2011-05-13 06:10:58 +00003865bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00003866 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00003867 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00003868 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Hunt913820d2011-05-13 06:10:58 +00003869 return false;
3870
Alexis Hunte77a28f2011-05-18 03:41:58 +00003871 SourceLocation Loc = CD->getLocation();
3872
Alexis Hunt913820d2011-05-13 06:10:58 +00003873 // Do access control from the constructor
3874 ContextRAII CtorContext(*this, CD);
3875
Alexis Hunt899bd442011-06-10 04:44:37 +00003876 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00003877
Alexis Huntc9a55732011-05-14 05:23:28 +00003878 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3879 "copy assignment arg has no pointee type");
Alexis Hunt899bd442011-06-10 04:44:37 +00003880 unsigned ArgQuals =
3881 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3882 Qualifiers::Const : 0;
Alexis Hunt913820d2011-05-13 06:10:58 +00003883
3884 // We do this because we should never actually use an anonymous
3885 // union's constructor.
3886 if (Union && RD->isAnonymousStructOrUnion())
3887 return false;
3888
3889 // FIXME: We should put some diagnostic logic right into this function.
3890
3891 // C++0x [class.copy]/11
3892 // A defaulted [copy] constructor for class X is defined as delete if X has:
3893
3894 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3895 BE = RD->bases_end();
3896 BI != BE; ++BI) {
3897 // We'll handle this one later
3898 if (BI->isVirtual())
3899 continue;
3900
3901 QualType BaseType = BI->getType();
3902 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3903 assert(BaseDecl && "base isn't a CXXRecordDecl");
3904
3905 // -- any [direct base class] of a type with a destructor that is deleted or
3906 // inaccessible from the defaulted constructor
3907 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3908 if (BaseDtor->isDeleted())
3909 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003910 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003911 AR_accessible)
3912 return true;
3913
3914 // -- a [direct base class] B that cannot be [copied] because overload
3915 // resolution, as applied to B's [copy] constructor, results in an
3916 // ambiguity or a function that is deleted or inaccessible from the
3917 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003918 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003919 if (!BaseCtor || BaseCtor->isDeleted())
3920 return true;
3921 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3922 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003923 return true;
3924 }
3925
3926 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3927 BE = RD->vbases_end();
3928 BI != BE; ++BI) {
3929 QualType BaseType = BI->getType();
3930 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3931 assert(BaseDecl && "base isn't a CXXRecordDecl");
3932
Alexis Hunteef8ee02011-06-10 03:50:41 +00003933 // -- any [virtual base class] of a type with a destructor that is deleted or
Alexis Hunt913820d2011-05-13 06:10:58 +00003934 // inaccessible from the defaulted constructor
3935 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3936 if (BaseDtor->isDeleted())
3937 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003938 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003939 AR_accessible)
3940 return true;
3941
3942 // -- a [virtual base class] B that cannot be [copied] because overload
3943 // resolution, as applied to B's [copy] constructor, results in an
3944 // ambiguity or a function that is deleted or inaccessible from the
3945 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003946 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003947 if (!BaseCtor || BaseCtor->isDeleted())
3948 return true;
3949 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3950 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003951 return true;
3952 }
3953
3954 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3955 FE = RD->field_end();
3956 FI != FE; ++FI) {
3957 QualType FieldType = Context.getBaseElementType(FI->getType());
3958
3959 // -- for a copy constructor, a non-static data member of rvalue reference
3960 // type
3961 if (FieldType->isRValueReferenceType())
3962 return true;
3963
3964 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3965
3966 if (FieldRecord) {
3967 // This is an anonymous union
3968 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3969 // Anonymous unions inside unions do not variant members create
3970 if (!Union) {
3971 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3972 UE = FieldRecord->field_end();
3973 UI != UE; ++UI) {
3974 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3975 CXXRecordDecl *UnionFieldRecord =
3976 UnionFieldType->getAsCXXRecordDecl();
3977
3978 // -- a variant member with a non-trivial [copy] constructor and X
3979 // is a union-like class
3980 if (UnionFieldRecord &&
3981 !UnionFieldRecord->hasTrivialCopyConstructor())
3982 return true;
3983 }
3984 }
3985
3986 // Don't try to initalize an anonymous union
3987 continue;
3988 } else {
3989 // -- a variant member with a non-trivial [copy] constructor and X is a
3990 // union-like class
3991 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3992 return true;
3993
3994 // -- any [non-static data member] of a type with a destructor that is
3995 // deleted or inaccessible from the defaulted constructor
3996 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3997 if (FieldDtor->isDeleted())
3998 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003999 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00004000 AR_accessible)
4001 return true;
4002 }
Alexis Hunt899bd442011-06-10 04:44:37 +00004003
4004 // -- a [non-static data member of class type (or array thereof)] B that
4005 // cannot be [copied] because overload resolution, as applied to B's
4006 // [copy] constructor, results in an ambiguity or a function that is
4007 // deleted or inaccessible from the defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00004008 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
4009 ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00004010 if (!FieldCtor || FieldCtor->isDeleted())
4011 return true;
4012 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4013 PDiag()) != AR_accessible)
4014 return true;
Alexis Hunt913820d2011-05-13 06:10:58 +00004015 }
Alexis Hunt913820d2011-05-13 06:10:58 +00004016 }
4017
4018 return false;
4019}
4020
Alexis Huntb2f27802011-05-14 05:23:24 +00004021bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4022 CXXRecordDecl *RD = MD->getParent();
4023 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004024 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntb2f27802011-05-14 05:23:24 +00004025 return false;
4026
Alexis Hunte77a28f2011-05-18 03:41:58 +00004027 SourceLocation Loc = MD->getLocation();
4028
Alexis Huntb2f27802011-05-14 05:23:24 +00004029 // Do access control from the constructor
4030 ContextRAII MethodContext(*this, MD);
4031
4032 bool Union = RD->isUnion();
4033
Alexis Hunt491ec602011-06-21 23:42:56 +00004034 unsigned ArgQuals =
4035 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4036 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00004037
4038 // We do this because we should never actually use an anonymous
4039 // union's constructor.
4040 if (Union && RD->isAnonymousStructOrUnion())
4041 return false;
4042
Alexis Huntb2f27802011-05-14 05:23:24 +00004043 // FIXME: We should put some diagnostic logic right into this function.
4044
Sebastian Redl22653ba2011-08-30 19:58:05 +00004045 // C++0x [class.copy]/20
Alexis Huntb2f27802011-05-14 05:23:24 +00004046 // A defaulted [copy] assignment operator for class X is defined as deleted
4047 // if X has:
4048
4049 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4050 BE = RD->bases_end();
4051 BI != BE; ++BI) {
4052 // We'll handle this one later
4053 if (BI->isVirtual())
4054 continue;
4055
4056 QualType BaseType = BI->getType();
4057 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4058 assert(BaseDecl && "base isn't a CXXRecordDecl");
4059
4060 // -- a [direct base class] B that cannot be [copied] because overload
4061 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00004062 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00004063 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004064 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4065 0);
4066 if (!CopyOper || CopyOper->isDeleted())
4067 return true;
4068 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004069 return true;
4070 }
4071
4072 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4073 BE = RD->vbases_end();
4074 BI != BE; ++BI) {
4075 QualType BaseType = BI->getType();
4076 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4077 assert(BaseDecl && "base isn't a CXXRecordDecl");
4078
Alexis Huntb2f27802011-05-14 05:23:24 +00004079 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00004080 // resolution, as applied to B's [copy] assignment operator, results in
4081 // an ambiguity or a function that is deleted or inaccessible from the
4082 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004083 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4084 0);
4085 if (!CopyOper || CopyOper->isDeleted())
4086 return true;
4087 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004088 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00004089 }
4090
4091 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4092 FE = RD->field_end();
4093 FI != FE; ++FI) {
4094 QualType FieldType = Context.getBaseElementType(FI->getType());
4095
4096 // -- a non-static data member of reference type
4097 if (FieldType->isReferenceType())
4098 return true;
4099
4100 // -- a non-static data member of const non-class type (or array thereof)
4101 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4102 return true;
4103
4104 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4105
4106 if (FieldRecord) {
4107 // This is an anonymous union
4108 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4109 // Anonymous unions inside unions do not variant members create
4110 if (!Union) {
4111 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4112 UE = FieldRecord->field_end();
4113 UI != UE; ++UI) {
4114 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4115 CXXRecordDecl *UnionFieldRecord =
4116 UnionFieldType->getAsCXXRecordDecl();
4117
4118 // -- a variant member with a non-trivial [copy] assignment operator
4119 // and X is a union-like class
4120 if (UnionFieldRecord &&
4121 !UnionFieldRecord->hasTrivialCopyAssignment())
4122 return true;
4123 }
4124 }
4125
4126 // Don't try to initalize an anonymous union
4127 continue;
4128 // -- a variant member with a non-trivial [copy] assignment operator
4129 // and X is a union-like class
4130 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4131 return true;
4132 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004133
Alexis Hunt491ec602011-06-21 23:42:56 +00004134 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4135 false, 0);
4136 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl22653ba2011-08-30 19:58:05 +00004137 return true;
Alexis Hunt491ec602011-06-21 23:42:56 +00004138 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl22653ba2011-08-30 19:58:05 +00004139 return true;
4140 }
4141 }
4142
4143 return false;
4144}
4145
4146bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4147 CXXRecordDecl *RD = CD->getParent();
4148 assert(!RD->isDependentType() && "do deletion after instantiation");
4149 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4150 return false;
4151
4152 SourceLocation Loc = CD->getLocation();
4153
4154 // Do access control from the constructor
4155 ContextRAII CtorContext(*this, CD);
4156
4157 bool Union = RD->isUnion();
4158
4159 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4160 "copy assignment arg has no pointee type");
4161
4162 // We do this because we should never actually use an anonymous
4163 // union's constructor.
4164 if (Union && RD->isAnonymousStructOrUnion())
4165 return false;
4166
4167 // C++0x [class.copy]/11
4168 // A defaulted [move] constructor for class X is defined as deleted
4169 // if X has:
4170
4171 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4172 BE = RD->bases_end();
4173 BI != BE; ++BI) {
4174 // We'll handle this one later
4175 if (BI->isVirtual())
4176 continue;
4177
4178 QualType BaseType = BI->getType();
4179 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4180 assert(BaseDecl && "base isn't a CXXRecordDecl");
4181
4182 // -- any [direct base class] of a type with a destructor that is deleted or
4183 // inaccessible from the defaulted constructor
4184 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4185 if (BaseDtor->isDeleted())
4186 return true;
4187 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4188 AR_accessible)
4189 return true;
4190
4191 // -- a [direct base class] B that cannot be [moved] because overload
4192 // resolution, as applied to B's [move] constructor, results in an
4193 // ambiguity or a function that is deleted or inaccessible from the
4194 // defaulted constructor
4195 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4196 if (!BaseCtor || BaseCtor->isDeleted())
4197 return true;
4198 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4199 AR_accessible)
4200 return true;
4201
4202 // -- for a move constructor, a [direct base class] with a type that
4203 // does not have a move constructor and is not trivially copyable.
4204 // If the field isn't a record, it's always trivially copyable.
4205 // A moving constructor could be a copy constructor instead.
4206 if (!BaseCtor->isMoveConstructor() &&
4207 !BaseDecl->isTriviallyCopyable())
4208 return true;
4209 }
4210
4211 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4212 BE = RD->vbases_end();
4213 BI != BE; ++BI) {
4214 QualType BaseType = BI->getType();
4215 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4216 assert(BaseDecl && "base isn't a CXXRecordDecl");
4217
4218 // -- any [virtual base class] of a type with a destructor that is deleted
4219 // or inaccessible from the defaulted constructor
4220 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4221 if (BaseDtor->isDeleted())
4222 return true;
4223 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4224 AR_accessible)
4225 return true;
4226
4227 // -- a [virtual base class] B that cannot be [moved] because overload
4228 // resolution, as applied to B's [move] constructor, results in an
4229 // ambiguity or a function that is deleted or inaccessible from the
4230 // defaulted constructor
4231 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4232 if (!BaseCtor || BaseCtor->isDeleted())
4233 return true;
4234 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4235 AR_accessible)
4236 return true;
4237
4238 // -- for a move constructor, a [virtual base class] with a type that
4239 // does not have a move constructor and is not trivially copyable.
4240 // If the field isn't a record, it's always trivially copyable.
4241 // A moving constructor could be a copy constructor instead.
4242 if (!BaseCtor->isMoveConstructor() &&
4243 !BaseDecl->isTriviallyCopyable())
4244 return true;
4245 }
4246
4247 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4248 FE = RD->field_end();
4249 FI != FE; ++FI) {
4250 QualType FieldType = Context.getBaseElementType(FI->getType());
4251
4252 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4253 // This is an anonymous union
4254 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4255 // Anonymous unions inside unions do not variant members create
4256 if (!Union) {
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 // -- a variant member with a non-trivial [move] constructor and X
4265 // is a union-like class
4266 if (UnionFieldRecord &&
4267 !UnionFieldRecord->hasTrivialMoveConstructor())
4268 return true;
4269 }
4270 }
4271
4272 // Don't try to initalize an anonymous union
4273 continue;
4274 } else {
4275 // -- a variant member with a non-trivial [move] constructor and X is a
4276 // union-like class
4277 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4278 return true;
4279
4280 // -- any [non-static data member] of a type with a destructor that is
4281 // deleted or inaccessible from the defaulted constructor
4282 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4283 if (FieldDtor->isDeleted())
4284 return true;
4285 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4286 AR_accessible)
4287 return true;
4288 }
4289
4290 // -- a [non-static data member of class type (or array thereof)] B that
4291 // cannot be [moved] because overload resolution, as applied to B's
4292 // [move] constructor, results in an ambiguity or a function that is
4293 // deleted or inaccessible from the defaulted constructor
4294 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4295 if (!FieldCtor || FieldCtor->isDeleted())
4296 return true;
4297 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4298 PDiag()) != AR_accessible)
4299 return true;
4300
4301 // -- for a move constructor, a [non-static data member] with a type that
4302 // does not have a move constructor and is not trivially copyable.
4303 // If the field isn't a record, it's always trivially copyable.
4304 // A moving constructor could be a copy constructor instead.
4305 if (!FieldCtor->isMoveConstructor() &&
4306 !FieldRecord->isTriviallyCopyable())
4307 return true;
4308 }
4309 }
4310
4311 return false;
4312}
4313
4314bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4315 CXXRecordDecl *RD = MD->getParent();
4316 assert(!RD->isDependentType() && "do deletion after instantiation");
4317 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4318 return false;
4319
4320 SourceLocation Loc = MD->getLocation();
4321
4322 // Do access control from the constructor
4323 ContextRAII MethodContext(*this, MD);
4324
4325 bool Union = RD->isUnion();
4326
4327 // We do this because we should never actually use an anonymous
4328 // union's constructor.
4329 if (Union && RD->isAnonymousStructOrUnion())
4330 return false;
4331
4332 // C++0x [class.copy]/20
4333 // A defaulted [move] assignment operator for class X is defined as deleted
4334 // if X has:
4335
4336 // -- for the move constructor, [...] any direct or indirect virtual base
4337 // class.
4338 if (RD->getNumVBases() != 0)
4339 return true;
4340
4341 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4342 BE = RD->bases_end();
4343 BI != BE; ++BI) {
4344
4345 QualType BaseType = BI->getType();
4346 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4347 assert(BaseDecl && "base isn't a CXXRecordDecl");
4348
4349 // -- a [direct base class] B that cannot be [moved] because overload
4350 // resolution, as applied to B's [move] assignment operator, results in
4351 // an ambiguity or a function that is deleted or inaccessible from the
4352 // assignment operator
4353 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4354 if (!MoveOper || MoveOper->isDeleted())
4355 return true;
4356 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4357 return true;
4358
4359 // -- for the move assignment operator, a [direct base class] with a type
4360 // that does not have a move assignment operator and is not trivially
4361 // copyable.
4362 if (!MoveOper->isMoveAssignmentOperator() &&
4363 !BaseDecl->isTriviallyCopyable())
4364 return true;
4365 }
4366
4367 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4368 FE = RD->field_end();
4369 FI != FE; ++FI) {
4370 QualType FieldType = Context.getBaseElementType(FI->getType());
4371
4372 // -- a non-static data member of reference type
4373 if (FieldType->isReferenceType())
4374 return true;
4375
4376 // -- a non-static data member of const non-class type (or array thereof)
4377 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4378 return true;
4379
4380 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4381
4382 if (FieldRecord) {
4383 // This is an anonymous union
4384 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4385 // Anonymous unions inside unions do not variant members create
4386 if (!Union) {
4387 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4388 UE = FieldRecord->field_end();
4389 UI != UE; ++UI) {
4390 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4391 CXXRecordDecl *UnionFieldRecord =
4392 UnionFieldType->getAsCXXRecordDecl();
4393
4394 // -- a variant member with a non-trivial [move] assignment operator
4395 // and X is a union-like class
4396 if (UnionFieldRecord &&
4397 !UnionFieldRecord->hasTrivialMoveAssignment())
4398 return true;
4399 }
4400 }
4401
4402 // Don't try to initalize an anonymous union
4403 continue;
4404 // -- a variant member with a non-trivial [move] assignment operator
4405 // and X is a union-like class
4406 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4407 return true;
4408 }
4409
4410 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4411 if (!MoveOper || MoveOper->isDeleted())
4412 return true;
4413 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4414 return true;
4415
4416 // -- for the move assignment operator, a [non-static data member] with a
4417 // type that does not have a move assignment operator and is not
4418 // trivially copyable.
4419 if (!MoveOper->isMoveAssignmentOperator() &&
4420 !FieldRecord->isTriviallyCopyable())
4421 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004422 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004423 }
4424
4425 return false;
4426}
4427
Alexis Huntf91729462011-05-12 22:46:25 +00004428bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4429 CXXRecordDecl *RD = DD->getParent();
4430 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004431 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntf91729462011-05-12 22:46:25 +00004432 return false;
4433
Alexis Hunte77a28f2011-05-18 03:41:58 +00004434 SourceLocation Loc = DD->getLocation();
4435
Alexis Huntf91729462011-05-12 22:46:25 +00004436 // Do access control from the destructor
4437 ContextRAII CtorContext(*this, DD);
4438
4439 bool Union = RD->isUnion();
4440
Alexis Hunt913820d2011-05-13 06:10:58 +00004441 // We do this because we should never actually use an anonymous
4442 // union's destructor.
4443 if (Union && RD->isAnonymousStructOrUnion())
4444 return false;
4445
Alexis Huntf91729462011-05-12 22:46:25 +00004446 // C++0x [class.dtor]p5
4447 // A defaulted destructor for a class X is defined as deleted if:
4448 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4449 BE = RD->bases_end();
4450 BI != BE; ++BI) {
4451 // We'll handle this one later
4452 if (BI->isVirtual())
4453 continue;
4454
4455 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4456 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4457 assert(BaseDtor && "base has no destructor");
4458
4459 // -- any direct or virtual base class has a deleted destructor or
4460 // a destructor that is inaccessible from the defaulted destructor
4461 if (BaseDtor->isDeleted())
4462 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004463 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004464 AR_accessible)
4465 return true;
4466 }
4467
4468 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4469 BE = RD->vbases_end();
4470 BI != BE; ++BI) {
4471 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4472 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4473 assert(BaseDtor && "base has no destructor");
4474
4475 // -- any direct or virtual base class has a deleted destructor or
4476 // a destructor that is inaccessible from the defaulted destructor
4477 if (BaseDtor->isDeleted())
4478 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004479 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004480 AR_accessible)
4481 return true;
4482 }
4483
4484 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4485 FE = RD->field_end();
4486 FI != FE; ++FI) {
4487 QualType FieldType = Context.getBaseElementType(FI->getType());
4488 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4489 if (FieldRecord) {
4490 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4491 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4492 UE = FieldRecord->field_end();
4493 UI != UE; ++UI) {
4494 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4495 CXXRecordDecl *UnionFieldRecord =
4496 UnionFieldType->getAsCXXRecordDecl();
4497
4498 // -- X is a union-like class that has a variant member with a non-
4499 // trivial destructor.
4500 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4501 return true;
4502 }
4503 // Technically we are supposed to do this next check unconditionally.
4504 // But that makes absolutely no sense.
4505 } else {
4506 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4507
4508 // -- any of the non-static data members has class type M (or array
4509 // thereof) and M has a deleted destructor or a destructor that is
4510 // inaccessible from the defaulted destructor
4511 if (FieldDtor->isDeleted())
4512 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004513 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004514 AR_accessible)
4515 return true;
4516
4517 // -- X is a union-like class that has a variant member with a non-
4518 // trivial destructor.
4519 if (Union && !FieldDtor->isTrivial())
4520 return true;
4521 }
4522 }
4523 }
4524
4525 if (DD->isVirtual()) {
4526 FunctionDecl *OperatorDelete = 0;
4527 DeclarationName Name =
4528 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004529 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004530 false))
4531 return true;
4532 }
4533
4534
4535 return false;
4536}
4537
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004538/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004539namespace {
4540 struct FindHiddenVirtualMethodData {
4541 Sema *S;
4542 CXXMethodDecl *Method;
4543 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004544 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00004545 };
4546}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004547
4548/// \brief Member lookup function that determines whether a given C++
4549/// method overloads virtual methods in a base class without overriding any,
4550/// to be used with CXXRecordDecl::lookupInBases().
4551static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4552 CXXBasePath &Path,
4553 void *UserData) {
4554 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4555
4556 FindHiddenVirtualMethodData &Data
4557 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4558
4559 DeclarationName Name = Data.Method->getDeclName();
4560 assert(Name.getNameKind() == DeclarationName::Identifier);
4561
4562 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004563 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004564 for (Path.Decls = BaseRecord->lookup(Name);
4565 Path.Decls.first != Path.Decls.second;
4566 ++Path.Decls.first) {
4567 NamedDecl *D = *Path.Decls.first;
4568 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004569 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004570 foundSameNameMethod = true;
4571 // Interested only in hidden virtual methods.
4572 if (!MD->isVirtual())
4573 continue;
4574 // If the method we are checking overrides a method from its base
4575 // don't warn about the other overloaded methods.
4576 if (!Data.S->IsOverload(Data.Method, MD, false))
4577 return true;
4578 // Collect the overload only if its hidden.
4579 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4580 overloadedMethods.push_back(MD);
4581 }
4582 }
4583
4584 if (foundSameNameMethod)
4585 Data.OverloadedMethods.append(overloadedMethods.begin(),
4586 overloadedMethods.end());
4587 return foundSameNameMethod;
4588}
4589
4590/// \brief See if a method overloads virtual methods in a base class without
4591/// overriding any.
4592void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4593 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikie9c902b52011-09-25 23:23:43 +00004594 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004595 return;
4596 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4597 return;
4598
4599 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4600 /*bool RecordPaths=*/false,
4601 /*bool DetectVirtual=*/false);
4602 FindHiddenVirtualMethodData Data;
4603 Data.Method = MD;
4604 Data.S = this;
4605
4606 // Keep the base methods that were overriden or introduced in the subclass
4607 // by 'using' in a set. A base method not in this set is hidden.
4608 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4609 res.first != res.second; ++res.first) {
4610 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4611 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4612 E = MD->end_overridden_methods();
4613 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004614 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004615 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4616 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004617 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004618 }
4619
4620 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4621 !Data.OverloadedMethods.empty()) {
4622 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4623 << MD << (Data.OverloadedMethods.size() > 1);
4624
4625 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4626 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4627 Diag(overloadedMD->getLocation(),
4628 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4629 }
4630 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00004631}
4632
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004633void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00004634 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004635 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004636 SourceLocation RBrac,
4637 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004638 if (!TagDecl)
4639 return;
Mike Stump11289f42009-09-09 15:08:12 +00004640
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004641 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00004642
David Blaikie751c5582011-09-22 02:58:26 +00004643 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00004644 // strict aliasing violation!
4645 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00004646 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00004647
Douglas Gregor0be31a22010-07-02 17:43:08 +00004648 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00004649 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004650}
4651
Douglas Gregor05379422008-11-03 17:51:48 +00004652/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4653/// special functions, such as the default constructor, copy
4654/// constructor, or destructor, to the given C++ class (C++
4655/// [special]p1). This routine can only be executed just before the
4656/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004657void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004658 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00004659 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004660
Douglas Gregor54be3392010-07-01 17:57:27 +00004661 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00004662 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004663
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004664 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4665 ++ASTContext::NumImplicitCopyAssignmentOperators;
4666
4667 // If we have a dynamic class, then the copy assignment operator may be
4668 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4669 // it shows up in the right place in the vtable and that we diagnose
4670 // problems with the implicit exception specification.
4671 if (ClassDecl->isDynamicClass())
4672 DeclareImplicitCopyAssignment(ClassDecl);
4673 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004674
Douglas Gregor7454c562010-07-02 20:37:36 +00004675 if (!ClassDecl->hasUserDeclaredDestructor()) {
4676 ++ASTContext::NumImplicitDestructors;
4677
4678 // If we have a dynamic class, then the destructor may be virtual, so we
4679 // have to declare the destructor immediately. This ensures that, e.g., it
4680 // shows up in the right place in the vtable and that we diagnose problems
4681 // with the implicit exception specification.
4682 if (ClassDecl->isDynamicClass())
4683 DeclareImplicitDestructor(ClassDecl);
4684 }
Douglas Gregor05379422008-11-03 17:51:48 +00004685}
4686
Francois Pichet1c229c02011-04-22 22:18:13 +00004687void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4688 if (!D)
4689 return;
4690
4691 int NumParamList = D->getNumTemplateParameterLists();
4692 for (int i = 0; i < NumParamList; i++) {
4693 TemplateParameterList* Params = D->getTemplateParameterList(i);
4694 for (TemplateParameterList::iterator Param = Params->begin(),
4695 ParamEnd = Params->end();
4696 Param != ParamEnd; ++Param) {
4697 NamedDecl *Named = cast<NamedDecl>(*Param);
4698 if (Named->getDeclName()) {
4699 S->AddDecl(Named);
4700 IdResolver.AddDecl(Named);
4701 }
4702 }
4703 }
4704}
4705
John McCall48871652010-08-21 09:40:31 +00004706void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00004707 if (!D)
4708 return;
4709
4710 TemplateParameterList *Params = 0;
4711 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4712 Params = Template->getTemplateParameters();
4713 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4714 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4715 Params = PartialSpec->getTemplateParameters();
4716 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004717 return;
4718
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004719 for (TemplateParameterList::iterator Param = Params->begin(),
4720 ParamEnd = Params->end();
4721 Param != ParamEnd; ++Param) {
4722 NamedDecl *Named = cast<NamedDecl>(*Param);
4723 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00004724 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004725 IdResolver.AddDecl(Named);
4726 }
4727 }
4728}
4729
John McCall48871652010-08-21 09:40:31 +00004730void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004731 if (!RecordD) return;
4732 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00004733 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00004734 PushDeclContext(S, Record);
4735}
4736
John McCall48871652010-08-21 09:40:31 +00004737void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004738 if (!RecordD) return;
4739 PopDeclContext();
4740}
4741
Douglas Gregor4d87df52008-12-16 21:30:33 +00004742/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4743/// parsing a top-level (non-nested) C++ class, and we are now
4744/// parsing those parts of the given Method declaration that could
4745/// not be parsed earlier (C++ [class.mem]p2), such as default
4746/// arguments. This action should enter the scope of the given
4747/// Method declaration as if we had just parsed the qualified method
4748/// name. However, it should not bring the parameters into scope;
4749/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00004750void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004751}
4752
4753/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4754/// C++ method declaration. We're (re-)introducing the given
4755/// function parameter into scope for use in parsing later parts of
4756/// the method declaration. For example, we could see an
4757/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00004758void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004759 if (!ParamD)
4760 return;
Mike Stump11289f42009-09-09 15:08:12 +00004761
John McCall48871652010-08-21 09:40:31 +00004762 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00004763
4764 // If this parameter has an unparsed default argument, clear it out
4765 // to make way for the parsed default argument.
4766 if (Param->hasUnparsedDefaultArg())
4767 Param->setDefaultArg(0);
4768
John McCall48871652010-08-21 09:40:31 +00004769 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004770 if (Param->getDeclName())
4771 IdResolver.AddDecl(Param);
4772}
4773
4774/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4775/// processing the delayed method declaration for Method. The method
4776/// declaration is now considered finished. There may be a separate
4777/// ActOnStartOfFunctionDef action later (not necessarily
4778/// immediately!) for this method, if it was also defined inside the
4779/// class body.
John McCall48871652010-08-21 09:40:31 +00004780void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004781 if (!MethodD)
4782 return;
Mike Stump11289f42009-09-09 15:08:12 +00004783
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004784 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00004785
John McCall48871652010-08-21 09:40:31 +00004786 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004787
4788 // Now that we have our default arguments, check the constructor
4789 // again. It could produce additional diagnostics or affect whether
4790 // the class has implicitly-declared destructors, among other
4791 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004792 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4793 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004794
4795 // Check the default arguments, which we may have added.
4796 if (!Method->isInvalidDecl())
4797 CheckCXXDefaultArguments(Method);
4798}
4799
Douglas Gregor831c93f2008-11-05 20:51:48 +00004800/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00004801/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00004802/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004803/// emit diagnostics and set the invalid bit to true. In any case, the type
4804/// will be updated to reflect a well-formed type for the constructor and
4805/// returned.
4806QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004807 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004808 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004809
4810 // C++ [class.ctor]p3:
4811 // A constructor shall not be virtual (10.3) or static (9.4). A
4812 // constructor can be invoked for a const, volatile or const
4813 // volatile object. A constructor shall not be declared const,
4814 // volatile, or const volatile (9.3.2).
4815 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004816 if (!D.isInvalidType())
4817 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4818 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4819 << SourceRange(D.getIdentifierLoc());
4820 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004821 }
John McCall8e7d6562010-08-26 03:08:43 +00004822 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004823 if (!D.isInvalidType())
4824 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4825 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4826 << SourceRange(D.getIdentifierLoc());
4827 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004828 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004829 }
Mike Stump11289f42009-09-09 15:08:12 +00004830
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004831 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004832 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00004833 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004834 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4835 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004836 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004837 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4838 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004839 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004840 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4841 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00004842 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004843 }
Mike Stump11289f42009-09-09 15:08:12 +00004844
Douglas Gregordb9d6642011-01-26 05:01:58 +00004845 // C++0x [class.ctor]p4:
4846 // A constructor shall not be declared with a ref-qualifier.
4847 if (FTI.hasRefQualifier()) {
4848 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4849 << FTI.RefQualifierIsLValueRef
4850 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4851 D.setInvalidType();
4852 }
4853
Douglas Gregor831c93f2008-11-05 20:51:48 +00004854 // Rebuild the function type "R" without any type qualifiers (in
4855 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00004856 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00004857 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004858 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4859 return R;
4860
4861 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4862 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004863 EPI.RefQualifier = RQ_None;
4864
Chris Lattner38378bf2009-04-25 08:28:21 +00004865 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00004866 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004867}
4868
Douglas Gregor4d87df52008-12-16 21:30:33 +00004869/// CheckConstructor - Checks a fully-formed constructor for
4870/// well-formedness, issuing any diagnostics required. Returns true if
4871/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004872void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00004873 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004874 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4875 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004876 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004877
4878 // C++ [class.copy]p3:
4879 // A declaration of a constructor for a class X is ill-formed if
4880 // its first parameter is of type (optionally cv-qualified) X and
4881 // either there are no other parameters or else all other
4882 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004883 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00004884 ((Constructor->getNumParams() == 1) ||
4885 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00004886 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4887 Constructor->getTemplateSpecializationKind()
4888 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004889 QualType ParamType = Constructor->getParamDecl(0)->getType();
4890 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4891 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00004892 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00004893 const char *ConstRef
4894 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4895 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00004896 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00004897 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00004898
4899 // FIXME: Rather that making the constructor invalid, we should endeavor
4900 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004901 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004902 }
4903 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00004904}
4905
John McCalldeb646e2010-08-04 01:04:25 +00004906/// CheckDestructor - Checks a fully-formed destructor definition for
4907/// well-formedness, issuing any diagnostics required. Returns true
4908/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00004909bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00004910 CXXRecordDecl *RD = Destructor->getParent();
4911
4912 if (Destructor->isVirtual()) {
4913 SourceLocation Loc;
4914
4915 if (!Destructor->isImplicit())
4916 Loc = Destructor->getLocation();
4917 else
4918 Loc = RD->getLocation();
4919
4920 // If we have a virtual destructor, look up the deallocation function
4921 FunctionDecl *OperatorDelete = 0;
4922 DeclarationName Name =
4923 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00004924 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00004925 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00004926
4927 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00004928
4929 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004930 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00004931
4932 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00004933}
4934
Mike Stump11289f42009-09-09 15:08:12 +00004935static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00004936FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4937 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4938 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004939 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00004940}
4941
Douglas Gregor831c93f2008-11-05 20:51:48 +00004942/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4943/// the well-formednes of the destructor declarator @p D with type @p
4944/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004945/// emit diagnostics and set the declarator to invalid. Even if this happens,
4946/// will be updated to reflect a well-formed type for the destructor and
4947/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00004948QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004949 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004950 // C++ [class.dtor]p1:
4951 // [...] A typedef-name that names a class is a class-name
4952 // (7.1.3); however, a typedef-name that names a class shall not
4953 // be used as the identifier in the declarator for a destructor
4954 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00004955 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00004956 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00004957 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00004958 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004959 else if (const TemplateSpecializationType *TST =
4960 DeclaratorType->getAs<TemplateSpecializationType>())
4961 if (TST->isTypeAlias())
4962 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4963 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004964
4965 // C++ [class.dtor]p2:
4966 // A destructor is used to destroy objects of its class type. A
4967 // destructor takes no parameters, and no return type can be
4968 // specified for it (not even void). The address of a destructor
4969 // shall not be taken. A destructor shall not be static. A
4970 // destructor can be invoked for a const, volatile or const
4971 // volatile object. A destructor shall not be declared const,
4972 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00004973 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004974 if (!D.isInvalidType())
4975 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4976 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00004977 << SourceRange(D.getIdentifierLoc())
4978 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4979
John McCall8e7d6562010-08-26 03:08:43 +00004980 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004981 }
Chris Lattner38378bf2009-04-25 08:28:21 +00004982 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004983 // Destructors don't have return types, but the parser will
4984 // happily parse something like:
4985 //
4986 // class X {
4987 // float ~X();
4988 // };
4989 //
4990 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00004991 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4992 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4993 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00004994 }
Mike Stump11289f42009-09-09 15:08:12 +00004995
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004996 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004997 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004998 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004999 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5000 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005001 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005002 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5003 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005004 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005005 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5006 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00005007 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005008 }
5009
Douglas Gregordb9d6642011-01-26 05:01:58 +00005010 // C++0x [class.dtor]p2:
5011 // A destructor shall not be declared with a ref-qualifier.
5012 if (FTI.hasRefQualifier()) {
5013 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5014 << FTI.RefQualifierIsLValueRef
5015 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5016 D.setInvalidType();
5017 }
5018
Douglas Gregor831c93f2008-11-05 20:51:48 +00005019 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00005020 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005021 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5022
5023 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00005024 FTI.freeArgs();
5025 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005026 }
5027
Mike Stump11289f42009-09-09 15:08:12 +00005028 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00005029 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005030 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00005031 D.setInvalidType();
5032 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00005033
5034 // Rebuild the function type "R" without any type qualifiers or
5035 // parameters (in case any of the errors above fired) and with
5036 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00005037 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00005038 if (!D.isInvalidType())
5039 return R;
5040
Douglas Gregor95755162010-07-01 05:10:53 +00005041 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005042 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5043 EPI.Variadic = false;
5044 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005045 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005046 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005047}
5048
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005049/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5050/// well-formednes of the conversion function declarator @p D with
5051/// type @p R. If there are any errors in the declarator, this routine
5052/// will emit diagnostics and return true. Otherwise, it will return
5053/// false. Either way, the type @p R will be updated to reflect a
5054/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005055void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00005056 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005057 // C++ [class.conv.fct]p1:
5058 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00005059 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00005060 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00005061 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005062 if (!D.isInvalidType())
5063 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5064 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5065 << SourceRange(D.getIdentifierLoc());
5066 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005067 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005068 }
John McCall212fa2e2010-04-13 00:04:31 +00005069
5070 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5071
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005072 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005073 // Conversion functions don't have return types, but the parser will
5074 // happily parse something like:
5075 //
5076 // class X {
5077 // float operator bool();
5078 // };
5079 //
5080 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00005081 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5082 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5083 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00005084 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005085 }
5086
John McCall212fa2e2010-04-13 00:04:31 +00005087 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5088
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005089 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00005090 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005091 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5092
5093 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005094 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005095 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00005096 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005097 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005098 D.setInvalidType();
5099 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005100
John McCall212fa2e2010-04-13 00:04:31 +00005101 // Diagnose "&operator bool()" and other such nonsense. This
5102 // is actually a gcc extension which we don't support.
5103 if (Proto->getResultType() != ConvType) {
5104 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5105 << Proto->getResultType();
5106 D.setInvalidType();
5107 ConvType = Proto->getResultType();
5108 }
5109
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005110 // C++ [class.conv.fct]p4:
5111 // The conversion-type-id shall not represent a function type nor
5112 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005113 if (ConvType->isArrayType()) {
5114 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5115 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005116 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005117 } else if (ConvType->isFunctionType()) {
5118 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5119 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005120 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005121 }
5122
5123 // Rebuild the function type "R" without any parameters (in case any
5124 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00005125 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00005126 if (D.isInvalidType())
5127 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005128
Douglas Gregor5fb53972009-01-14 15:45:31 +00005129 // C++0x explicit conversion operators.
5130 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00005131 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00005132 diag::warn_explicit_conversion_functions)
5133 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005134}
5135
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005136/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5137/// the declaration of the given C++ conversion function. This routine
5138/// is responsible for recording the conversion function in the C++
5139/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00005140Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005141 assert(Conversion && "Expected to receive a conversion function declaration");
5142
Douglas Gregor4287b372008-12-12 08:25:50 +00005143 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005144
5145 // Make sure we aren't redeclaring the conversion function.
5146 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005147
5148 // C++ [class.conv.fct]p1:
5149 // [...] A conversion function is never used to convert a
5150 // (possibly cv-qualified) object to the (possibly cv-qualified)
5151 // same object type (or a reference to it), to a (possibly
5152 // cv-qualified) base class of that type (or a reference to it),
5153 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00005154 // FIXME: Suppress this warning if the conversion function ends up being a
5155 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00005156 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005157 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005158 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005159 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005160 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5161 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00005162 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005163 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005164 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5165 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005166 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005167 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005168 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005169 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005170 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005171 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005172 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005173 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005174 }
5175
Douglas Gregor457104e2010-09-29 04:25:11 +00005176 if (FunctionTemplateDecl *ConversionTemplate
5177 = Conversion->getDescribedFunctionTemplate())
5178 return ConversionTemplate;
5179
John McCall48871652010-08-21 09:40:31 +00005180 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005181}
5182
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005183//===----------------------------------------------------------------------===//
5184// Namespace Handling
5185//===----------------------------------------------------------------------===//
5186
John McCallb1be5232010-08-26 09:15:37 +00005187
5188
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005189/// ActOnStartNamespaceDef - This is called at the start of a namespace
5190/// definition.
John McCall48871652010-08-21 09:40:31 +00005191Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00005192 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005193 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00005194 SourceLocation IdentLoc,
5195 IdentifierInfo *II,
5196 SourceLocation LBrace,
5197 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005198 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5199 // For anonymous namespace, take the location of the left brace.
5200 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00005201 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005202 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005203 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005204
5205 Scope *DeclRegionScope = NamespcScope->getParent();
5206
Anders Carlssona7bcade2010-02-07 01:09:23 +00005207 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5208
John McCall2faf32c2010-12-10 02:59:44 +00005209 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5210 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00005211
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005212 if (II) {
5213 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00005214 // The identifier in an original-namespace-definition shall not
5215 // have been previously defined in the declarative region in
5216 // which the original-namespace-definition appears. The
5217 // identifier in an original-namespace-definition is the name of
5218 // the namespace. Subsequently in that declarative region, it is
5219 // treated as an original-namespace-name.
5220 //
5221 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005222 // look through using directives, just look for any ordinary names.
5223
5224 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5225 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5226 Decl::IDNS_Namespace;
5227 NamedDecl *PrevDecl = 0;
5228 for (DeclContext::lookup_result R
5229 = CurContext->getRedeclContext()->lookup(II);
5230 R.first != R.second; ++R.first) {
5231 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5232 PrevDecl = *R.first;
5233 break;
5234 }
5235 }
5236
Douglas Gregor91f84212008-12-11 16:49:14 +00005237 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5238 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005239 if (Namespc->isInline() != OrigNS->isInline()) {
5240 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00005241 if (OrigNS->isInline()) {
5242 // The user probably just forgot the 'inline', so suggest that it
5243 // be added back.
5244 Diag(Namespc->getLocation(),
5245 diag::warn_inline_namespace_reopened_noninline)
5246 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5247 } else {
5248 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5249 << Namespc->isInline();
5250 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005251 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00005252
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005253 // Recover by ignoring the new namespace's inline status.
5254 Namespc->setInline(OrigNS->isInline());
5255 }
5256
Douglas Gregor91f84212008-12-11 16:49:14 +00005257 // Attach this namespace decl to the chain of extended namespace
5258 // definitions.
5259 OrigNS->setNextNamespace(Namespc);
5260 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005261
Mike Stump11289f42009-09-09 15:08:12 +00005262 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00005263 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00005264 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00005265 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005266 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005267 } else if (PrevDecl) {
5268 // This is an invalid name redefinition.
5269 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5270 << Namespc->getDeclName();
5271 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5272 Namespc->setInvalidDecl();
5273 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00005274 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00005275 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005276 // This is the first "real" definition of the namespace "std", so update
5277 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005278 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005279 // We had already defined a dummy namespace "std". Link this new
5280 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005281 StdNS->setNextNamespace(Namespc);
5282 StdNS->setLocation(IdentLoc);
5283 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00005284 }
5285
5286 // Make our StdNamespace cache point at the first real definition of the
5287 // "std" namespace.
5288 StdNamespace = Namespc;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005289
5290 // Add this instance of "std" to the set of known namespaces
5291 KnownNamespaces[Namespc] = false;
5292 } else if (!Namespc->isInline()) {
5293 // Since this is an "original" namespace, add it to the known set of
5294 // namespaces if it is not an inline namespace.
5295 KnownNamespaces[Namespc] = false;
Mike Stump11289f42009-09-09 15:08:12 +00005296 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005297
5298 PushOnScopeChains(Namespc, DeclRegionScope);
5299 } else {
John McCall4fa53422009-10-01 00:25:31 +00005300 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00005301 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00005302
5303 // Link the anonymous namespace into its parent.
5304 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00005305 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00005306 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5307 PrevDecl = TU->getAnonymousNamespace();
5308 TU->setAnonymousNamespace(Namespc);
5309 } else {
5310 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5311 PrevDecl = ND->getAnonymousNamespace();
5312 ND->setAnonymousNamespace(Namespc);
5313 }
5314
5315 // Link the anonymous namespace with its previous declaration.
5316 if (PrevDecl) {
5317 assert(PrevDecl->isAnonymousNamespace());
5318 assert(!PrevDecl->getNextNamespace());
5319 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5320 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005321
5322 if (Namespc->isInline() != PrevDecl->isInline()) {
5323 // inline-ness must match
5324 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5325 << Namespc->isInline();
5326 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5327 Namespc->setInvalidDecl();
5328 // Recover by ignoring the new namespace's inline status.
5329 Namespc->setInline(PrevDecl->isInline());
5330 }
John McCall0db42252009-12-16 02:06:49 +00005331 }
John McCall4fa53422009-10-01 00:25:31 +00005332
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00005333 CurContext->addDecl(Namespc);
5334
John McCall4fa53422009-10-01 00:25:31 +00005335 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5336 // behaves as if it were replaced by
5337 // namespace unique { /* empty body */ }
5338 // using namespace unique;
5339 // namespace unique { namespace-body }
5340 // where all occurrences of 'unique' in a translation unit are
5341 // replaced by the same identifier and this identifier differs
5342 // from all other identifiers in the entire program.
5343
5344 // We just create the namespace with an empty name and then add an
5345 // implicit using declaration, just like the standard suggests.
5346 //
5347 // CodeGen enforces the "universally unique" aspect by giving all
5348 // declarations semantically contained within an anonymous
5349 // namespace internal linkage.
5350
John McCall0db42252009-12-16 02:06:49 +00005351 if (!PrevDecl) {
5352 UsingDirectiveDecl* UD
5353 = UsingDirectiveDecl::Create(Context, CurContext,
5354 /* 'using' */ LBrace,
5355 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00005356 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00005357 /* identifier */ SourceLocation(),
5358 Namespc,
5359 /* Ancestor */ CurContext);
5360 UD->setImplicit();
5361 CurContext->addDecl(UD);
5362 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005363 }
5364
5365 // Although we could have an invalid decl (i.e. the namespace name is a
5366 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00005367 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5368 // for the namespace has the declarations that showed up in that particular
5369 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00005370 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00005371 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005372}
5373
Sebastian Redla6602e92009-11-23 15:34:23 +00005374/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5375/// is a namespace alias, returns the namespace it points to.
5376static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5377 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5378 return AD->getNamespace();
5379 return dyn_cast_or_null<NamespaceDecl>(D);
5380}
5381
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005382/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5383/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00005384void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005385 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5386 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005387 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005388 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00005389 if (Namespc->hasAttr<VisibilityAttr>())
5390 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005391}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005392
John McCall28a0cf72010-08-25 07:42:41 +00005393CXXRecordDecl *Sema::getStdBadAlloc() const {
5394 return cast_or_null<CXXRecordDecl>(
5395 StdBadAlloc.get(Context.getExternalSource()));
5396}
5397
5398NamespaceDecl *Sema::getStdNamespace() const {
5399 return cast_or_null<NamespaceDecl>(
5400 StdNamespace.get(Context.getExternalSource()));
5401}
5402
Douglas Gregorcdf87022010-06-29 17:53:46 +00005403/// \brief Retrieve the special "std" namespace, which may require us to
5404/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005405NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00005406 if (!StdNamespace) {
5407 // The "std" namespace has not yet been defined, so build one implicitly.
5408 StdNamespace = NamespaceDecl::Create(Context,
5409 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005410 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00005411 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005412 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005413 }
5414
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005415 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005416}
5417
Douglas Gregora172e082011-03-26 22:25:30 +00005418/// \brief Determine whether a using statement is in a context where it will be
5419/// apply in all contexts.
5420static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5421 switch (CurContext->getDeclKind()) {
5422 case Decl::TranslationUnit:
5423 return true;
5424 case Decl::LinkageSpec:
5425 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5426 default:
5427 return false;
5428 }
5429}
5430
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005431static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5432 CXXScopeSpec &SS,
5433 SourceLocation IdentLoc,
5434 IdentifierInfo *Ident) {
5435 R.clear();
5436 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5437 R.getLookupKind(), Sc, &SS, NULL,
5438 false, S.CTC_NoKeywords, NULL)) {
5439 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5440 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5441 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5442 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5443 if (DeclContext *DC = S.computeDeclContext(SS, false))
5444 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5445 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5446 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5447 else
5448 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5449 << Ident << CorrectedQuotedStr
5450 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5451
5452 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5453 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5454
5455 Ident = Corrected.getCorrectionAsIdentifierInfo();
5456 R.addDecl(Corrected.getCorrectionDecl());
5457 return true;
5458 }
5459 R.setLookupName(Ident);
5460 }
5461 return false;
5462}
5463
John McCall48871652010-08-21 09:40:31 +00005464Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005465 SourceLocation UsingLoc,
5466 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005467 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00005468 SourceLocation IdentLoc,
5469 IdentifierInfo *NamespcName,
5470 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00005471 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5472 assert(NamespcName && "Invalid NamespcName.");
5473 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00005474
5475 // This can only happen along a recovery path.
5476 while (S->getFlags() & Scope::TemplateParamScope)
5477 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00005478 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00005479
Douglas Gregor889ceb72009-02-03 19:21:40 +00005480 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00005481 NestedNameSpecifier *Qualifier = 0;
5482 if (SS.isSet())
5483 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5484
Douglas Gregor34074322009-01-14 22:20:51 +00005485 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005486 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5487 LookupParsedName(R, S, &SS);
5488 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005489 return 0;
John McCall27b18f82009-11-17 02:14:36 +00005490
Douglas Gregorcdf87022010-06-29 17:53:46 +00005491 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005492 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005493 // Allow "using namespace std;" or "using namespace ::std;" even if
5494 // "std" hasn't been defined yet, for GCC compatibility.
5495 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5496 NamespcName->isStr("std")) {
5497 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005498 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00005499 R.resolveKind();
5500 }
5501 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005502 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005503 }
5504
John McCall9f3059a2009-10-09 21:13:30 +00005505 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00005506 NamedDecl *Named = R.getFoundDecl();
5507 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5508 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00005509 // C++ [namespace.udir]p1:
5510 // A using-directive specifies that the names in the nominated
5511 // namespace can be used in the scope in which the
5512 // using-directive appears after the using-directive. During
5513 // unqualified name lookup (3.4.1), the names appear as if they
5514 // were declared in the nearest enclosing namespace which
5515 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00005516 // namespace. [Note: in this context, "contains" means "contains
5517 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00005518
5519 // Find enclosing context containing both using-directive and
5520 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00005521 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005522 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5523 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5524 CommonAncestor = CommonAncestor->getParent();
5525
Sebastian Redla6602e92009-11-23 15:34:23 +00005526 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00005527 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00005528 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005529
Douglas Gregora172e082011-03-26 22:25:30 +00005530 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00005531 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005532 Diag(IdentLoc, diag::warn_using_directive_in_header);
5533 }
5534
Douglas Gregor889ceb72009-02-03 19:21:40 +00005535 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005536 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00005537 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00005538 }
5539
Douglas Gregor889ceb72009-02-03 19:21:40 +00005540 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00005541 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00005542}
5543
5544void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5545 // If scope has associated entity, then using directive is at namespace
5546 // or translation unit scope. We add UsingDirectiveDecls, into
5547 // it's lookup structure.
5548 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005549 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005550 else
5551 // Otherwise it is block-sope. using-directives will affect lookup
5552 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00005553 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005554}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005555
Douglas Gregorfec52632009-06-20 00:51:54 +00005556
John McCall48871652010-08-21 09:40:31 +00005557Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00005558 AccessSpecifier AS,
5559 bool HasUsingKeyword,
5560 SourceLocation UsingLoc,
5561 CXXScopeSpec &SS,
5562 UnqualifiedId &Name,
5563 AttributeList *AttrList,
5564 bool IsTypeName,
5565 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00005566 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00005567
Douglas Gregor220f4272009-11-04 16:30:06 +00005568 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00005569 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00005570 case UnqualifiedId::IK_Identifier:
5571 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00005572 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00005573 case UnqualifiedId::IK_ConversionFunctionId:
5574 break;
5575
5576 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005577 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00005578 // C++0x inherited constructors.
5579 if (getLangOptions().CPlusPlus0x) break;
5580
Douglas Gregor220f4272009-11-04 16:30:06 +00005581 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5582 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005583 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005584
5585 case UnqualifiedId::IK_DestructorName:
5586 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5587 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005588 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005589
5590 case UnqualifiedId::IK_TemplateId:
5591 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5592 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00005593 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005594 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005595
5596 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5597 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00005598 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00005599 return 0;
John McCall3969e302009-12-08 07:46:18 +00005600
John McCalla0097262009-12-11 02:10:03 +00005601 // Warn about using declarations.
5602 // TODO: store that the declaration was written without 'using' and
5603 // talk about access decls instead of using decls in the
5604 // diagnostics.
5605 if (!HasUsingKeyword) {
5606 UsingLoc = Name.getSourceRange().getBegin();
5607
5608 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00005609 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00005610 }
5611
Douglas Gregorc4356532010-12-16 00:46:58 +00005612 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5613 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5614 return 0;
5615
John McCall3f746822009-11-17 05:59:44 +00005616 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005617 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005618 /* IsInstantiation */ false,
5619 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00005620 if (UD)
5621 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00005622
John McCall48871652010-08-21 09:40:31 +00005623 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00005624}
5625
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005626/// \brief Determine whether a using declaration considers the given
5627/// declarations as "equivalent", e.g., if they are redeclarations of
5628/// the same entity or are both typedefs of the same type.
5629static bool
5630IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5631 bool &SuppressRedeclaration) {
5632 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5633 SuppressRedeclaration = false;
5634 return true;
5635 }
5636
Richard Smithdda56e42011-04-15 14:24:37 +00005637 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5638 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005639 SuppressRedeclaration = true;
5640 return Context.hasSameType(TD1->getUnderlyingType(),
5641 TD2->getUnderlyingType());
5642 }
5643
5644 return false;
5645}
5646
5647
John McCall84d87672009-12-10 09:41:52 +00005648/// Determines whether to create a using shadow decl for a particular
5649/// decl, given the set of decls existing prior to this using lookup.
5650bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5651 const LookupResult &Previous) {
5652 // Diagnose finding a decl which is not from a base class of the
5653 // current class. We do this now because there are cases where this
5654 // function will silently decide not to build a shadow decl, which
5655 // will pre-empt further diagnostics.
5656 //
5657 // We don't need to do this in C++0x because we do the check once on
5658 // the qualifier.
5659 //
5660 // FIXME: diagnose the following if we care enough:
5661 // struct A { int foo; };
5662 // struct B : A { using A::foo; };
5663 // template <class T> struct C : A {};
5664 // template <class T> struct D : C<T> { using B::foo; } // <---
5665 // This is invalid (during instantiation) in C++03 because B::foo
5666 // resolves to the using decl in B, which is not a base class of D<T>.
5667 // We can't diagnose it immediately because C<T> is an unknown
5668 // specialization. The UsingShadowDecl in D<T> then points directly
5669 // to A::foo, which will look well-formed when we instantiate.
5670 // The right solution is to not collapse the shadow-decl chain.
5671 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5672 DeclContext *OrigDC = Orig->getDeclContext();
5673
5674 // Handle enums and anonymous structs.
5675 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5676 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5677 while (OrigRec->isAnonymousStructOrUnion())
5678 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5679
5680 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5681 if (OrigDC == CurContext) {
5682 Diag(Using->getLocation(),
5683 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005684 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005685 Diag(Orig->getLocation(), diag::note_using_decl_target);
5686 return true;
5687 }
5688
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005689 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00005690 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005691 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00005692 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005693 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005694 Diag(Orig->getLocation(), diag::note_using_decl_target);
5695 return true;
5696 }
5697 }
5698
5699 if (Previous.empty()) return false;
5700
5701 NamedDecl *Target = Orig;
5702 if (isa<UsingShadowDecl>(Target))
5703 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5704
John McCalla17e83e2009-12-11 02:33:26 +00005705 // If the target happens to be one of the previous declarations, we
5706 // don't have a conflict.
5707 //
5708 // FIXME: but we might be increasing its access, in which case we
5709 // should redeclare it.
5710 NamedDecl *NonTag = 0, *Tag = 0;
5711 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5712 I != E; ++I) {
5713 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005714 bool Result;
5715 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5716 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00005717
5718 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5719 }
5720
John McCall84d87672009-12-10 09:41:52 +00005721 if (Target->isFunctionOrFunctionTemplate()) {
5722 FunctionDecl *FD;
5723 if (isa<FunctionTemplateDecl>(Target))
5724 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5725 else
5726 FD = cast<FunctionDecl>(Target);
5727
5728 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00005729 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00005730 case Ovl_Overload:
5731 return false;
5732
5733 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00005734 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005735 break;
5736
5737 // We found a decl with the exact signature.
5738 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005739 // If we're in a record, we want to hide the target, so we
5740 // return true (without a diagnostic) to tell the caller not to
5741 // build a shadow decl.
5742 if (CurContext->isRecord())
5743 return true;
5744
5745 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00005746 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005747 break;
5748 }
5749
5750 Diag(Target->getLocation(), diag::note_using_decl_target);
5751 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5752 return true;
5753 }
5754
5755 // Target is not a function.
5756
John McCall84d87672009-12-10 09:41:52 +00005757 if (isa<TagDecl>(Target)) {
5758 // No conflict between a tag and a non-tag.
5759 if (!Tag) return false;
5760
John McCalle29c5cd2009-12-10 19:51:03 +00005761 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005762 Diag(Target->getLocation(), diag::note_using_decl_target);
5763 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5764 return true;
5765 }
5766
5767 // No conflict between a tag and a non-tag.
5768 if (!NonTag) return false;
5769
John McCalle29c5cd2009-12-10 19:51:03 +00005770 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005771 Diag(Target->getLocation(), diag::note_using_decl_target);
5772 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5773 return true;
5774}
5775
John McCall3f746822009-11-17 05:59:44 +00005776/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00005777UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00005778 UsingDecl *UD,
5779 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00005780
5781 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00005782 NamedDecl *Target = Orig;
5783 if (isa<UsingShadowDecl>(Target)) {
5784 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5785 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00005786 }
5787
5788 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00005789 = UsingShadowDecl::Create(Context, CurContext,
5790 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00005791 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00005792
5793 Shadow->setAccess(UD->getAccess());
5794 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5795 Shadow->setInvalidDecl();
5796
John McCall3f746822009-11-17 05:59:44 +00005797 if (S)
John McCall3969e302009-12-08 07:46:18 +00005798 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00005799 else
John McCall3969e302009-12-08 07:46:18 +00005800 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00005801
John McCall3969e302009-12-08 07:46:18 +00005802
John McCall84d87672009-12-10 09:41:52 +00005803 return Shadow;
5804}
John McCall3969e302009-12-08 07:46:18 +00005805
John McCall84d87672009-12-10 09:41:52 +00005806/// Hides a using shadow declaration. This is required by the current
5807/// using-decl implementation when a resolvable using declaration in a
5808/// class is followed by a declaration which would hide or override
5809/// one or more of the using decl's targets; for example:
5810///
5811/// struct Base { void foo(int); };
5812/// struct Derived : Base {
5813/// using Base::foo;
5814/// void foo(int);
5815/// };
5816///
5817/// The governing language is C++03 [namespace.udecl]p12:
5818///
5819/// When a using-declaration brings names from a base class into a
5820/// derived class scope, member functions in the derived class
5821/// override and/or hide member functions with the same name and
5822/// parameter types in a base class (rather than conflicting).
5823///
5824/// There are two ways to implement this:
5825/// (1) optimistically create shadow decls when they're not hidden
5826/// by existing declarations, or
5827/// (2) don't create any shadow decls (or at least don't make them
5828/// visible) until we've fully parsed/instantiated the class.
5829/// The problem with (1) is that we might have to retroactively remove
5830/// a shadow decl, which requires several O(n) operations because the
5831/// decl structures are (very reasonably) not designed for removal.
5832/// (2) avoids this but is very fiddly and phase-dependent.
5833void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00005834 if (Shadow->getDeclName().getNameKind() ==
5835 DeclarationName::CXXConversionFunctionName)
5836 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5837
John McCall84d87672009-12-10 09:41:52 +00005838 // Remove it from the DeclContext...
5839 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005840
John McCall84d87672009-12-10 09:41:52 +00005841 // ...and the scope, if applicable...
5842 if (S) {
John McCall48871652010-08-21 09:40:31 +00005843 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00005844 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005845 }
5846
John McCall84d87672009-12-10 09:41:52 +00005847 // ...and the using decl.
5848 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5849
5850 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00005851 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00005852}
5853
John McCalle61f2ba2009-11-18 02:36:19 +00005854/// Builds a using declaration.
5855///
5856/// \param IsInstantiation - Whether this call arises from an
5857/// instantiation of an unresolved using declaration. We treat
5858/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00005859NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5860 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005861 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005862 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00005863 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005864 bool IsInstantiation,
5865 bool IsTypeName,
5866 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00005867 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005868 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00005869 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00005870
Anders Carlssonf038fc22009-08-28 05:49:21 +00005871 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00005872
Anders Carlsson59140b32009-08-28 03:16:11 +00005873 if (SS.isEmpty()) {
5874 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00005875 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00005876 }
Mike Stump11289f42009-09-09 15:08:12 +00005877
John McCall84d87672009-12-10 09:41:52 +00005878 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005879 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00005880 ForRedeclaration);
5881 Previous.setHideTags(false);
5882 if (S) {
5883 LookupName(Previous, S);
5884
5885 // It is really dumb that we have to do this.
5886 LookupResult::Filter F = Previous.makeFilter();
5887 while (F.hasNext()) {
5888 NamedDecl *D = F.next();
5889 if (!isDeclInScope(D, CurContext, S))
5890 F.erase();
5891 }
5892 F.done();
5893 } else {
5894 assert(IsInstantiation && "no scope in non-instantiation");
5895 assert(CurContext->isRecord() && "scope not record in instantiation");
5896 LookupQualifiedName(Previous, CurContext);
5897 }
5898
John McCall84d87672009-12-10 09:41:52 +00005899 // Check for invalid redeclarations.
5900 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5901 return 0;
5902
5903 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00005904 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5905 return 0;
5906
John McCall84c16cf2009-11-12 03:15:40 +00005907 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005908 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005909 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00005910 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00005911 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00005912 // FIXME: not all declaration name kinds are legal here
5913 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5914 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005915 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005916 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00005917 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005918 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5919 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00005920 }
John McCallb96ec562009-12-04 22:46:56 +00005921 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005922 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5923 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00005924 }
John McCallb96ec562009-12-04 22:46:56 +00005925 D->setAccess(AS);
5926 CurContext->addDecl(D);
5927
5928 if (!LookupContext) return D;
5929 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00005930
John McCall0b66eb32010-05-01 00:40:08 +00005931 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00005932 UD->setInvalidDecl();
5933 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00005934 }
5935
Sebastian Redl08905022011-02-05 19:23:19 +00005936 // Constructor inheriting using decls get special treatment.
5937 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00005938 if (CheckInheritedConstructorUsingDecl(UD))
5939 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00005940 return UD;
5941 }
5942
5943 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00005944
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005945 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00005946
John McCall3969e302009-12-08 07:46:18 +00005947 // Unlike most lookups, we don't always want to hide tag
5948 // declarations: tag names are visible through the using declaration
5949 // even if hidden by ordinary names, *except* in a dependent context
5950 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00005951 if (!IsInstantiation)
5952 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00005953
John McCall27b18f82009-11-17 02:14:36 +00005954 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00005955
John McCall9f3059a2009-10-09 21:13:30 +00005956 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00005957 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005958 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005959 UD->setInvalidDecl();
5960 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005961 }
5962
John McCallb96ec562009-12-04 22:46:56 +00005963 if (R.isAmbiguous()) {
5964 UD->setInvalidDecl();
5965 return UD;
5966 }
Mike Stump11289f42009-09-09 15:08:12 +00005967
John McCalle61f2ba2009-11-18 02:36:19 +00005968 if (IsTypeName) {
5969 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00005970 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005971 Diag(IdentLoc, diag::err_using_typename_non_type);
5972 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5973 Diag((*I)->getUnderlyingDecl()->getLocation(),
5974 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005975 UD->setInvalidDecl();
5976 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005977 }
5978 } else {
5979 // If we asked for a non-typename and we got a type, error out,
5980 // but only if this is an instantiation of an unresolved using
5981 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00005982 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005983 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5984 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005985 UD->setInvalidDecl();
5986 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005987 }
Anders Carlsson59140b32009-08-28 03:16:11 +00005988 }
5989
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005990 // C++0x N2914 [namespace.udecl]p6:
5991 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00005992 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005993 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5994 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005995 UD->setInvalidDecl();
5996 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005997 }
Mike Stump11289f42009-09-09 15:08:12 +00005998
John McCall84d87672009-12-10 09:41:52 +00005999 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6000 if (!CheckUsingShadowDecl(UD, *I, Previous))
6001 BuildUsingShadowDecl(S, UD, *I);
6002 }
John McCall3f746822009-11-17 05:59:44 +00006003
6004 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006005}
6006
Sebastian Redl08905022011-02-05 19:23:19 +00006007/// Additional checks for a using declaration referring to a constructor name.
6008bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6009 if (UD->isTypeName()) {
6010 // FIXME: Cannot specify typename when specifying constructor
6011 return true;
6012 }
6013
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006014 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00006015 assert(SourceType &&
6016 "Using decl naming constructor doesn't have type in scope spec.");
6017 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6018
6019 // Check whether the named type is a direct base class.
6020 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6021 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6022 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6023 BaseIt != BaseE; ++BaseIt) {
6024 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6025 if (CanonicalSourceType == BaseType)
6026 break;
6027 }
6028
6029 if (BaseIt == BaseE) {
6030 // Did not find SourceType in the bases.
6031 Diag(UD->getUsingLocation(),
6032 diag::err_using_decl_constructor_not_in_direct_base)
6033 << UD->getNameInfo().getSourceRange()
6034 << QualType(SourceType, 0) << TargetClass;
6035 return true;
6036 }
6037
6038 BaseIt->setInheritConstructors();
6039
6040 return false;
6041}
6042
John McCall84d87672009-12-10 09:41:52 +00006043/// Checks that the given using declaration is not an invalid
6044/// redeclaration. Note that this is checking only for the using decl
6045/// itself, not for any ill-formedness among the UsingShadowDecls.
6046bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6047 bool isTypeName,
6048 const CXXScopeSpec &SS,
6049 SourceLocation NameLoc,
6050 const LookupResult &Prev) {
6051 // C++03 [namespace.udecl]p8:
6052 // C++0x [namespace.udecl]p10:
6053 // A using-declaration is a declaration and can therefore be used
6054 // repeatedly where (and only where) multiple declarations are
6055 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00006056 //
John McCall032092f2010-11-29 18:01:58 +00006057 // That's in non-member contexts.
6058 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00006059 return false;
6060
6061 NestedNameSpecifier *Qual
6062 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6063
6064 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6065 NamedDecl *D = *I;
6066
6067 bool DTypename;
6068 NestedNameSpecifier *DQual;
6069 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6070 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006071 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006072 } else if (UnresolvedUsingValueDecl *UD
6073 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6074 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006075 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006076 } else if (UnresolvedUsingTypenameDecl *UD
6077 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6078 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006079 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006080 } else continue;
6081
6082 // using decls differ if one says 'typename' and the other doesn't.
6083 // FIXME: non-dependent using decls?
6084 if (isTypeName != DTypename) continue;
6085
6086 // using decls differ if they name different scopes (but note that
6087 // template instantiation can cause this check to trigger when it
6088 // didn't before instantiation).
6089 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6090 Context.getCanonicalNestedNameSpecifier(DQual))
6091 continue;
6092
6093 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00006094 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00006095 return true;
6096 }
6097
6098 return false;
6099}
6100
John McCall3969e302009-12-08 07:46:18 +00006101
John McCallb96ec562009-12-04 22:46:56 +00006102/// Checks that the given nested-name qualifier used in a using decl
6103/// in the current context is appropriately related to the current
6104/// scope. If an error is found, diagnoses it and returns true.
6105bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6106 const CXXScopeSpec &SS,
6107 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00006108 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006109
John McCall3969e302009-12-08 07:46:18 +00006110 if (!CurContext->isRecord()) {
6111 // C++03 [namespace.udecl]p3:
6112 // C++0x [namespace.udecl]p8:
6113 // A using-declaration for a class member shall be a member-declaration.
6114
6115 // If we weren't able to compute a valid scope, it must be a
6116 // dependent class scope.
6117 if (!NamedContext || NamedContext->isRecord()) {
6118 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6119 << SS.getRange();
6120 return true;
6121 }
6122
6123 // Otherwise, everything is known to be fine.
6124 return false;
6125 }
6126
6127 // The current scope is a record.
6128
6129 // If the named context is dependent, we can't decide much.
6130 if (!NamedContext) {
6131 // FIXME: in C++0x, we can diagnose if we can prove that the
6132 // nested-name-specifier does not refer to a base class, which is
6133 // still possible in some cases.
6134
6135 // Otherwise we have to conservatively report that things might be
6136 // okay.
6137 return false;
6138 }
6139
6140 if (!NamedContext->isRecord()) {
6141 // Ideally this would point at the last name in the specifier,
6142 // but we don't have that level of source info.
6143 Diag(SS.getRange().getBegin(),
6144 diag::err_using_decl_nested_name_specifier_is_not_class)
6145 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6146 return true;
6147 }
6148
Douglas Gregor7c842292010-12-21 07:41:49 +00006149 if (!NamedContext->isDependentContext() &&
6150 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6151 return true;
6152
John McCall3969e302009-12-08 07:46:18 +00006153 if (getLangOptions().CPlusPlus0x) {
6154 // C++0x [namespace.udecl]p3:
6155 // In a using-declaration used as a member-declaration, the
6156 // nested-name-specifier shall name a base class of the class
6157 // being defined.
6158
6159 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6160 cast<CXXRecordDecl>(NamedContext))) {
6161 if (CurContext == NamedContext) {
6162 Diag(NameLoc,
6163 diag::err_using_decl_nested_name_specifier_is_current_class)
6164 << SS.getRange();
6165 return true;
6166 }
6167
6168 Diag(SS.getRange().getBegin(),
6169 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6170 << (NestedNameSpecifier*) SS.getScopeRep()
6171 << cast<CXXRecordDecl>(CurContext)
6172 << SS.getRange();
6173 return true;
6174 }
6175
6176 return false;
6177 }
6178
6179 // C++03 [namespace.udecl]p4:
6180 // A using-declaration used as a member-declaration shall refer
6181 // to a member of a base class of the class being defined [etc.].
6182
6183 // Salient point: SS doesn't have to name a base class as long as
6184 // lookup only finds members from base classes. Therefore we can
6185 // diagnose here only if we can prove that that can't happen,
6186 // i.e. if the class hierarchies provably don't intersect.
6187
6188 // TODO: it would be nice if "definitely valid" results were cached
6189 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6190 // need to be repeated.
6191
6192 struct UserData {
6193 llvm::DenseSet<const CXXRecordDecl*> Bases;
6194
6195 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6196 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6197 Data->Bases.insert(Base);
6198 return true;
6199 }
6200
6201 bool hasDependentBases(const CXXRecordDecl *Class) {
6202 return !Class->forallBases(collect, this);
6203 }
6204
6205 /// Returns true if the base is dependent or is one of the
6206 /// accumulated base classes.
6207 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6208 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6209 return !Data->Bases.count(Base);
6210 }
6211
6212 bool mightShareBases(const CXXRecordDecl *Class) {
6213 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6214 }
6215 };
6216
6217 UserData Data;
6218
6219 // Returns false if we find a dependent base.
6220 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6221 return false;
6222
6223 // Returns false if the class has a dependent base or if it or one
6224 // of its bases is present in the base set of the current context.
6225 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6226 return false;
6227
6228 Diag(SS.getRange().getBegin(),
6229 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6230 << (NestedNameSpecifier*) SS.getScopeRep()
6231 << cast<CXXRecordDecl>(CurContext)
6232 << SS.getRange();
6233
6234 return true;
John McCallb96ec562009-12-04 22:46:56 +00006235}
6236
Richard Smithdda56e42011-04-15 14:24:37 +00006237Decl *Sema::ActOnAliasDeclaration(Scope *S,
6238 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006239 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00006240 SourceLocation UsingLoc,
6241 UnqualifiedId &Name,
6242 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00006243 // Skip up to the relevant declaration scope.
6244 while (S->getFlags() & Scope::TemplateParamScope)
6245 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00006246 assert((S->getFlags() & Scope::DeclScope) &&
6247 "got alias-declaration outside of declaration scope");
6248
6249 if (Type.isInvalid())
6250 return 0;
6251
6252 bool Invalid = false;
6253 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6254 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00006255 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00006256
6257 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6258 return 0;
6259
6260 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006261 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00006262 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006263 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6264 TInfo->getTypeLoc().getBeginLoc());
6265 }
Richard Smithdda56e42011-04-15 14:24:37 +00006266
6267 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6268 LookupName(Previous, S);
6269
6270 // Warn about shadowing the name of a template parameter.
6271 if (Previous.isSingleResult() &&
6272 Previous.getFoundDecl()->isTemplateParameter()) {
6273 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6274 Previous.getFoundDecl()))
6275 Invalid = true;
6276 Previous.clear();
6277 }
6278
6279 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6280 "name in alias declaration must be an identifier");
6281 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6282 Name.StartLocation,
6283 Name.Identifier, TInfo);
6284
6285 NewTD->setAccess(AS);
6286
6287 if (Invalid)
6288 NewTD->setInvalidDecl();
6289
Richard Smith3f1b5d02011-05-05 21:57:07 +00006290 CheckTypedefForVariablyModifiedType(S, NewTD);
6291 Invalid |= NewTD->isInvalidDecl();
6292
Richard Smithdda56e42011-04-15 14:24:37 +00006293 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006294
6295 NamedDecl *NewND;
6296 if (TemplateParamLists.size()) {
6297 TypeAliasTemplateDecl *OldDecl = 0;
6298 TemplateParameterList *OldTemplateParams = 0;
6299
6300 if (TemplateParamLists.size() != 1) {
6301 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6302 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6303 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6304 }
6305 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6306
6307 // Only consider previous declarations in the same scope.
6308 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6309 /*ExplicitInstantiationOrSpecialization*/false);
6310 if (!Previous.empty()) {
6311 Redeclaration = true;
6312
6313 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6314 if (!OldDecl && !Invalid) {
6315 Diag(UsingLoc, diag::err_redefinition_different_kind)
6316 << Name.Identifier;
6317
6318 NamedDecl *OldD = Previous.getRepresentativeDecl();
6319 if (OldD->getLocation().isValid())
6320 Diag(OldD->getLocation(), diag::note_previous_definition);
6321
6322 Invalid = true;
6323 }
6324
6325 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6326 if (TemplateParameterListsAreEqual(TemplateParams,
6327 OldDecl->getTemplateParameters(),
6328 /*Complain=*/true,
6329 TPL_TemplateMatch))
6330 OldTemplateParams = OldDecl->getTemplateParameters();
6331 else
6332 Invalid = true;
6333
6334 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6335 if (!Invalid &&
6336 !Context.hasSameType(OldTD->getUnderlyingType(),
6337 NewTD->getUnderlyingType())) {
6338 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6339 // but we can't reasonably accept it.
6340 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6341 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6342 if (OldTD->getLocation().isValid())
6343 Diag(OldTD->getLocation(), diag::note_previous_definition);
6344 Invalid = true;
6345 }
6346 }
6347 }
6348
6349 // Merge any previous default template arguments into our parameters,
6350 // and check the parameter list.
6351 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6352 TPC_TypeAliasTemplate))
6353 return 0;
6354
6355 TypeAliasTemplateDecl *NewDecl =
6356 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6357 Name.Identifier, TemplateParams,
6358 NewTD);
6359
6360 NewDecl->setAccess(AS);
6361
6362 if (Invalid)
6363 NewDecl->setInvalidDecl();
6364 else if (OldDecl)
6365 NewDecl->setPreviousDeclaration(OldDecl);
6366
6367 NewND = NewDecl;
6368 } else {
6369 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6370 NewND = NewTD;
6371 }
Richard Smithdda56e42011-04-15 14:24:37 +00006372
6373 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00006374 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00006375
Richard Smith3f1b5d02011-05-05 21:57:07 +00006376 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00006377}
6378
John McCall48871652010-08-21 09:40:31 +00006379Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006380 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006381 SourceLocation AliasLoc,
6382 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006383 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006384 SourceLocation IdentLoc,
6385 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00006386
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006387 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006388 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6389 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006390
Anders Carlssondca83c42009-03-28 06:23:46 +00006391 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00006392 NamedDecl *PrevDecl
6393 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6394 ForRedeclaration);
6395 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6396 PrevDecl = 0;
6397
6398 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006399 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00006400 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006401 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00006402 // FIXME: At some point, we'll want to create the (redundant)
6403 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00006404 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00006405 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00006406 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006407 }
Mike Stump11289f42009-09-09 15:08:12 +00006408
Anders Carlssondca83c42009-03-28 06:23:46 +00006409 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6410 diag::err_redefinition_different_kind;
6411 Diag(AliasLoc, DiagID) << Alias;
6412 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00006413 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00006414 }
6415
John McCall27b18f82009-11-17 02:14:36 +00006416 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006417 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006418
John McCall9f3059a2009-10-09 21:13:30 +00006419 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006420 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006421 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006422 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006423 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00006424 }
Mike Stump11289f42009-09-09 15:08:12 +00006425
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006426 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00006427 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00006428 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00006429 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006430
John McCalld8d0d432010-02-16 06:53:13 +00006431 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00006432 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00006433}
6434
Douglas Gregora57478e2010-05-01 15:04:51 +00006435namespace {
6436 /// \brief Scoped object used to handle the state changes required in Sema
6437 /// to implicitly define the body of a C++ member function;
6438 class ImplicitlyDefinedFunctionScope {
6439 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00006440 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00006441
6442 public:
6443 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00006444 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00006445 {
Douglas Gregora57478e2010-05-01 15:04:51 +00006446 S.PushFunctionScope();
6447 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6448 }
6449
6450 ~ImplicitlyDefinedFunctionScope() {
6451 S.PopExpressionEvaluationContext();
6452 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00006453 }
6454 };
6455}
6456
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006457Sema::ImplicitExceptionSpecification
6458Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00006459 // C++ [except.spec]p14:
6460 // An implicitly declared special member function (Clause 12) shall have an
6461 // exception-specification. [...]
6462 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006463 if (ClassDecl->isInvalidDecl())
6464 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00006465
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006466 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006467 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6468 BEnd = ClassDecl->bases_end();
6469 B != BEnd; ++B) {
6470 if (B->isVirtual()) // Handled below.
6471 continue;
6472
Douglas Gregor9672f922010-07-03 00:47:00 +00006473 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6474 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006475 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6476 // If this is a deleted function, add it anyway. This might be conformant
6477 // with the standard. This might not. I'm not sure. It might not matter.
6478 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006479 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006480 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006481 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006482
6483 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006484 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6485 BEnd = ClassDecl->vbases_end();
6486 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00006487 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6488 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006489 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6490 // If this is a deleted function, add it anyway. This might be conformant
6491 // with the standard. This might not. I'm not sure. It might not matter.
6492 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006493 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006494 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006495 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006496
6497 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006498 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6499 FEnd = ClassDecl->field_end();
6500 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00006501 if (F->hasInClassInitializer()) {
6502 if (Expr *E = F->getInClassInitializer())
6503 ExceptSpec.CalledExpr(E);
6504 else if (!F->isInvalidDecl())
6505 ExceptSpec.SetDelayed();
6506 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00006507 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00006508 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6509 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6510 // If this is a deleted function, add it anyway. This might be conformant
6511 // with the standard. This might not. I'm not sure. It might not matter.
6512 // In particular, the problem is that this function never gets called. It
6513 // might just be ill-formed because this function attempts to refer to
6514 // a deleted function here.
6515 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006516 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006517 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006518 }
John McCalldb40c7f2010-12-14 08:05:40 +00006519
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006520 return ExceptSpec;
6521}
6522
6523CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6524 CXXRecordDecl *ClassDecl) {
6525 // C++ [class.ctor]p5:
6526 // A default constructor for a class X is a constructor of class X
6527 // that can be called without an argument. If there is no
6528 // user-declared constructor for class X, a default constructor is
6529 // implicitly declared. An implicitly-declared default constructor
6530 // is an inline public member of its class.
6531 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6532 "Should not build implicit default constructor!");
6533
6534 ImplicitExceptionSpecification Spec =
6535 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6536 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00006537
Douglas Gregor6d880b12010-07-01 22:31:05 +00006538 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006539 CanQualType ClassType
6540 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006541 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006542 DeclarationName Name
6543 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006544 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006545 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00006546 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006547 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00006548 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006549 /*TInfo=*/0,
6550 /*isExplicit=*/false,
6551 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00006552 /*isImplicitlyDeclared=*/true,
6553 // FIXME: apply the rules for definitions here
6554 /*isConstexpr=*/false);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006555 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00006556 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006557 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00006558 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00006559
6560 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00006561 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6562
Douglas Gregor0be31a22010-07-02 17:43:08 +00006563 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00006564 PushOnScopeChains(DefaultCon, S, false);
6565 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00006566
6567 if (ShouldDeleteDefaultConstructor(DefaultCon))
6568 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00006569
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006570 return DefaultCon;
6571}
6572
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006573void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6574 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00006575 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006576 !Constructor->doesThisDeclarationHaveABody() &&
6577 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006578 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006579
Anders Carlsson423f5d82010-04-23 16:04:08 +00006580 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00006581 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00006582
Douglas Gregora57478e2010-05-01 15:04:51 +00006583 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006584 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00006585 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006586 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006587 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00006588 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00006589 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00006590 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00006591 }
Douglas Gregor73193272010-09-20 16:48:21 +00006592
6593 SourceLocation Loc = Constructor->getLocation();
6594 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6595
6596 Constructor->setUsed();
6597 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006598
6599 if (ASTMutationListener *L = getASTMutationListener()) {
6600 L->CompletedImplicitDefinition(Constructor);
6601 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006602}
6603
Richard Smith938f40b2011-06-11 17:19:42 +00006604/// Get any existing defaulted default constructor for the given class. Do not
6605/// implicitly define one if it does not exist.
6606static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6607 CXXRecordDecl *D) {
6608 ASTContext &Context = Self.Context;
6609 QualType ClassType = Context.getTypeDeclType(D);
6610 DeclarationName ConstructorName
6611 = Context.DeclarationNames.getCXXConstructorName(
6612 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6613
6614 DeclContext::lookup_const_iterator Con, ConEnd;
6615 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6616 Con != ConEnd; ++Con) {
6617 // A function template cannot be defaulted.
6618 if (isa<FunctionTemplateDecl>(*Con))
6619 continue;
6620
6621 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6622 if (Constructor->isDefaultConstructor())
6623 return Constructor->isDefaulted() ? Constructor : 0;
6624 }
6625 return 0;
6626}
6627
6628void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6629 if (!D) return;
6630 AdjustDeclIfTemplate(D);
6631
6632 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6633 CXXConstructorDecl *CtorDecl
6634 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6635
6636 if (!CtorDecl) return;
6637
6638 // Compute the exception specification for the default constructor.
6639 const FunctionProtoType *CtorTy =
6640 CtorDecl->getType()->castAs<FunctionProtoType>();
6641 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6642 ImplicitExceptionSpecification Spec =
6643 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6644 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6645 assert(EPI.ExceptionSpecType != EST_Delayed);
6646
6647 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6648 }
6649
6650 // If the default constructor is explicitly defaulted, checking the exception
6651 // specification is deferred until now.
6652 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6653 !ClassDecl->isDependentType())
6654 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6655}
6656
Sebastian Redl08905022011-02-05 19:23:19 +00006657void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6658 // We start with an initial pass over the base classes to collect those that
6659 // inherit constructors from. If there are none, we can forgo all further
6660 // processing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006661 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redl08905022011-02-05 19:23:19 +00006662 BasesVector BasesToInheritFrom;
6663 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6664 BaseE = ClassDecl->bases_end();
6665 BaseIt != BaseE; ++BaseIt) {
6666 if (BaseIt->getInheritConstructors()) {
6667 QualType Base = BaseIt->getType();
6668 if (Base->isDependentType()) {
6669 // If we inherit constructors from anything that is dependent, just
6670 // abort processing altogether. We'll get another chance for the
6671 // instantiations.
6672 return;
6673 }
6674 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6675 }
6676 }
6677 if (BasesToInheritFrom.empty())
6678 return;
6679
6680 // Now collect the constructors that we already have in the current class.
6681 // Those take precedence over inherited constructors.
6682 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6683 // unless there is a user-declared constructor with the same signature in
6684 // the class where the using-declaration appears.
6685 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6686 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6687 CtorE = ClassDecl->ctor_end();
6688 CtorIt != CtorE; ++CtorIt) {
6689 ExistingConstructors.insert(
6690 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6691 }
6692
6693 Scope *S = getScopeForContext(ClassDecl);
6694 DeclarationName CreatedCtorName =
6695 Context.DeclarationNames.getCXXConstructorName(
6696 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6697
6698 // Now comes the true work.
6699 // First, we keep a map from constructor types to the base that introduced
6700 // them. Needed for finding conflicting constructors. We also keep the
6701 // actually inserted declarations in there, for pretty diagnostics.
6702 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6703 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6704 ConstructorToSourceMap InheritedConstructors;
6705 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6706 BaseE = BasesToInheritFrom.end();
6707 BaseIt != BaseE; ++BaseIt) {
6708 const RecordType *Base = *BaseIt;
6709 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6710 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6711 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6712 CtorE = BaseDecl->ctor_end();
6713 CtorIt != CtorE; ++CtorIt) {
6714 // Find the using declaration for inheriting this base's constructors.
6715 DeclarationName Name =
6716 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6717 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6718 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6719 SourceLocation UsingLoc = UD ? UD->getLocation() :
6720 ClassDecl->getLocation();
6721
6722 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6723 // from the class X named in the using-declaration consists of actual
6724 // constructors and notional constructors that result from the
6725 // transformation of defaulted parameters as follows:
6726 // - all non-template default constructors of X, and
6727 // - for each non-template constructor of X that has at least one
6728 // parameter with a default argument, the set of constructors that
6729 // results from omitting any ellipsis parameter specification and
6730 // successively omitting parameters with a default argument from the
6731 // end of the parameter-type-list.
6732 CXXConstructorDecl *BaseCtor = *CtorIt;
6733 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6734 const FunctionProtoType *BaseCtorType =
6735 BaseCtor->getType()->getAs<FunctionProtoType>();
6736
6737 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6738 maxParams = BaseCtor->getNumParams();
6739 params <= maxParams; ++params) {
6740 // Skip default constructors. They're never inherited.
6741 if (params == 0)
6742 continue;
6743 // Skip copy and move constructors for the same reason.
6744 if (CanBeCopyOrMove && params == 1)
6745 continue;
6746
6747 // Build up a function type for this particular constructor.
6748 // FIXME: The working paper does not consider that the exception spec
6749 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00006750 // source. This code doesn't yet, either. When it does, this code will
6751 // need to be delayed until after exception specifications and in-class
6752 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00006753 const Type *NewCtorType;
6754 if (params == maxParams)
6755 NewCtorType = BaseCtorType;
6756 else {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006757 SmallVector<QualType, 16> Args;
Sebastian Redl08905022011-02-05 19:23:19 +00006758 for (unsigned i = 0; i < params; ++i) {
6759 Args.push_back(BaseCtorType->getArgType(i));
6760 }
6761 FunctionProtoType::ExtProtoInfo ExtInfo =
6762 BaseCtorType->getExtProtoInfo();
6763 ExtInfo.Variadic = false;
6764 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6765 Args.data(), params, ExtInfo)
6766 .getTypePtr();
6767 }
6768 const Type *CanonicalNewCtorType =
6769 Context.getCanonicalType(NewCtorType);
6770
6771 // Now that we have the type, first check if the class already has a
6772 // constructor with this signature.
6773 if (ExistingConstructors.count(CanonicalNewCtorType))
6774 continue;
6775
6776 // Then we check if we have already declared an inherited constructor
6777 // with this signature.
6778 std::pair<ConstructorToSourceMap::iterator, bool> result =
6779 InheritedConstructors.insert(std::make_pair(
6780 CanonicalNewCtorType,
6781 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6782 if (!result.second) {
6783 // Already in the map. If it came from a different class, that's an
6784 // error. Not if it's from the same.
6785 CanQualType PreviousBase = result.first->second.first;
6786 if (CanonicalBase != PreviousBase) {
6787 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6788 const CXXConstructorDecl *PrevBaseCtor =
6789 PrevCtor->getInheritedConstructor();
6790 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6791
6792 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6793 Diag(BaseCtor->getLocation(),
6794 diag::note_using_decl_constructor_conflict_current_ctor);
6795 Diag(PrevBaseCtor->getLocation(),
6796 diag::note_using_decl_constructor_conflict_previous_ctor);
6797 Diag(PrevCtor->getLocation(),
6798 diag::note_using_decl_constructor_conflict_previous_using);
6799 }
6800 continue;
6801 }
6802
6803 // OK, we're there, now add the constructor.
6804 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smitha77a0a62011-08-15 21:04:07 +00006805 // user-written inline constructor [...]
Sebastian Redl08905022011-02-05 19:23:19 +00006806 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6807 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00006808 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6809 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00006810 /*ImplicitlyDeclared=*/true,
6811 // FIXME: Due to a defect in the standard, we treat inherited
6812 // constructors as constexpr even if that makes them ill-formed.
6813 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redl08905022011-02-05 19:23:19 +00006814 NewCtor->setAccess(BaseCtor->getAccess());
6815
6816 // Build up the parameter decls and add them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006817 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redl08905022011-02-05 19:23:19 +00006818 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006819 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6820 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00006821 /*IdentifierInfo=*/0,
6822 BaseCtorType->getArgType(i),
6823 /*TInfo=*/0, SC_None,
6824 SC_None, /*DefaultArg=*/0));
6825 }
David Blaikie9c70e042011-09-21 18:16:56 +00006826 NewCtor->setParams(ParamDecls);
Sebastian Redl08905022011-02-05 19:23:19 +00006827 NewCtor->setInheritedConstructor(BaseCtor);
6828
6829 PushOnScopeChains(NewCtor, S, false);
6830 ClassDecl->addDecl(NewCtor);
6831 result.first->second.second = NewCtor;
6832 }
6833 }
6834 }
6835}
6836
Alexis Huntf91729462011-05-12 22:46:25 +00006837Sema::ImplicitExceptionSpecification
6838Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00006839 // C++ [except.spec]p14:
6840 // An implicitly declared special member function (Clause 12) shall have
6841 // an exception-specification.
6842 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006843 if (ClassDecl->isInvalidDecl())
6844 return ExceptSpec;
6845
Douglas Gregorf1203042010-07-01 19:09:28 +00006846 // Direct base-class destructors.
6847 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6848 BEnd = ClassDecl->bases_end();
6849 B != BEnd; ++B) {
6850 if (B->isVirtual()) // Handled below.
6851 continue;
6852
6853 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6854 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006855 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006856 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006857
Douglas Gregorf1203042010-07-01 19:09:28 +00006858 // Virtual base-class destructors.
6859 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6860 BEnd = ClassDecl->vbases_end();
6861 B != BEnd; ++B) {
6862 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6863 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006864 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006865 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006866
Douglas Gregorf1203042010-07-01 19:09:28 +00006867 // Field destructors.
6868 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6869 FEnd = ClassDecl->field_end();
6870 F != FEnd; ++F) {
6871 if (const RecordType *RecordTy
6872 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6873 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006874 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006875 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006876
Alexis Huntf91729462011-05-12 22:46:25 +00006877 return ExceptSpec;
6878}
6879
6880CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6881 // C++ [class.dtor]p2:
6882 // If a class has no user-declared destructor, a destructor is
6883 // declared implicitly. An implicitly-declared destructor is an
6884 // inline public member of its class.
6885
6886 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00006887 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00006888 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6889
Douglas Gregor7454c562010-07-02 20:37:36 +00006890 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00006891 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006892
Douglas Gregorf1203042010-07-01 19:09:28 +00006893 CanQualType ClassType
6894 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006895 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00006896 DeclarationName Name
6897 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006898 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00006899 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006900 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6901 /*isInline=*/true,
6902 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00006903 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00006904 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00006905 Destructor->setImplicit();
6906 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00006907
6908 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00006909 ++ASTContext::NumImplicitDestructorsDeclared;
6910
6911 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006912 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00006913 PushOnScopeChains(Destructor, S, false);
6914 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00006915
6916 // This could be uniqued if it ever proves significant.
6917 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00006918
6919 if (ShouldDeleteDestructor(Destructor))
6920 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00006921
6922 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00006923
Douglas Gregorf1203042010-07-01 19:09:28 +00006924 return Destructor;
6925}
6926
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006927void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00006928 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006929 assert((Destructor->isDefaulted() &&
6930 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006931 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00006932 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006933 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006934
Douglas Gregor54818f02010-05-12 16:39:35 +00006935 if (Destructor->isInvalidDecl())
6936 return;
6937
Douglas Gregora57478e2010-05-01 15:04:51 +00006938 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006939
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006940 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00006941 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6942 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00006943
Douglas Gregor54818f02010-05-12 16:39:35 +00006944 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006945 Diag(CurrentLocation, diag::note_member_synthesized_at)
6946 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6947
6948 Destructor->setInvalidDecl();
6949 return;
6950 }
6951
Douglas Gregor73193272010-09-20 16:48:21 +00006952 SourceLocation Loc = Destructor->getLocation();
6953 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregoreb4089a2011-09-22 20:32:43 +00006954 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006955 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006956 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006957
6958 if (ASTMutationListener *L = getASTMutationListener()) {
6959 L->CompletedImplicitDefinition(Destructor);
6960 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006961}
6962
Sebastian Redl623ea822011-05-19 05:13:44 +00006963void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6964 CXXDestructorDecl *destructor) {
6965 // C++11 [class.dtor]p3:
6966 // A declaration of a destructor that does not have an exception-
6967 // specification is implicitly considered to have the same exception-
6968 // specification as an implicit declaration.
6969 const FunctionProtoType *dtorType = destructor->getType()->
6970 getAs<FunctionProtoType>();
6971 if (dtorType->hasExceptionSpec())
6972 return;
6973
6974 ImplicitExceptionSpecification exceptSpec =
6975 ComputeDefaultedDtorExceptionSpec(classDecl);
6976
Chandler Carruth9a797572011-09-20 04:55:26 +00006977 // Replace the destructor's type, building off the existing one. Fortunately,
6978 // the only thing of interest in the destructor type is its extended info.
6979 // The return and arguments are fixed.
6980 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl623ea822011-05-19 05:13:44 +00006981 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6982 epi.NumExceptions = exceptSpec.size();
6983 epi.Exceptions = exceptSpec.data();
6984 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6985
6986 destructor->setType(ty);
6987
6988 // FIXME: If the destructor has a body that could throw, and the newly created
6989 // spec doesn't allow exceptions, we should emit a warning, because this
6990 // change in behavior can break conforming C++03 programs at runtime.
6991 // However, we don't have a body yet, so it needs to be done somewhere else.
6992}
6993
Sebastian Redl22653ba2011-08-30 19:58:05 +00006994/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00006995/// \c To.
6996///
Sebastian Redl22653ba2011-08-30 19:58:05 +00006997/// This routine is used to copy/move the members of a class with an
6998/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00006999/// copied are arrays, this routine builds for loops to copy them.
7000///
7001/// \param S The Sema object used for type-checking.
7002///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007003/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007004///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007005/// \param T The type of the expressions being copied/moved. Both expressions
7006/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007007///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007008/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007009///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007010/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007011///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007012/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007013/// Otherwise, it's a non-static member subobject.
7014///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007015/// \param Copying Whether we're copying or moving.
7016///
Douglas Gregorb139cd52010-05-01 20:49:11 +00007017/// \param Depth Internal parameter recording the depth of the recursion.
7018///
7019/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00007020static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00007021BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00007022 Expr *To, Expr *From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007023 bool CopyingBaseSubobject, bool Copying,
7024 unsigned Depth = 0) {
7025 // C++0x [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00007026 // Each subobject is assigned in the manner appropriate to its type:
7027 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00007028 // - if the subobject is of class type, as if by a call to operator= with
7029 // the subobject as the object expression and the corresponding
7030 // subobject of x as a single function argument (as if by explicit
7031 // qualification; that is, ignoring any possible virtual overriding
7032 // functions in more derived classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007033 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7034 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7035
7036 // Look for operator=.
7037 DeclarationName Name
7038 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7039 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7040 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7041
Sebastian Redl22653ba2011-08-30 19:58:05 +00007042 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007043 LookupResult::Filter F = OpLookup.makeFilter();
7044 while (F.hasNext()) {
7045 NamedDecl *D = F.next();
7046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl22653ba2011-08-30 19:58:05 +00007047 if (Copying ? Method->isCopyAssignmentOperator() :
7048 Method->isMoveAssignmentOperator())
Douglas Gregorb139cd52010-05-01 20:49:11 +00007049 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00007050
Douglas Gregorb139cd52010-05-01 20:49:11 +00007051 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00007052 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007053 F.done();
7054
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007055 // Suppress the protected check (C++ [class.protected]) for each of the
7056 // assignment operators we found. This strange dance is required when
7057 // we're assigning via a base classes's copy-assignment operator. To
7058 // ensure that we're getting the right base class subobject (without
7059 // ambiguities), we need to cast "this" to that subobject type; to
7060 // ensure that we don't go through the virtual call mechanism, we need
7061 // to qualify the operator= name with the base class (see below). However,
7062 // this means that if the base class has a protected copy assignment
7063 // operator, the protected member access check will fail. So, we
7064 // rewrite "protected" access to "public" access in this case, since we
7065 // know by construction that we're calling from a derived class.
7066 if (CopyingBaseSubobject) {
7067 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7068 L != LEnd; ++L) {
7069 if (L.getAccess() == AS_protected)
7070 L.setAccess(AS_public);
7071 }
7072 }
7073
Douglas Gregorb139cd52010-05-01 20:49:11 +00007074 // Create the nested-name-specifier that will be used to qualify the
7075 // reference to operator=; this is required to suppress the virtual
7076 // call mechanism.
7077 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00007078 SS.MakeTrivial(S.Context,
7079 NestedNameSpecifier::Create(S.Context, 0, false,
7080 T.getTypePtr()),
7081 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007082
7083 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00007084 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00007085 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007086 /*FirstQualifierInScope=*/0, OpLookup,
7087 /*TemplateArgs=*/0,
7088 /*SuppressQualifierCheck=*/true);
7089 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007090 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007091
7092 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00007093
John McCalldadc5752010-08-24 06:29:42 +00007094 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007095 OpEqualRef.takeAs<Expr>(),
7096 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007097 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007098 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007099
7100 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007101 }
John McCallab8c2732010-03-16 06:11:48 +00007102
Douglas Gregorb139cd52010-05-01 20:49:11 +00007103 // - if the subobject is of scalar type, the built-in assignment
7104 // operator is used.
7105 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7106 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00007107 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007108 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007109 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007110
7111 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007112 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007113
7114 // - if the subobject is an array, each element is assigned, in the
7115 // manner appropriate to the element type;
7116
7117 // Construct a loop over the array bounds, e.g.,
7118 //
7119 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7120 //
7121 // that will copy each of the array elements.
7122 QualType SizeType = S.Context.getSizeType();
7123
7124 // Create the iteration variable.
7125 IdentifierInfo *IterationVarName = 0;
7126 {
7127 llvm::SmallString<8> Str;
7128 llvm::raw_svector_ostream OS(Str);
7129 OS << "__i" << Depth;
7130 IterationVarName = &S.Context.Idents.get(OS.str());
7131 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00007132 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007133 IterationVarName, SizeType,
7134 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007135 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007136
7137 // Initialize the iteration variable to zero.
7138 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007139 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00007140
7141 // Create a reference to the iteration variable; we'll use this several
7142 // times throughout.
7143 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00007144 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007145 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7146
7147 // Create the DeclStmt that holds the iteration variable.
7148 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7149
7150 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007151 llvm::APInt Upper
7152 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00007153 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00007154 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00007155 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7156 BO_NE, S.Context.BoolTy,
7157 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007158
7159 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007160 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00007161 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7162 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007163
7164 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007165 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7166 IterationVarRef, Loc));
7167 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7168 IterationVarRef, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00007169 if (!Copying) // Cast to rvalue
7170 From = CastForMoving(S, From);
7171
7172 // Build the copy/move for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00007173 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7174 To, From, CopyingBaseSubobject,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007175 Copying, Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00007176 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007177 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007178
7179 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00007180 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007181 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00007182 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00007183 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007184}
7185
Alexis Hunt119f3652011-05-14 05:23:20 +00007186std::pair<Sema::ImplicitExceptionSpecification, bool>
7187Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7188 CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007189 if (ClassDecl->isInvalidDecl())
7190 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7191
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007192 // C++ [class.copy]p10:
7193 // If the class definition does not explicitly declare a copy
7194 // assignment operator, one is declared implicitly.
7195 // The implicitly-defined copy assignment operator for a class X
7196 // will have the form
7197 //
7198 // X& X::operator=(const X&)
7199 //
7200 // if
7201 bool HasConstCopyAssignment = true;
7202
7203 // -- each direct base class B of X has a copy assignment operator
7204 // whose parameter is of type const B&, const volatile B& or B,
7205 // and
7206 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7207 BaseEnd = ClassDecl->bases_end();
7208 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007209 // We'll handle this below
7210 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7211 continue;
7212
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007213 assert(!Base->getType()->isDependentType() &&
7214 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00007215 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7216 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7217 &HasConstCopyAssignment);
7218 }
7219
7220 // In C++0x, the above citation has "or virtual added"
7221 if (LangOpts.CPlusPlus0x) {
7222 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7223 BaseEnd = ClassDecl->vbases_end();
7224 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7225 assert(!Base->getType()->isDependentType() &&
7226 "Cannot generate implicit members for class with dependent bases.");
7227 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7228 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7229 &HasConstCopyAssignment);
7230 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007231 }
7232
7233 // -- for all the nonstatic data members of X that are of a class
7234 // type M (or array thereof), each such class type has a copy
7235 // assignment operator whose parameter is of type const M&,
7236 // const volatile M& or M.
7237 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7238 FieldEnd = ClassDecl->field_end();
7239 HasConstCopyAssignment && Field != FieldEnd;
7240 ++Field) {
7241 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007242 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7243 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7244 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007245 }
7246 }
7247
7248 // Otherwise, the implicitly declared copy assignment operator will
7249 // have the form
7250 //
7251 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007252
Douglas Gregor68e11362010-07-01 17:48:08 +00007253 // C++ [except.spec]p14:
7254 // An implicitly declared special member function (Clause 12) shall have an
7255 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00007256
7257 // It is unspecified whether or not an implicit copy assignment operator
7258 // attempts to deduplicate calls to assignment operators of virtual bases are
7259 // made. As such, this exception specification is effectively unspecified.
7260 // Based on a similar decision made for constness in C++0x, we're erring on
7261 // the side of assuming such calls to be made regardless of whether they
7262 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00007263 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00007264 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00007265 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7266 BaseEnd = ClassDecl->bases_end();
7267 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007268 if (Base->isVirtual())
7269 continue;
7270
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007271 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00007272 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007273 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7274 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00007275 ExceptSpec.CalledDecl(CopyAssign);
7276 }
Alexis Hunt491ec602011-06-21 23:42:56 +00007277
7278 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7279 BaseEnd = ClassDecl->vbases_end();
7280 Base != BaseEnd; ++Base) {
7281 CXXRecordDecl *BaseClassDecl
7282 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7283 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7284 ArgQuals, false, 0))
7285 ExceptSpec.CalledDecl(CopyAssign);
7286 }
7287
Douglas Gregor68e11362010-07-01 17:48:08 +00007288 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7289 FieldEnd = ClassDecl->field_end();
7290 Field != FieldEnd;
7291 ++Field) {
7292 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007293 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7294 if (CXXMethodDecl *CopyAssign =
7295 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7296 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007297 }
Douglas Gregor68e11362010-07-01 17:48:08 +00007298 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007299
Alexis Hunt119f3652011-05-14 05:23:20 +00007300 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7301}
7302
7303CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7304 // Note: The following rules are largely analoguous to the copy
7305 // constructor rules. Note that virtual bases are not taken into account
7306 // for determining the argument type of the operator. Note also that
7307 // operators taking an object instead of a reference are allowed.
7308
7309 ImplicitExceptionSpecification Spec(Context);
7310 bool Const;
7311 llvm::tie(Spec, Const) =
7312 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7313
7314 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7315 QualType RetType = Context.getLValueReferenceType(ArgType);
7316 if (Const)
7317 ArgType = ArgType.withConst();
7318 ArgType = Context.getLValueReferenceType(ArgType);
7319
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007320 // An implicitly-declared copy assignment operator is an inline public
7321 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00007322 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007323 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007324 SourceLocation ClassLoc = ClassDecl->getLocation();
7325 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007326 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00007327 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00007328 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007329 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00007330 /*StorageClassAsWritten=*/SC_None,
Richard Smitha77a0a62011-08-15 21:04:07 +00007331 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf2f08062011-03-08 17:10:18 +00007332 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007333 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00007334 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007335 CopyAssignment->setImplicit();
7336 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007337
7338 // Add the parameter to the operator.
7339 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007340 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007341 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007342 SC_None,
7343 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007344 CopyAssignment->setParams(FromParam);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007345
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007346 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007347 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00007348
Douglas Gregor0be31a22010-07-02 17:43:08 +00007349 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007350 PushOnScopeChains(CopyAssignment, S, false);
7351 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007352
Alexis Huntd74c85f2011-06-22 01:05:13 +00007353 // C++0x [class.copy]p18:
7354 // ... If the class definition declares a move constructor or move
7355 // assignment operator, the implicitly declared copy assignment operator is
7356 // defined as deleted; ...
7357 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7358 ClassDecl->hasUserDeclaredMoveAssignment() ||
7359 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007360 CopyAssignment->setDeletedAsWritten();
7361
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007362 AddOverriddenMethods(ClassDecl, CopyAssignment);
7363 return CopyAssignment;
7364}
7365
Douglas Gregorb139cd52010-05-01 20:49:11 +00007366void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7367 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00007368 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007369 CopyAssignOperator->isOverloadedOperator() &&
7370 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007371 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007372 "DefineImplicitCopyAssignment called for wrong function");
7373
7374 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7375
7376 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7377 CopyAssignOperator->setInvalidDecl();
7378 return;
7379 }
7380
7381 CopyAssignOperator->setUsed();
7382
7383 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007384 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007385
7386 // C++0x [class.copy]p30:
7387 // The implicitly-defined or explicitly-defaulted copy assignment operator
7388 // for a non-union class X performs memberwise copy assignment of its
7389 // subobjects. The direct base classes of X are assigned first, in the
7390 // order of their declaration in the base-specifier-list, and then the
7391 // immediate non-static data members of X are assigned, in the order in
7392 // which they were declared in the class definition.
7393
7394 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00007395 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007396
7397 // The parameter for the "other" object, which we are copying from.
7398 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7399 Qualifiers OtherQuals = Other->getType().getQualifiers();
7400 QualType OtherRefType = Other->getType();
7401 if (const LValueReferenceType *OtherRef
7402 = OtherRefType->getAs<LValueReferenceType>()) {
7403 OtherRefType = OtherRef->getPointeeType();
7404 OtherQuals = OtherRefType.getQualifiers();
7405 }
7406
7407 // Our location for everything implicitly-generated.
7408 SourceLocation Loc = CopyAssignOperator->getLocation();
7409
7410 // Construct a reference to the "other" object. We'll be using this
7411 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00007412 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007413 assert(OtherRef && "Reference to parameter cannot fail!");
7414
7415 // Construct the "this" pointer. We'll be using this throughout the generated
7416 // ASTs.
7417 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7418 assert(This && "Reference to this cannot fail!");
7419
7420 // Assign base classes.
7421 bool Invalid = false;
7422 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7423 E = ClassDecl->bases_end(); Base != E; ++Base) {
7424 // Form the assignment:
7425 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7426 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00007427 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007428 Invalid = true;
7429 continue;
7430 }
7431
John McCallcf142162010-08-07 06:22:56 +00007432 CXXCastPath BasePath;
7433 BasePath.push_back(Base);
7434
Douglas Gregorb139cd52010-05-01 20:49:11 +00007435 // Construct the "from" expression, which is an implicit cast to the
7436 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00007437 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00007438 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7439 CK_UncheckedDerivedToBase,
7440 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007441
7442 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00007443 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007444
7445 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00007446 To = ImpCastExprToType(To.take(),
7447 Context.getCVRQualifiedType(BaseType,
7448 CopyAssignOperator->getTypeQualifiers()),
7449 CK_UncheckedDerivedToBase,
7450 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007451
7452 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00007453 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00007454 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007455 /*CopyingBaseSubobject=*/true,
7456 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007457 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007458 Diag(CurrentLocation, diag::note_member_synthesized_at)
7459 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7460 CopyAssignOperator->setInvalidDecl();
7461 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007462 }
7463
7464 // Success! Record the copy.
7465 Statements.push_back(Copy.takeAs<Expr>());
7466 }
7467
7468 // \brief Reference to the __builtin_memcpy function.
7469 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007470 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007471 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007472
7473 // Assign non-static members.
7474 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7475 FieldEnd = ClassDecl->field_end();
7476 Field != FieldEnd; ++Field) {
7477 // Check for members of reference type; we can't copy those.
7478 if (Field->getType()->isReferenceType()) {
7479 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7480 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7481 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007482 Diag(CurrentLocation, diag::note_member_synthesized_at)
7483 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007484 Invalid = true;
7485 continue;
7486 }
7487
7488 // Check for members of const-qualified, non-class type.
7489 QualType BaseType = Context.getBaseElementType(Field->getType());
7490 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7491 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7492 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7493 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007494 Diag(CurrentLocation, diag::note_member_synthesized_at)
7495 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007496 Invalid = true;
7497 continue;
7498 }
John McCall1b1a1db2011-06-17 00:18:42 +00007499
7500 // Suppress assigning zero-width bitfields.
7501 if (const Expr *Width = Field->getBitWidth())
7502 if (Width->EvaluateAsInt(Context) == 0)
7503 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007504
7505 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007506 if (FieldType->isIncompleteArrayType()) {
7507 assert(ClassDecl->hasFlexibleArrayMember() &&
7508 "Incomplete array type is not valid");
7509 continue;
7510 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007511
7512 // Build references to the field in the object we're copying from and to.
7513 CXXScopeSpec SS; // Intentionally empty
7514 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7515 LookupMemberName);
7516 MemberLookup.addDecl(*Field);
7517 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00007518 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00007519 Loc, /*IsArrow=*/false,
7520 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00007521 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00007522 Loc, /*IsArrow=*/true,
7523 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007524 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7525 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7526
7527 // If the field should be copied with __builtin_memcpy rather than via
7528 // explicit assignments, do so. This optimization only applies for arrays
7529 // of scalars and arrays of class type with trivial copy-assignment
7530 // operators.
Fariborz Jahanianc1a151b2011-08-09 00:26:11 +00007531 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl22653ba2011-08-30 19:58:05 +00007532 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007533 // Compute the size of the memory buffer to be copied.
7534 QualType SizeType = Context.getSizeType();
7535 llvm::APInt Size(Context.getTypeSize(SizeType),
7536 Context.getTypeSizeInChars(BaseType).getQuantity());
7537 for (const ConstantArrayType *Array
7538 = Context.getAsConstantArrayType(FieldType);
7539 Array;
7540 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00007541 llvm::APInt ArraySize
7542 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007543 Size *= ArraySize;
7544 }
7545
7546 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00007547 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7548 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007549
7550 bool NeedsCollectableMemCpy =
7551 (BaseType->isRecordType() &&
7552 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7553
7554 if (NeedsCollectableMemCpy) {
7555 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007556 // Create a reference to the __builtin_objc_memmove_collectable function.
7557 LookupResult R(*this,
7558 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007559 Loc, LookupOrdinaryName);
7560 LookupName(R, TUScope, true);
7561
7562 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7563 if (!CollectableMemCpy) {
7564 // Something went horribly wrong earlier, and we will have
7565 // complained about it.
7566 Invalid = true;
7567 continue;
7568 }
7569
7570 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7571 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007572 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007573 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7574 }
7575 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007576 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007577 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007578 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7579 LookupOrdinaryName);
7580 LookupName(R, TUScope, true);
7581
7582 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7583 if (!BuiltinMemCpy) {
7584 // Something went horribly wrong earlier, and we will have complained
7585 // about it.
7586 Invalid = true;
7587 continue;
7588 }
7589
7590 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7591 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007592 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007593 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7594 }
7595
John McCall37ad5512010-08-23 06:44:23 +00007596 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007597 CallArgs.push_back(To.takeAs<Expr>());
7598 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007599 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00007600 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007601 if (NeedsCollectableMemCpy)
7602 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007603 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007604 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007605 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007606 else
7607 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007608 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007609 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007610 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007611
Douglas Gregorb139cd52010-05-01 20:49:11 +00007612 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7613 Statements.push_back(Call.takeAs<Expr>());
7614 continue;
7615 }
7616
7617 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00007618 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007619 To.get(), From.get(),
7620 /*CopyingBaseSubobject=*/false,
7621 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007622 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007623 Diag(CurrentLocation, diag::note_member_synthesized_at)
7624 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7625 CopyAssignOperator->setInvalidDecl();
7626 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007627 }
7628
7629 // Success! Record the copy.
7630 Statements.push_back(Copy.takeAs<Stmt>());
7631 }
7632
7633 if (!Invalid) {
7634 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00007635 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007636
John McCalldadc5752010-08-24 06:29:42 +00007637 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007638 if (Return.isInvalid())
7639 Invalid = true;
7640 else {
7641 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00007642
7643 if (Trap.hasErrorOccurred()) {
7644 Diag(CurrentLocation, diag::note_member_synthesized_at)
7645 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7646 Invalid = true;
7647 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007648 }
7649 }
7650
7651 if (Invalid) {
7652 CopyAssignOperator->setInvalidDecl();
7653 return;
7654 }
7655
John McCalldadc5752010-08-24 06:29:42 +00007656 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00007657 /*isStmtExpr=*/false);
7658 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7659 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00007660
7661 if (ASTMutationListener *L = getASTMutationListener()) {
7662 L->CompletedImplicitDefinition(CopyAssignOperator);
7663 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007664}
7665
Sebastian Redl22653ba2011-08-30 19:58:05 +00007666Sema::ImplicitExceptionSpecification
7667Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7668 ImplicitExceptionSpecification ExceptSpec(Context);
7669
7670 if (ClassDecl->isInvalidDecl())
7671 return ExceptSpec;
7672
7673 // C++0x [except.spec]p14:
7674 // An implicitly declared special member function (Clause 12) shall have an
7675 // exception-specification. [...]
7676
7677 // It is unspecified whether or not an implicit move assignment operator
7678 // attempts to deduplicate calls to assignment operators of virtual bases are
7679 // made. As such, this exception specification is effectively unspecified.
7680 // Based on a similar decision made for constness in C++0x, we're erring on
7681 // the side of assuming such calls to be made regardless of whether they
7682 // actually happen.
7683 // Note that a move constructor is not implicitly declared when there are
7684 // virtual bases, but it can still be user-declared and explicitly defaulted.
7685 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7686 BaseEnd = ClassDecl->bases_end();
7687 Base != BaseEnd; ++Base) {
7688 if (Base->isVirtual())
7689 continue;
7690
7691 CXXRecordDecl *BaseClassDecl
7692 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7693 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7694 false, 0))
7695 ExceptSpec.CalledDecl(MoveAssign);
7696 }
7697
7698 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7699 BaseEnd = ClassDecl->vbases_end();
7700 Base != BaseEnd; ++Base) {
7701 CXXRecordDecl *BaseClassDecl
7702 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7703 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7704 false, 0))
7705 ExceptSpec.CalledDecl(MoveAssign);
7706 }
7707
7708 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7709 FieldEnd = ClassDecl->field_end();
7710 Field != FieldEnd;
7711 ++Field) {
7712 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7713 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7714 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7715 false, 0))
7716 ExceptSpec.CalledDecl(MoveAssign);
7717 }
7718 }
7719
7720 return ExceptSpec;
7721}
7722
7723CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7724 // Note: The following rules are largely analoguous to the move
7725 // constructor rules.
7726
7727 ImplicitExceptionSpecification Spec(
7728 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7729
7730 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7731 QualType RetType = Context.getLValueReferenceType(ArgType);
7732 ArgType = Context.getRValueReferenceType(ArgType);
7733
7734 // An implicitly-declared move assignment operator is an inline public
7735 // member of its class.
7736 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7737 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7738 SourceLocation ClassLoc = ClassDecl->getLocation();
7739 DeclarationNameInfo NameInfo(Name, ClassLoc);
7740 CXXMethodDecl *MoveAssignment
7741 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7742 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7743 /*TInfo=*/0, /*isStatic=*/false,
7744 /*StorageClassAsWritten=*/SC_None,
7745 /*isInline=*/true,
7746 /*isConstexpr=*/false,
7747 SourceLocation());
7748 MoveAssignment->setAccess(AS_public);
7749 MoveAssignment->setDefaulted();
7750 MoveAssignment->setImplicit();
7751 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7752
7753 // Add the parameter to the operator.
7754 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7755 ClassLoc, ClassLoc, /*Id=*/0,
7756 ArgType, /*TInfo=*/0,
7757 SC_None,
7758 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007759 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00007760
7761 // Note that we have added this copy-assignment operator.
7762 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7763
7764 // C++0x [class.copy]p9:
7765 // If the definition of a class X does not explicitly declare a move
7766 // assignment operator, one will be implicitly declared as defaulted if and
7767 // only if:
7768 // [...]
7769 // - the move assignment operator would not be implicitly defined as
7770 // deleted.
7771 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7772 // Cache this result so that we don't try to generate this over and over
7773 // on every lookup, leaking memory and wasting time.
7774 ClassDecl->setFailedImplicitMoveAssignment();
7775 return 0;
7776 }
7777
7778 if (Scope *S = getScopeForContext(ClassDecl))
7779 PushOnScopeChains(MoveAssignment, S, false);
7780 ClassDecl->addDecl(MoveAssignment);
7781
7782 AddOverriddenMethods(ClassDecl, MoveAssignment);
7783 return MoveAssignment;
7784}
7785
7786void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7787 CXXMethodDecl *MoveAssignOperator) {
7788 assert((MoveAssignOperator->isDefaulted() &&
7789 MoveAssignOperator->isOverloadedOperator() &&
7790 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7791 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7792 "DefineImplicitMoveAssignment called for wrong function");
7793
7794 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7795
7796 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7797 MoveAssignOperator->setInvalidDecl();
7798 return;
7799 }
7800
7801 MoveAssignOperator->setUsed();
7802
7803 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7804 DiagnosticErrorTrap Trap(Diags);
7805
7806 // C++0x [class.copy]p28:
7807 // The implicitly-defined or move assignment operator for a non-union class
7808 // X performs memberwise move assignment of its subobjects. The direct base
7809 // classes of X are assigned first, in the order of their declaration in the
7810 // base-specifier-list, and then the immediate non-static data members of X
7811 // are assigned, in the order in which they were declared in the class
7812 // definition.
7813
7814 // The statements that form the synthesized function body.
7815 ASTOwningVector<Stmt*> Statements(*this);
7816
7817 // The parameter for the "other" object, which we are move from.
7818 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7819 QualType OtherRefType = Other->getType()->
7820 getAs<RValueReferenceType>()->getPointeeType();
7821 assert(OtherRefType.getQualifiers() == 0 &&
7822 "Bad argument type of defaulted move assignment");
7823
7824 // Our location for everything implicitly-generated.
7825 SourceLocation Loc = MoveAssignOperator->getLocation();
7826
7827 // Construct a reference to the "other" object. We'll be using this
7828 // throughout the generated ASTs.
7829 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7830 assert(OtherRef && "Reference to parameter cannot fail!");
7831 // Cast to rvalue.
7832 OtherRef = CastForMoving(*this, OtherRef);
7833
7834 // Construct the "this" pointer. We'll be using this throughout the generated
7835 // ASTs.
7836 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7837 assert(This && "Reference to this cannot fail!");
7838
7839 // Assign base classes.
7840 bool Invalid = false;
7841 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7842 E = ClassDecl->bases_end(); Base != E; ++Base) {
7843 // Form the assignment:
7844 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7845 QualType BaseType = Base->getType().getUnqualifiedType();
7846 if (!BaseType->isRecordType()) {
7847 Invalid = true;
7848 continue;
7849 }
7850
7851 CXXCastPath BasePath;
7852 BasePath.push_back(Base);
7853
7854 // Construct the "from" expression, which is an implicit cast to the
7855 // appropriately-qualified base type.
7856 Expr *From = OtherRef;
7857 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00007858 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00007859
7860 // Dereference "this".
7861 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7862
7863 // Implicitly cast "this" to the appropriately-qualified base type.
7864 To = ImpCastExprToType(To.take(),
7865 Context.getCVRQualifiedType(BaseType,
7866 MoveAssignOperator->getTypeQualifiers()),
7867 CK_UncheckedDerivedToBase,
7868 VK_LValue, &BasePath);
7869
7870 // Build the move.
7871 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7872 To.get(), From,
7873 /*CopyingBaseSubobject=*/true,
7874 /*Copying=*/false);
7875 if (Move.isInvalid()) {
7876 Diag(CurrentLocation, diag::note_member_synthesized_at)
7877 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7878 MoveAssignOperator->setInvalidDecl();
7879 return;
7880 }
7881
7882 // Success! Record the move.
7883 Statements.push_back(Move.takeAs<Expr>());
7884 }
7885
7886 // \brief Reference to the __builtin_memcpy function.
7887 Expr *BuiltinMemCpyRef = 0;
7888 // \brief Reference to the __builtin_objc_memmove_collectable function.
7889 Expr *CollectableMemCpyRef = 0;
7890
7891 // Assign non-static members.
7892 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7893 FieldEnd = ClassDecl->field_end();
7894 Field != FieldEnd; ++Field) {
7895 // Check for members of reference type; we can't move those.
7896 if (Field->getType()->isReferenceType()) {
7897 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7898 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7899 Diag(Field->getLocation(), diag::note_declared_at);
7900 Diag(CurrentLocation, diag::note_member_synthesized_at)
7901 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7902 Invalid = true;
7903 continue;
7904 }
7905
7906 // Check for members of const-qualified, non-class type.
7907 QualType BaseType = Context.getBaseElementType(Field->getType());
7908 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7909 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7910 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7911 Diag(Field->getLocation(), diag::note_declared_at);
7912 Diag(CurrentLocation, diag::note_member_synthesized_at)
7913 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7914 Invalid = true;
7915 continue;
7916 }
7917
7918 // Suppress assigning zero-width bitfields.
7919 if (const Expr *Width = Field->getBitWidth())
7920 if (Width->EvaluateAsInt(Context) == 0)
7921 continue;
7922
7923 QualType FieldType = Field->getType().getNonReferenceType();
7924 if (FieldType->isIncompleteArrayType()) {
7925 assert(ClassDecl->hasFlexibleArrayMember() &&
7926 "Incomplete array type is not valid");
7927 continue;
7928 }
7929
7930 // Build references to the field in the object we're copying from and to.
7931 CXXScopeSpec SS; // Intentionally empty
7932 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7933 LookupMemberName);
7934 MemberLookup.addDecl(*Field);
7935 MemberLookup.resolveKind();
7936 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7937 Loc, /*IsArrow=*/false,
7938 SS, 0, MemberLookup, 0);
7939 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7940 Loc, /*IsArrow=*/true,
7941 SS, 0, MemberLookup, 0);
7942 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7943 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7944
7945 assert(!From.get()->isLValue() && // could be xvalue or prvalue
7946 "Member reference with rvalue base must be rvalue except for reference "
7947 "members, which aren't allowed for move assignment.");
7948
7949 // If the field should be copied with __builtin_memcpy rather than via
7950 // explicit assignments, do so. This optimization only applies for arrays
7951 // of scalars and arrays of class type with trivial move-assignment
7952 // operators.
7953 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7954 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7955 // Compute the size of the memory buffer to be copied.
7956 QualType SizeType = Context.getSizeType();
7957 llvm::APInt Size(Context.getTypeSize(SizeType),
7958 Context.getTypeSizeInChars(BaseType).getQuantity());
7959 for (const ConstantArrayType *Array
7960 = Context.getAsConstantArrayType(FieldType);
7961 Array;
7962 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7963 llvm::APInt ArraySize
7964 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7965 Size *= ArraySize;
7966 }
7967
Douglas Gregor528499b2011-09-01 02:09:07 +00007968 // Take the address of the field references for "from" and "to". We
7969 // directly construct UnaryOperators here because semantic analysis
7970 // does not permit us to take the address of an xvalue.
7971 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
7972 Context.getPointerType(From.get()->getType()),
7973 VK_RValue, OK_Ordinary, Loc);
7974 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
7975 Context.getPointerType(To.get()->getType()),
7976 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00007977
7978 bool NeedsCollectableMemCpy =
7979 (BaseType->isRecordType() &&
7980 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7981
7982 if (NeedsCollectableMemCpy) {
7983 if (!CollectableMemCpyRef) {
7984 // Create a reference to the __builtin_objc_memmove_collectable function.
7985 LookupResult R(*this,
7986 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7987 Loc, LookupOrdinaryName);
7988 LookupName(R, TUScope, true);
7989
7990 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7991 if (!CollectableMemCpy) {
7992 // Something went horribly wrong earlier, and we will have
7993 // complained about it.
7994 Invalid = true;
7995 continue;
7996 }
7997
7998 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7999 CollectableMemCpy->getType(),
8000 VK_LValue, Loc, 0).take();
8001 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8002 }
8003 }
8004 // Create a reference to the __builtin_memcpy builtin function.
8005 else if (!BuiltinMemCpyRef) {
8006 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8007 LookupOrdinaryName);
8008 LookupName(R, TUScope, true);
8009
8010 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8011 if (!BuiltinMemCpy) {
8012 // Something went horribly wrong earlier, and we will have complained
8013 // about it.
8014 Invalid = true;
8015 continue;
8016 }
8017
8018 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8019 BuiltinMemCpy->getType(),
8020 VK_LValue, Loc, 0).take();
8021 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8022 }
8023
8024 ASTOwningVector<Expr*> CallArgs(*this);
8025 CallArgs.push_back(To.takeAs<Expr>());
8026 CallArgs.push_back(From.takeAs<Expr>());
8027 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8028 ExprResult Call = ExprError();
8029 if (NeedsCollectableMemCpy)
8030 Call = ActOnCallExpr(/*Scope=*/0,
8031 CollectableMemCpyRef,
8032 Loc, move_arg(CallArgs),
8033 Loc);
8034 else
8035 Call = ActOnCallExpr(/*Scope=*/0,
8036 BuiltinMemCpyRef,
8037 Loc, move_arg(CallArgs),
8038 Loc);
8039
8040 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8041 Statements.push_back(Call.takeAs<Expr>());
8042 continue;
8043 }
8044
8045 // Build the move of this field.
8046 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8047 To.get(), From.get(),
8048 /*CopyingBaseSubobject=*/false,
8049 /*Copying=*/false);
8050 if (Move.isInvalid()) {
8051 Diag(CurrentLocation, diag::note_member_synthesized_at)
8052 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8053 MoveAssignOperator->setInvalidDecl();
8054 return;
8055 }
8056
8057 // Success! Record the copy.
8058 Statements.push_back(Move.takeAs<Stmt>());
8059 }
8060
8061 if (!Invalid) {
8062 // Add a "return *this;"
8063 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8064
8065 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8066 if (Return.isInvalid())
8067 Invalid = true;
8068 else {
8069 Statements.push_back(Return.takeAs<Stmt>());
8070
8071 if (Trap.hasErrorOccurred()) {
8072 Diag(CurrentLocation, diag::note_member_synthesized_at)
8073 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8074 Invalid = true;
8075 }
8076 }
8077 }
8078
8079 if (Invalid) {
8080 MoveAssignOperator->setInvalidDecl();
8081 return;
8082 }
8083
8084 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8085 /*isStmtExpr=*/false);
8086 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8087 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8088
8089 if (ASTMutationListener *L = getASTMutationListener()) {
8090 L->CompletedImplicitDefinition(MoveAssignOperator);
8091 }
8092}
8093
Alexis Hunt913820d2011-05-13 06:10:58 +00008094std::pair<Sema::ImplicitExceptionSpecification, bool>
8095Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008096 if (ClassDecl->isInvalidDecl())
8097 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8098
Douglas Gregor54be3392010-07-01 17:57:27 +00008099 // C++ [class.copy]p5:
8100 // The implicitly-declared copy constructor for a class X will
8101 // have the form
8102 //
8103 // X::X(const X&)
8104 //
8105 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00008106 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00008107 bool HasConstCopyConstructor = true;
8108
8109 // -- each direct or virtual base class B of X has a copy
8110 // constructor whose first parameter is of type const B& or
8111 // const volatile B&, and
8112 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8113 BaseEnd = ClassDecl->bases_end();
8114 HasConstCopyConstructor && Base != BaseEnd;
8115 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008116 // Virtual bases are handled below.
8117 if (Base->isVirtual())
8118 continue;
8119
Douglas Gregora6d69502010-07-02 23:41:54 +00008120 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00008121 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008122 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8123 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00008124 }
8125
8126 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8127 BaseEnd = ClassDecl->vbases_end();
8128 HasConstCopyConstructor && Base != BaseEnd;
8129 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008130 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00008131 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008132 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8133 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008134 }
8135
8136 // -- for all the nonstatic data members of X that are of a
8137 // class type M (or array thereof), each such class type
8138 // has a copy constructor whose first parameter is of type
8139 // const M& or const volatile M&.
8140 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8141 FieldEnd = ClassDecl->field_end();
8142 HasConstCopyConstructor && Field != FieldEnd;
8143 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008144 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008145 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008146 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8147 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008148 }
8149 }
Douglas Gregor54be3392010-07-01 17:57:27 +00008150 // Otherwise, the implicitly declared copy constructor will have
8151 // the form
8152 //
8153 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00008154
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008155 // C++ [except.spec]p14:
8156 // An implicitly declared special member function (Clause 12) shall have an
8157 // exception-specification. [...]
8158 ImplicitExceptionSpecification ExceptSpec(Context);
8159 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8160 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8161 BaseEnd = ClassDecl->bases_end();
8162 Base != BaseEnd;
8163 ++Base) {
8164 // Virtual bases are handled below.
8165 if (Base->isVirtual())
8166 continue;
8167
Douglas Gregora6d69502010-07-02 23:41:54 +00008168 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008169 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008170 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008171 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008172 ExceptSpec.CalledDecl(CopyConstructor);
8173 }
8174 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8175 BaseEnd = ClassDecl->vbases_end();
8176 Base != BaseEnd;
8177 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008178 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008179 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008180 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008181 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008182 ExceptSpec.CalledDecl(CopyConstructor);
8183 }
8184 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8185 FieldEnd = ClassDecl->field_end();
8186 Field != FieldEnd;
8187 ++Field) {
8188 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008189 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8190 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008191 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00008192 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008193 }
8194 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008195
Alexis Hunt913820d2011-05-13 06:10:58 +00008196 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8197}
8198
8199CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8200 CXXRecordDecl *ClassDecl) {
8201 // C++ [class.copy]p4:
8202 // If the class definition does not explicitly declare a copy
8203 // constructor, one is declared implicitly.
8204
8205 ImplicitExceptionSpecification Spec(Context);
8206 bool Const;
8207 llvm::tie(Spec, Const) =
8208 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8209
8210 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8211 QualType ArgType = ClassType;
8212 if (Const)
8213 ArgType = ArgType.withConst();
8214 ArgType = Context.getLValueReferenceType(ArgType);
8215
8216 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8217
Douglas Gregor54be3392010-07-01 17:57:27 +00008218 DeclarationName Name
8219 = Context.DeclarationNames.getCXXConstructorName(
8220 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008221 SourceLocation ClassLoc = ClassDecl->getLocation();
8222 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00008223
8224 // An implicitly-declared copy constructor is an inline public
8225 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00008226 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00008227 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00008228 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00008229 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00008230 /*TInfo=*/0,
8231 /*isExplicit=*/false,
8232 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00008233 /*isImplicitlyDeclared=*/true,
8234 // FIXME: apply the rules for definitions here
8235 /*isConstexpr=*/false);
Douglas Gregor54be3392010-07-01 17:57:27 +00008236 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00008237 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00008238 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8239
Douglas Gregora6d69502010-07-02 23:41:54 +00008240 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00008241 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8242
Douglas Gregor54be3392010-07-01 17:57:27 +00008243 // Add the parameter to the constructor.
8244 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008245 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00008246 /*IdentifierInfo=*/0,
8247 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008248 SC_None,
8249 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008250 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +00008251
Douglas Gregor0be31a22010-07-02 17:43:08 +00008252 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00008253 PushOnScopeChains(CopyConstructor, S, false);
8254 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008255
Alexis Huntd74c85f2011-06-22 01:05:13 +00008256 // C++0x [class.copy]p7:
8257 // ... If the class definition declares a move constructor or move
8258 // assignment operator, the implicitly declared constructor is defined as
8259 // deleted; ...
8260 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8261 ClassDecl->hasUserDeclaredMoveAssignment() ||
8262 ShouldDeleteCopyConstructor(CopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00008263 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00008264
8265 return CopyConstructor;
8266}
8267
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008268void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00008269 CXXConstructorDecl *CopyConstructor) {
8270 assert((CopyConstructor->isDefaulted() &&
8271 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008272 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008273 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008274
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00008275 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008276 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008277
Douglas Gregora57478e2010-05-01 15:04:51 +00008278 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008279 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008280
Alexis Hunt1d792652011-01-08 20:30:50 +00008281 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008282 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00008283 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00008284 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00008285 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00008286 } else {
8287 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8288 CopyConstructor->getLocation(),
8289 MultiStmtArg(*this, 0, 0),
8290 /*isStmtExpr=*/false)
8291 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008292 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00008293 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00008294
8295 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00008296 if (ASTMutationListener *L = getASTMutationListener()) {
8297 L->CompletedImplicitDefinition(CopyConstructor);
8298 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008299}
8300
Sebastian Redl22653ba2011-08-30 19:58:05 +00008301Sema::ImplicitExceptionSpecification
8302Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8303 // C++ [except.spec]p14:
8304 // An implicitly declared special member function (Clause 12) shall have an
8305 // exception-specification. [...]
8306 ImplicitExceptionSpecification ExceptSpec(Context);
8307 if (ClassDecl->isInvalidDecl())
8308 return ExceptSpec;
8309
8310 // Direct base-class constructors.
8311 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8312 BEnd = ClassDecl->bases_end();
8313 B != BEnd; ++B) {
8314 if (B->isVirtual()) // Handled below.
8315 continue;
8316
8317 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8318 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8319 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8320 // If this is a deleted function, add it anyway. This might be conformant
8321 // with the standard. This might not. I'm not sure. It might not matter.
8322 if (Constructor)
8323 ExceptSpec.CalledDecl(Constructor);
8324 }
8325 }
8326
8327 // Virtual base-class constructors.
8328 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8329 BEnd = ClassDecl->vbases_end();
8330 B != BEnd; ++B) {
8331 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8332 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8333 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8334 // If this is a deleted function, add it anyway. This might be conformant
8335 // with the standard. This might not. I'm not sure. It might not matter.
8336 if (Constructor)
8337 ExceptSpec.CalledDecl(Constructor);
8338 }
8339 }
8340
8341 // Field constructors.
8342 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8343 FEnd = ClassDecl->field_end();
8344 F != FEnd; ++F) {
8345 if (F->hasInClassInitializer()) {
8346 if (Expr *E = F->getInClassInitializer())
8347 ExceptSpec.CalledExpr(E);
8348 else if (!F->isInvalidDecl())
8349 ExceptSpec.SetDelayed();
8350 } else if (const RecordType *RecordTy
8351 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8352 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8353 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8354 // If this is a deleted function, add it anyway. This might be conformant
8355 // with the standard. This might not. I'm not sure. It might not matter.
8356 // In particular, the problem is that this function never gets called. It
8357 // might just be ill-formed because this function attempts to refer to
8358 // a deleted function here.
8359 if (Constructor)
8360 ExceptSpec.CalledDecl(Constructor);
8361 }
8362 }
8363
8364 return ExceptSpec;
8365}
8366
8367CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8368 CXXRecordDecl *ClassDecl) {
8369 ImplicitExceptionSpecification Spec(
8370 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8371
8372 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8373 QualType ArgType = Context.getRValueReferenceType(ClassType);
8374
8375 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8376
8377 DeclarationName Name
8378 = Context.DeclarationNames.getCXXConstructorName(
8379 Context.getCanonicalType(ClassType));
8380 SourceLocation ClassLoc = ClassDecl->getLocation();
8381 DeclarationNameInfo NameInfo(Name, ClassLoc);
8382
8383 // C++0x [class.copy]p11:
8384 // An implicitly-declared copy/move constructor is an inline public
8385 // member of its class.
8386 CXXConstructorDecl *MoveConstructor
8387 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8388 Context.getFunctionType(Context.VoidTy,
8389 &ArgType, 1, EPI),
8390 /*TInfo=*/0,
8391 /*isExplicit=*/false,
8392 /*isInline=*/true,
8393 /*isImplicitlyDeclared=*/true,
8394 // FIXME: apply the rules for definitions here
8395 /*isConstexpr=*/false);
8396 MoveConstructor->setAccess(AS_public);
8397 MoveConstructor->setDefaulted();
8398 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8399
8400 // Add the parameter to the constructor.
8401 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8402 ClassLoc, ClassLoc,
8403 /*IdentifierInfo=*/0,
8404 ArgType, /*TInfo=*/0,
8405 SC_None,
8406 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008407 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008408
8409 // C++0x [class.copy]p9:
8410 // If the definition of a class X does not explicitly declare a move
8411 // constructor, one will be implicitly declared as defaulted if and only if:
8412 // [...]
8413 // - the move constructor would not be implicitly defined as deleted.
8414 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8415 // Cache this result so that we don't try to generate this over and over
8416 // on every lookup, leaking memory and wasting time.
8417 ClassDecl->setFailedImplicitMoveConstructor();
8418 return 0;
8419 }
8420
8421 // Note that we have declared this constructor.
8422 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8423
8424 if (Scope *S = getScopeForContext(ClassDecl))
8425 PushOnScopeChains(MoveConstructor, S, false);
8426 ClassDecl->addDecl(MoveConstructor);
8427
8428 return MoveConstructor;
8429}
8430
8431void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8432 CXXConstructorDecl *MoveConstructor) {
8433 assert((MoveConstructor->isDefaulted() &&
8434 MoveConstructor->isMoveConstructor() &&
8435 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8436 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8437
8438 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8439 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8440
8441 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8442 DiagnosticErrorTrap Trap(Diags);
8443
8444 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8445 Trap.hasErrorOccurred()) {
8446 Diag(CurrentLocation, diag::note_member_synthesized_at)
8447 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8448 MoveConstructor->setInvalidDecl();
8449 } else {
8450 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8451 MoveConstructor->getLocation(),
8452 MultiStmtArg(*this, 0, 0),
8453 /*isStmtExpr=*/false)
8454 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008455 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008456 }
8457
8458 MoveConstructor->setUsed();
8459
8460 if (ASTMutationListener *L = getASTMutationListener()) {
8461 L->CompletedImplicitDefinition(MoveConstructor);
8462 }
8463}
8464
John McCalldadc5752010-08-24 06:29:42 +00008465ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008466Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00008467 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008468 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008469 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008470 unsigned ConstructKind,
8471 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00008472 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00008473
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008474 // C++0x [class.copy]p34:
8475 // When certain criteria are met, an implementation is allowed to
8476 // omit the copy/move construction of a class object, even if the
8477 // copy/move constructor and/or destructor for the object have
8478 // side effects. [...]
8479 // - when a temporary class object that has not been bound to a
8480 // reference (12.2) would be copied/moved to a class object
8481 // with the same cv-unqualified type, the copy/move operation
8482 // can be omitted by constructing the temporary object
8483 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00008484 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00008485 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008486 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00008487 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00008488 }
Mike Stump11289f42009-09-09 15:08:12 +00008489
8490 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008491 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008492 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00008493}
8494
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008495/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8496/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00008497ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008498Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8499 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008500 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008501 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008502 unsigned ConstructKind,
8503 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00008504 unsigned NumExprs = ExprArgs.size();
8505 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00008506
Nick Lewyckyd4693212011-03-25 01:44:32 +00008507 for (specific_attr_iterator<NonNullAttr>
8508 i = Constructor->specific_attr_begin<NonNullAttr>(),
8509 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8510 const NonNullAttr *NonNull = *i;
8511 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8512 }
8513
Douglas Gregor27381f32009-11-23 12:27:39 +00008514 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00008515 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008516 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00008517 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008518 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8519 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008520}
8521
Mike Stump11289f42009-09-09 15:08:12 +00008522bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008523 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00008524 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00008525 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00008526 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00008527 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00008528 move(Exprs), false, CXXConstructExpr::CK_Complete,
8529 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008530 if (TempResult.isInvalid())
8531 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008532
Anders Carlsson6eb55572009-08-25 05:12:04 +00008533 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00008534 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00008535 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00008536 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00008537 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00008538
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008539 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00008540}
8541
John McCall03c48482010-02-02 09:10:11 +00008542void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00008543 if (VD->isInvalidDecl()) return;
8544
John McCall03c48482010-02-02 09:10:11 +00008545 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00008546 if (ClassDecl->isInvalidDecl()) return;
8547 if (ClassDecl->hasTrivialDestructor()) return;
8548 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00008549
Chandler Carruth86d17d32011-03-27 21:26:48 +00008550 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8551 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8552 CheckDestructorAccess(VD->getLocation(), Destructor,
8553 PDiag(diag::err_access_dtor_var)
8554 << VD->getDeclName()
8555 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00008556
Chandler Carruth86d17d32011-03-27 21:26:48 +00008557 if (!VD->hasGlobalStorage()) return;
8558
8559 // Emit warning for non-trivial dtor in global scope (a real global,
8560 // class-static, function-static).
8561 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8562
8563 // TODO: this should be re-enabled for static locals by !CXAAtExit
8564 if (!VD->isStaticLocal())
8565 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008566}
8567
Mike Stump11289f42009-09-09 15:08:12 +00008568/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008569/// ActOnDeclarator, when a C++ direct initializer is present.
8570/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00008571void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00008572 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008573 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00008574 SourceLocation RParenLoc,
8575 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00008576 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008577
8578 // If there is no declaration, there was an error parsing it. Just ignore
8579 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00008580 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008581 return;
Mike Stump11289f42009-09-09 15:08:12 +00008582
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008583 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8584 if (!VDecl) {
8585 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8586 RealDecl->setInvalidDecl();
8587 return;
8588 }
8589
Richard Smith30482bc2011-02-20 03:19:35 +00008590 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8591 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008592 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8593 if (Exprs.size() > 1) {
8594 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8595 diag::err_auto_var_init_multiple_expressions)
8596 << VDecl->getDeclName() << VDecl->getType()
8597 << VDecl->getSourceRange();
8598 RealDecl->setInvalidDecl();
8599 return;
8600 }
8601
8602 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00008603 TypeSourceInfo *DeducedType = 0;
8604 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00008605 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8606 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8607 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00008608 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00008609 RealDecl->setInvalidDecl();
8610 return;
8611 }
Richard Smith9647d3c2011-03-17 16:11:59 +00008612 VDecl->setTypeSourceInfo(DeducedType);
8613 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00008614
John McCall31168b02011-06-15 23:02:42 +00008615 // In ARC, infer lifetime.
8616 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8617 VDecl->setInvalidDecl();
8618
Richard Smith30482bc2011-02-20 03:19:35 +00008619 // If this is a redeclaration, check that the type we just deduced matches
8620 // the previously declared type.
8621 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8622 MergeVarDeclTypes(VDecl, Old);
8623 }
8624
Douglas Gregor402250f2009-08-26 21:14:46 +00008625 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00008626 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008627 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8628 //
8629 // Clients that want to distinguish between the two forms, can check for
8630 // direct initializer using VarDecl::hasCXXDirectInitializer().
8631 // A major benefit is that clients that don't particularly care about which
8632 // exactly form was it (like the CodeGen) can handle both cases without
8633 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00008634
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008635 // C++ 8.5p11:
8636 // The form of initialization (using parentheses or '=') is generally
8637 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00008638 // class type.
8639
Douglas Gregor50dc2192010-02-11 22:55:30 +00008640 if (!VDecl->getType()->isDependentType() &&
8641 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00008642 diag::err_typecheck_decl_incomplete_type)) {
8643 VDecl->setInvalidDecl();
8644 return;
8645 }
8646
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008647 // The variable can not have an abstract class type.
8648 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8649 diag::err_abstract_type_in_decl,
8650 AbstractVariableType))
8651 VDecl->setInvalidDecl();
8652
Sebastian Redl5ca79842010-02-01 20:16:42 +00008653 const VarDecl *Def;
8654 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008655 Diag(VDecl->getLocation(), diag::err_redefinition)
8656 << VDecl->getDeclName();
8657 Diag(Def->getLocation(), diag::note_previous_definition);
8658 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00008659 return;
8660 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00008661
Douglas Gregorf0f83692010-08-24 05:27:49 +00008662 // C++ [class.static.data]p4
8663 // If a static data member is of const integral or const
8664 // enumeration type, its declaration in the class definition can
8665 // specify a constant-initializer which shall be an integral
8666 // constant expression (5.19). In that case, the member can appear
8667 // in integral constant expressions. The member shall still be
8668 // defined in a namespace scope if it is used in the program and the
8669 // namespace scope definition shall not contain an initializer.
8670 //
8671 // We already performed a redefinition check above, but for static
8672 // data members we also need to check whether there was an in-class
8673 // declaration with an initializer.
8674 const VarDecl* PrevInit = 0;
8675 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8676 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8677 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8678 return;
8679 }
8680
Douglas Gregor71f39c92010-12-16 01:31:22 +00008681 bool IsDependent = false;
8682 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8683 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8684 VDecl->setInvalidDecl();
8685 return;
8686 }
8687
8688 if (Exprs.get()[I]->isTypeDependent())
8689 IsDependent = true;
8690 }
8691
Douglas Gregor50dc2192010-02-11 22:55:30 +00008692 // If either the declaration has a dependent type or if any of the
8693 // expressions is type-dependent, we represent the initialization
8694 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00008695 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00008696 // Let clients know that initialization was done with a direct initializer.
8697 VDecl->setCXXDirectInitializer(true);
8698
8699 // Store the initialization expressions as a ParenListExpr.
8700 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00008701 VDecl->setInit(new (Context) ParenListExpr(
8702 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8703 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00008704 return;
8705 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008706
8707 // Capture the variable that is being initialized and the style of
8708 // initialization.
8709 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8710
8711 // FIXME: Poor source location information.
8712 InitializationKind Kind
8713 = InitializationKind::CreateDirect(VDecl->getLocation(),
8714 LParenLoc, RParenLoc);
8715
8716 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00008717 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00008718 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008719 if (Result.isInvalid()) {
8720 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008721 return;
8722 }
John McCallacf0ee52010-10-08 02:01:28 +00008723
Richard Smith2316cd82011-09-29 19:11:37 +00008724 Expr *Init = Result.get();
8725 CheckImplicitConversions(Init, LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008726
Richard Smith2316cd82011-09-29 19:11:37 +00008727 if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() &&
8728 !Init->isValueDependent() &&
8729 !Init->isConstantInitializer(Context,
8730 VDecl->getType()->isReferenceType())) {
8731 // FIXME: Improve this diagnostic to explain why the initializer is not
8732 // a constant expression.
8733 Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init)
8734 << VDecl << Init->getSourceRange();
8735 }
8736
8737 Init = MaybeCreateExprWithCleanups(Init);
8738 VDecl->setInit(Init);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008739 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00008740
John McCall8b7fd8f12011-01-19 11:48:09 +00008741 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008742}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008743
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008744/// \brief Given a constructor and the set of arguments provided for the
8745/// constructor, convert the arguments and add any required default arguments
8746/// to form a proper call to this constructor.
8747///
8748/// \returns true if an error occurred, false otherwise.
8749bool
8750Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8751 MultiExprArg ArgsPtr,
8752 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00008753 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008754 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8755 unsigned NumArgs = ArgsPtr.size();
8756 Expr **Args = (Expr **)ArgsPtr.get();
8757
8758 const FunctionProtoType *Proto
8759 = Constructor->getType()->getAs<FunctionProtoType>();
8760 assert(Proto && "Constructor without a prototype?");
8761 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008762
8763 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008764 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008765 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008766 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008767 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008768
8769 VariadicCallType CallType =
8770 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008771 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008772 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8773 Proto, 0, Args, NumArgs, AllArgs,
8774 CallType);
8775 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8776 ConvertedArgs.push_back(AllArgs[i]);
8777 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008778}
8779
Anders Carlssone363c8e2009-12-12 00:32:00 +00008780static inline bool
8781CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8782 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008783 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00008784 if (isa<NamespaceDecl>(DC)) {
8785 return SemaRef.Diag(FnDecl->getLocation(),
8786 diag::err_operator_new_delete_declared_in_namespace)
8787 << FnDecl->getDeclName();
8788 }
8789
8790 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00008791 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00008792 return SemaRef.Diag(FnDecl->getLocation(),
8793 diag::err_operator_new_delete_declared_static)
8794 << FnDecl->getDeclName();
8795 }
8796
Anders Carlsson60659a82009-12-12 02:43:16 +00008797 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00008798}
8799
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008800static inline bool
8801CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8802 CanQualType ExpectedResultType,
8803 CanQualType ExpectedFirstParamType,
8804 unsigned DependentParamTypeDiag,
8805 unsigned InvalidParamTypeDiag) {
8806 QualType ResultType =
8807 FnDecl->getType()->getAs<FunctionType>()->getResultType();
8808
8809 // Check that the result type is not dependent.
8810 if (ResultType->isDependentType())
8811 return SemaRef.Diag(FnDecl->getLocation(),
8812 diag::err_operator_new_delete_dependent_result_type)
8813 << FnDecl->getDeclName() << ExpectedResultType;
8814
8815 // Check that the result type is what we expect.
8816 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8817 return SemaRef.Diag(FnDecl->getLocation(),
8818 diag::err_operator_new_delete_invalid_result_type)
8819 << FnDecl->getDeclName() << ExpectedResultType;
8820
8821 // A function template must have at least 2 parameters.
8822 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8823 return SemaRef.Diag(FnDecl->getLocation(),
8824 diag::err_operator_new_delete_template_too_few_parameters)
8825 << FnDecl->getDeclName();
8826
8827 // The function decl must have at least 1 parameter.
8828 if (FnDecl->getNumParams() == 0)
8829 return SemaRef.Diag(FnDecl->getLocation(),
8830 diag::err_operator_new_delete_too_few_parameters)
8831 << FnDecl->getDeclName();
8832
8833 // Check the the first parameter type is not dependent.
8834 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8835 if (FirstParamType->isDependentType())
8836 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8837 << FnDecl->getDeclName() << ExpectedFirstParamType;
8838
8839 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00008840 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008841 ExpectedFirstParamType)
8842 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8843 << FnDecl->getDeclName() << ExpectedFirstParamType;
8844
8845 return false;
8846}
8847
Anders Carlsson12308f42009-12-11 23:23:22 +00008848static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008849CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00008850 // C++ [basic.stc.dynamic.allocation]p1:
8851 // A program is ill-formed if an allocation function is declared in a
8852 // namespace scope other than global scope or declared static in global
8853 // scope.
8854 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8855 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008856
8857 CanQualType SizeTy =
8858 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8859
8860 // C++ [basic.stc.dynamic.allocation]p1:
8861 // The return type shall be void*. The first parameter shall have type
8862 // std::size_t.
8863 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8864 SizeTy,
8865 diag::err_operator_new_dependent_param_type,
8866 diag::err_operator_new_param_type))
8867 return true;
8868
8869 // C++ [basic.stc.dynamic.allocation]p1:
8870 // The first parameter shall not have an associated default argument.
8871 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00008872 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008873 diag::err_operator_new_default_arg)
8874 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8875
8876 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00008877}
8878
8879static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00008880CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8881 // C++ [basic.stc.dynamic.deallocation]p1:
8882 // A program is ill-formed if deallocation functions are declared in a
8883 // namespace scope other than global scope or declared static in global
8884 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00008885 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8886 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00008887
8888 // C++ [basic.stc.dynamic.deallocation]p2:
8889 // Each deallocation function shall return void and its first parameter
8890 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008891 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8892 SemaRef.Context.VoidPtrTy,
8893 diag::err_operator_delete_dependent_param_type,
8894 diag::err_operator_delete_param_type))
8895 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00008896
Anders Carlsson12308f42009-12-11 23:23:22 +00008897 return false;
8898}
8899
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008900/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8901/// of this overloaded operator is well-formed. If so, returns false;
8902/// otherwise, emits appropriate diagnostics and returns true.
8903bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00008904 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008905 "Expected an overloaded operator declaration");
8906
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008907 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8908
Mike Stump11289f42009-09-09 15:08:12 +00008909 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008910 // The allocation and deallocation functions, operator new,
8911 // operator new[], operator delete and operator delete[], are
8912 // described completely in 3.7.3. The attributes and restrictions
8913 // found in the rest of this subclause do not apply to them unless
8914 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00008915 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00008916 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00008917
Anders Carlsson22f443f2009-12-12 00:26:23 +00008918 if (Op == OO_New || Op == OO_Array_New)
8919 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008920
8921 // C++ [over.oper]p6:
8922 // An operator function shall either be a non-static member
8923 // function or be a non-member function and have at least one
8924 // parameter whose type is a class, a reference to a class, an
8925 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00008926 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8927 if (MethodDecl->isStatic())
8928 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008929 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008930 } else {
8931 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00008932 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8933 ParamEnd = FnDecl->param_end();
8934 Param != ParamEnd; ++Param) {
8935 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00008936 if (ParamType->isDependentType() || ParamType->isRecordType() ||
8937 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008938 ClassOrEnumParam = true;
8939 break;
8940 }
8941 }
8942
Douglas Gregord69246b2008-11-17 16:14:12 +00008943 if (!ClassOrEnumParam)
8944 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00008945 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008946 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008947 }
8948
8949 // C++ [over.oper]p8:
8950 // An operator function cannot have default arguments (8.3.6),
8951 // except where explicitly stated below.
8952 //
Mike Stump11289f42009-09-09 15:08:12 +00008953 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008954 // (C++ [over.call]p1).
8955 if (Op != OO_Call) {
8956 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8957 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008958 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00008959 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00008960 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008961 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008962 }
8963 }
8964
Douglas Gregor6cf08062008-11-10 13:38:07 +00008965 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8966 { false, false, false }
8967#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8968 , { Unary, Binary, MemberOnly }
8969#include "clang/Basic/OperatorKinds.def"
8970 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008971
Douglas Gregor6cf08062008-11-10 13:38:07 +00008972 bool CanBeUnaryOperator = OperatorUses[Op][0];
8973 bool CanBeBinaryOperator = OperatorUses[Op][1];
8974 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008975
8976 // C++ [over.oper]p8:
8977 // [...] Operator functions cannot have more or fewer parameters
8978 // than the number required for the corresponding operator, as
8979 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00008980 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00008981 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008982 if (Op != OO_Call &&
8983 ((NumParams == 1 && !CanBeUnaryOperator) ||
8984 (NumParams == 2 && !CanBeBinaryOperator) ||
8985 (NumParams < 1) || (NumParams > 2))) {
8986 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008987 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00008988 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008989 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00008990 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008991 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00008992 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00008993 assert(CanBeBinaryOperator &&
8994 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008995 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00008996 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008997
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008998 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008999 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009000 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009001
Douglas Gregord69246b2008-11-17 16:14:12 +00009002 // Overloaded operators other than operator() cannot be variadic.
9003 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00009004 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009005 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009006 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009007 }
9008
9009 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00009010 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9011 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009012 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009013 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009014 }
9015
9016 // C++ [over.inc]p1:
9017 // The user-defined function called operator++ implements the
9018 // prefix and postfix ++ operator. If this function is a member
9019 // function with no parameters, or a non-member function with one
9020 // parameter of class or enumeration type, it defines the prefix
9021 // increment operator ++ for objects of that type. If the function
9022 // is a member function with one parameter (which shall be of type
9023 // int) or a non-member function with two parameters (the second
9024 // of which shall be of type int), it defines the postfix
9025 // increment operator ++ for objects of that type.
9026 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9027 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9028 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00009029 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009030 ParamIsInt = BT->getKind() == BuiltinType::Int;
9031
Chris Lattner2b786902008-11-21 07:50:02 +00009032 if (!ParamIsInt)
9033 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00009034 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009035 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009036 }
9037
Douglas Gregord69246b2008-11-17 16:14:12 +00009038 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009039}
Chris Lattner3b024a32008-12-17 07:09:26 +00009040
Alexis Huntc88db062010-01-13 09:01:02 +00009041/// CheckLiteralOperatorDeclaration - Check whether the declaration
9042/// of this literal operator function is well-formed. If so, returns
9043/// false; otherwise, emits appropriate diagnostics and returns true.
9044bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9045 DeclContext *DC = FnDecl->getDeclContext();
9046 Decl::Kind Kind = DC->getDeclKind();
9047 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9048 Kind != Decl::LinkageSpec) {
9049 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9050 << FnDecl->getDeclName();
9051 return true;
9052 }
9053
9054 bool Valid = false;
9055
Alexis Hunt7dd26172010-04-07 23:11:06 +00009056 // template <char...> type operator "" name() is the only valid template
9057 // signature, and the only valid signature with no parameters.
9058 if (FnDecl->param_size() == 0) {
9059 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9060 // Must have only one template parameter
9061 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9062 if (Params->size() == 1) {
9063 NonTypeTemplateParmDecl *PmDecl =
9064 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00009065
Alexis Hunt7dd26172010-04-07 23:11:06 +00009066 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00009067 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9068 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9069 Valid = true;
9070 }
9071 }
9072 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00009073 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00009074 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9075
Alexis Huntc88db062010-01-13 09:01:02 +00009076 QualType T = (*Param)->getType();
9077
Alexis Hunt079a6f72010-04-07 22:57:35 +00009078 // unsigned long long int, long double, and any character type are allowed
9079 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00009080 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9081 Context.hasSameType(T, Context.LongDoubleTy) ||
9082 Context.hasSameType(T, Context.CharTy) ||
9083 Context.hasSameType(T, Context.WCharTy) ||
9084 Context.hasSameType(T, Context.Char16Ty) ||
9085 Context.hasSameType(T, Context.Char32Ty)) {
9086 if (++Param == FnDecl->param_end())
9087 Valid = true;
9088 goto FinishedParams;
9089 }
9090
Alexis Hunt079a6f72010-04-07 22:57:35 +00009091 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00009092 const PointerType *PT = T->getAs<PointerType>();
9093 if (!PT)
9094 goto FinishedParams;
9095 T = PT->getPointeeType();
9096 if (!T.isConstQualified())
9097 goto FinishedParams;
9098 T = T.getUnqualifiedType();
9099
9100 // Move on to the second parameter;
9101 ++Param;
9102
9103 // If there is no second parameter, the first must be a const char *
9104 if (Param == FnDecl->param_end()) {
9105 if (Context.hasSameType(T, Context.CharTy))
9106 Valid = true;
9107 goto FinishedParams;
9108 }
9109
9110 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9111 // are allowed as the first parameter to a two-parameter function
9112 if (!(Context.hasSameType(T, Context.CharTy) ||
9113 Context.hasSameType(T, Context.WCharTy) ||
9114 Context.hasSameType(T, Context.Char16Ty) ||
9115 Context.hasSameType(T, Context.Char32Ty)))
9116 goto FinishedParams;
9117
9118 // The second and final parameter must be an std::size_t
9119 T = (*Param)->getType().getUnqualifiedType();
9120 if (Context.hasSameType(T, Context.getSizeType()) &&
9121 ++Param == FnDecl->param_end())
9122 Valid = true;
9123 }
9124
9125 // FIXME: This diagnostic is absolutely terrible.
9126FinishedParams:
9127 if (!Valid) {
9128 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9129 << FnDecl->getDeclName();
9130 return true;
9131 }
9132
Douglas Gregor86325ad2011-08-30 22:40:35 +00009133 StringRef LiteralName
9134 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9135 if (LiteralName[0] != '_') {
9136 // C++0x [usrlit.suffix]p1:
9137 // Literal suffix identifiers that do not start with an underscore are
9138 // reserved for future standardization.
9139 bool IsHexFloat = true;
9140 if (LiteralName.size() > 1 &&
9141 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9142 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9143 if (!isdigit(LiteralName[I])) {
9144 IsHexFloat = false;
9145 break;
9146 }
9147 }
9148 }
9149
9150 if (IsHexFloat)
9151 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9152 << LiteralName;
9153 else
9154 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9155 }
9156
Alexis Huntc88db062010-01-13 09:01:02 +00009157 return false;
9158}
9159
Douglas Gregor07665a62009-01-05 19:45:36 +00009160/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9161/// linkage specification, including the language and (if present)
9162/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9163/// the location of the language string literal, which is provided
9164/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9165/// the '{' brace. Otherwise, this linkage specification does not
9166/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00009167Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9168 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009169 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +00009170 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00009171 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009172 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009173 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009174 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009175 Language = LinkageSpecDecl::lang_cxx;
9176 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00009177 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00009178 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00009179 }
Mike Stump11289f42009-09-09 15:08:12 +00009180
Chris Lattner438e5012008-12-17 07:13:27 +00009181 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00009182
Douglas Gregor07665a62009-01-05 19:45:36 +00009183 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009184 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009185 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00009186 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00009187 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00009188}
9189
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00009190/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00009191/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9192/// valid, it's the position of the closing '}' brace in a linkage
9193/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00009194Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009195 Decl *LinkageSpec,
9196 SourceLocation RBraceLoc) {
9197 if (LinkageSpec) {
9198 if (RBraceLoc.isValid()) {
9199 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9200 LSDecl->setRBraceLoc(RBraceLoc);
9201 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009202 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009203 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009204 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00009205}
9206
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009207/// \brief Perform semantic analysis for the variable declaration that
9208/// occurs within a C++ catch clause, returning the newly-created
9209/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009210VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00009211 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009212 SourceLocation StartLoc,
9213 SourceLocation Loc,
9214 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009215 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009216 QualType ExDeclType = TInfo->getType();
9217
Sebastian Redl54c04d42008-12-22 19:15:10 +00009218 // Arrays and functions decay.
9219 if (ExDeclType->isArrayType())
9220 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9221 else if (ExDeclType->isFunctionType())
9222 ExDeclType = Context.getPointerType(ExDeclType);
9223
9224 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9225 // The exception-declaration shall not denote a pointer or reference to an
9226 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00009227 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00009228 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009229 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00009230 Invalid = true;
9231 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009232
Douglas Gregor104ee002010-03-08 01:47:36 +00009233 // GCC allows catching pointers and references to incomplete types
9234 // as an extension; so do we, but we warn by default.
9235
Sebastian Redl54c04d42008-12-22 19:15:10 +00009236 QualType BaseType = ExDeclType;
9237 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00009238 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00009239 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009240 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009241 BaseType = Ptr->getPointeeType();
9242 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00009243 DK = diag::ext_catch_incomplete_ptr;
9244 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00009245 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00009246 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009247 BaseType = Ref->getPointeeType();
9248 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00009249 DK = diag::ext_catch_incomplete_ref;
9250 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009251 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00009252 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00009253 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9254 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00009255 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009256
Mike Stump11289f42009-09-09 15:08:12 +00009257 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009258 RequireNonAbstractType(Loc, ExDeclType,
9259 diag::err_abstract_type_in_decl,
9260 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00009261 Invalid = true;
9262
John McCall2ca705e2010-07-24 00:37:23 +00009263 // Only the non-fragile NeXT runtime currently supports C++ catches
9264 // of ObjC types, and no runtime supports catching ObjC types by value.
9265 if (!Invalid && getLangOptions().ObjC1) {
9266 QualType T = ExDeclType;
9267 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9268 T = RT->getPointeeType();
9269
9270 if (T->isObjCObjectType()) {
9271 Diag(Loc, diag::err_objc_object_catch);
9272 Invalid = true;
9273 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00009274 if (!getLangOptions().ObjCNonFragileABI)
9275 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00009276 }
9277 }
9278
Abramo Bagnaradff19302011-03-08 08:55:46 +00009279 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9280 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00009281 ExDecl->setExceptionVariable(true);
9282
Douglas Gregor750734c2011-07-06 18:14:43 +00009283 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +00009284 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00009285 // C++ [except.handle]p16:
9286 // The object declared in an exception-declaration or, if the
9287 // exception-declaration does not specify a name, a temporary (12.2) is
9288 // copy-initialized (8.5) from the exception object. [...]
9289 // The object is destroyed when the handler exits, after the destruction
9290 // of any automatic objects initialized within the handler.
9291 //
9292 // We just pretend to initialize the object with itself, then make sure
9293 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00009294 QualType initType = ExDeclType;
9295
9296 InitializedEntity entity =
9297 InitializedEntity::InitializeVariable(ExDecl);
9298 InitializationKind initKind =
9299 InitializationKind::CreateCopy(Loc, SourceLocation());
9300
9301 Expr *opaqueValue =
9302 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9303 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9304 ExprResult result = sequence.Perform(*this, entity, initKind,
9305 MultiExprArg(&opaqueValue, 1));
9306 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00009307 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00009308 else {
9309 // If the constructor used was non-trivial, set this as the
9310 // "initializer".
9311 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9312 if (!construct->getConstructor()->isTrivial()) {
9313 Expr *init = MaybeCreateExprWithCleanups(construct);
9314 ExDecl->setInit(init);
9315 }
9316
9317 // And make sure it's destructable.
9318 FinalizeVarWithDestructor(ExDecl, recordType);
9319 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00009320 }
9321 }
9322
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009323 if (Invalid)
9324 ExDecl->setInvalidDecl();
9325
9326 return ExDecl;
9327}
9328
9329/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9330/// handler.
John McCall48871652010-08-21 09:40:31 +00009331Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00009332 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00009333 bool Invalid = D.isInvalidType();
9334
9335 // Check for unexpanded parameter packs.
9336 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9337 UPPC_ExceptionType)) {
9338 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9339 D.getIdentifierLoc());
9340 Invalid = true;
9341 }
9342
Sebastian Redl54c04d42008-12-22 19:15:10 +00009343 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009344 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00009345 LookupOrdinaryName,
9346 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009347 // The scope should be freshly made just for us. There is just no way
9348 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00009349 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00009350 if (PrevDecl->isTemplateParameter()) {
9351 // Maybe we will complain about the shadowed template parameter.
9352 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009353 }
9354 }
9355
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009356 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009357 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9358 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009359 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009360 }
9361
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009362 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009363 D.getSourceRange().getBegin(),
9364 D.getIdentifierLoc(),
9365 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009366 if (Invalid)
9367 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009368
Sebastian Redl54c04d42008-12-22 19:15:10 +00009369 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009370 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009371 PushOnScopeChains(ExDecl, S);
9372 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009373 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009374
Douglas Gregor758a8692009-06-17 21:51:59 +00009375 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00009376 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009377}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009378
Abramo Bagnaraea947882011-03-08 16:41:52 +00009379Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00009380 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009381 Expr *AssertMessageExpr_,
9382 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00009383 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009384
Anders Carlsson54b26982009-03-14 00:33:21 +00009385 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9386 llvm::APSInt Value(32);
9387 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009388 Diag(StaticAssertLoc,
9389 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00009390 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00009391 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00009392 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009393
Anders Carlsson54b26982009-03-14 00:33:21 +00009394 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009395 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00009396 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00009397 }
9398 }
Mike Stump11289f42009-09-09 15:08:12 +00009399
Douglas Gregoref68fee2010-12-15 23:55:21 +00009400 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9401 return 0;
9402
Abramo Bagnaraea947882011-03-08 16:41:52 +00009403 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9404 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00009405
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009406 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00009407 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009408}
Sebastian Redlf769df52009-03-24 22:27:57 +00009409
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009410/// \brief Perform semantic analysis of the given friend type declaration.
9411///
9412/// \returns A friend declaration that.
9413FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9414 TypeSourceInfo *TSInfo) {
9415 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9416
9417 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009418 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009419
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009420 if (!getLangOptions().CPlusPlus0x) {
9421 // C++03 [class.friend]p2:
9422 // An elaborated-type-specifier shall be used in a friend declaration
9423 // for a class.*
9424 //
9425 // * The class-key of the elaborated-type-specifier is required.
9426 if (!ActiveTemplateInstantiations.empty()) {
9427 // Do not complain about the form of friend template types during
9428 // template instantiation; we will already have complained when the
9429 // template was declared.
9430 } else if (!T->isElaboratedTypeSpecifier()) {
9431 // If we evaluated the type to a record type, suggest putting
9432 // a tag in front.
9433 if (const RecordType *RT = T->getAs<RecordType>()) {
9434 RecordDecl *RD = RT->getDecl();
9435
9436 std::string InsertionText = std::string(" ") + RD->getKindName();
9437
9438 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9439 << (unsigned) RD->getTagKind()
9440 << T
9441 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9442 InsertionText);
9443 } else {
9444 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9445 << T
9446 << SourceRange(FriendLoc, TypeRange.getEnd());
9447 }
9448 } else if (T->getAs<EnumType>()) {
9449 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009450 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009451 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009452 }
9453 }
9454
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009455 // C++0x [class.friend]p3:
9456 // If the type specifier in a friend declaration designates a (possibly
9457 // cv-qualified) class type, that class is declared as a friend; otherwise,
9458 // the friend declaration is ignored.
9459
9460 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9461 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009462
9463 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9464}
9465
John McCallace48cd2010-10-19 01:40:49 +00009466/// Handle a friend tag declaration where the scope specifier was
9467/// templated.
9468Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9469 unsigned TagSpec, SourceLocation TagLoc,
9470 CXXScopeSpec &SS,
9471 IdentifierInfo *Name, SourceLocation NameLoc,
9472 AttributeList *Attr,
9473 MultiTemplateParamsArg TempParamLists) {
9474 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9475
9476 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00009477 bool Invalid = false;
9478
9479 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00009480 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00009481 TempParamLists.get(),
9482 TempParamLists.size(),
9483 /*friend*/ true,
9484 isExplicitSpecialization,
9485 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00009486 if (TemplateParams->size() > 0) {
9487 // This is a declaration of a class template.
9488 if (Invalid)
9489 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009490
Eric Christopher6f228b52011-07-21 05:34:24 +00009491 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9492 SS, Name, NameLoc, Attr,
9493 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +00009494 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +00009495 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009496 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00009497 } else {
9498 // The "template<>" header is extraneous.
9499 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9500 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9501 isExplicitSpecialization = true;
9502 }
9503 }
9504
9505 if (Invalid) return 0;
9506
9507 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9508
9509 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00009510 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00009511 if (TempParamLists.get()[I]->size()) {
9512 isAllExplicitSpecializations = false;
9513 break;
9514 }
9515 }
9516
9517 // FIXME: don't ignore attributes.
9518
9519 // If it's explicit specializations all the way down, just forget
9520 // about the template header and build an appropriate non-templated
9521 // friend. TODO: for source fidelity, remember the headers.
9522 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009523 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00009524 ElaboratedTypeKeyword Keyword
9525 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009526 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009527 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00009528 if (T.isNull())
9529 return 0;
9530
9531 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9532 if (isa<DependentNameType>(T)) {
9533 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9534 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009535 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009536 TL.setNameLoc(NameLoc);
9537 } else {
9538 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9539 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009540 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009541 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9542 }
9543
9544 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9545 TSI, FriendLoc);
9546 Friend->setAccess(AS_public);
9547 CurContext->addDecl(Friend);
9548 return Friend;
9549 }
9550
9551 // Handle the case of a templated-scope friend class. e.g.
9552 // template <class T> class A<T>::B;
9553 // FIXME: we don't support these right now.
9554 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9555 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9556 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9557 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9558 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009559 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00009560 TL.setNameLoc(NameLoc);
9561
9562 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9563 TSI, FriendLoc);
9564 Friend->setAccess(AS_public);
9565 Friend->setUnsupportedFriend(true);
9566 CurContext->addDecl(Friend);
9567 return Friend;
9568}
9569
9570
John McCall11083da2009-09-16 22:47:08 +00009571/// Handle a friend type declaration. This works in tandem with
9572/// ActOnTag.
9573///
9574/// Notes on friend class templates:
9575///
9576/// We generally treat friend class declarations as if they were
9577/// declaring a class. So, for example, the elaborated type specifier
9578/// in a friend declaration is required to obey the restrictions of a
9579/// class-head (i.e. no typedefs in the scope chain), template
9580/// parameters are required to match up with simple template-ids, &c.
9581/// However, unlike when declaring a template specialization, it's
9582/// okay to refer to a template specialization without an empty
9583/// template parameter declaration, e.g.
9584/// friend class A<T>::B<unsigned>;
9585/// We permit this as a special case; if there are any template
9586/// parameters present at all, require proper matching, i.e.
9587/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00009588Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00009589 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00009590 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00009591
9592 assert(DS.isFriendSpecified());
9593 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9594
John McCall11083da2009-09-16 22:47:08 +00009595 // Try to convert the decl specifier to a type. This works for
9596 // friend templates because ActOnTag never produces a ClassTemplateDecl
9597 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00009598 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00009599 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9600 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00009601 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00009602 return 0;
John McCall07e91c02009-08-06 02:15:43 +00009603
Douglas Gregor6c110f32010-12-16 01:14:37 +00009604 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9605 return 0;
9606
John McCall11083da2009-09-16 22:47:08 +00009607 // This is definitely an error in C++98. It's probably meant to
9608 // be forbidden in C++0x, too, but the specification is just
9609 // poorly written.
9610 //
9611 // The problem is with declarations like the following:
9612 // template <T> friend A<T>::foo;
9613 // where deciding whether a class C is a friend or not now hinges
9614 // on whether there exists an instantiation of A that causes
9615 // 'foo' to equal C. There are restrictions on class-heads
9616 // (which we declare (by fiat) elaborated friend declarations to
9617 // be) that makes this tractable.
9618 //
9619 // FIXME: handle "template <> friend class A<T>;", which
9620 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00009621 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00009622 Diag(Loc, diag::err_tagless_friend_type_template)
9623 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00009624 return 0;
John McCall11083da2009-09-16 22:47:08 +00009625 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009626
John McCallaa74a0c2009-08-28 07:59:38 +00009627 // C++98 [class.friend]p1: A friend of a class is a function
9628 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00009629 // This is fixed in DR77, which just barely didn't make the C++03
9630 // deadline. It's also a very silly restriction that seriously
9631 // affects inner classes and which nobody else seems to implement;
9632 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00009633 //
9634 // But note that we could warn about it: it's always useless to
9635 // friend one of your own members (it's not, however, worthless to
9636 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00009637
John McCall11083da2009-09-16 22:47:08 +00009638 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009639 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00009640 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009641 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00009642 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00009643 TSI,
John McCall11083da2009-09-16 22:47:08 +00009644 DS.getFriendSpecLoc());
9645 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009646 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9647
9648 if (!D)
John McCall48871652010-08-21 09:40:31 +00009649 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009650
John McCall11083da2009-09-16 22:47:08 +00009651 D->setAccess(AS_public);
9652 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00009653
John McCall48871652010-08-21 09:40:31 +00009654 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00009655}
9656
John McCallde3fd222010-10-12 23:13:28 +00009657Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9658 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00009659 const DeclSpec &DS = D.getDeclSpec();
9660
9661 assert(DS.isFriendSpecified());
9662 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9663
9664 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00009665 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9666 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00009667
9668 // C++ [class.friend]p1
9669 // A friend of a class is a function or class....
9670 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00009671 // It *doesn't* see through dependent types, which is correct
9672 // according to [temp.arg.type]p3:
9673 // If a declaration acquires a function type through a
9674 // type dependent on a template-parameter and this causes
9675 // a declaration that does not use the syntactic form of a
9676 // function declarator to have a function type, the program
9677 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00009678 if (!T->isFunctionType()) {
9679 Diag(Loc, diag::err_unexpected_friend);
9680
9681 // It might be worthwhile to try to recover by creating an
9682 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00009683 return 0;
John McCall07e91c02009-08-06 02:15:43 +00009684 }
9685
9686 // C++ [namespace.memdef]p3
9687 // - If a friend declaration in a non-local class first declares a
9688 // class or function, the friend class or function is a member
9689 // of the innermost enclosing namespace.
9690 // - The name of the friend is not found by simple name lookup
9691 // until a matching declaration is provided in that namespace
9692 // scope (either before or after the class declaration granting
9693 // friendship).
9694 // - If a friend function is called, its name may be found by the
9695 // name lookup that considers functions from namespaces and
9696 // classes associated with the types of the function arguments.
9697 // - When looking for a prior declaration of a class or a function
9698 // declared as a friend, scopes outside the innermost enclosing
9699 // namespace scope are not considered.
9700
John McCallde3fd222010-10-12 23:13:28 +00009701 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009702 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9703 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00009704 assert(Name);
9705
Douglas Gregor6c110f32010-12-16 01:14:37 +00009706 // Check for unexpanded parameter packs.
9707 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9708 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9709 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9710 return 0;
9711
John McCall07e91c02009-08-06 02:15:43 +00009712 // The context we found the declaration in, or in which we should
9713 // create the declaration.
9714 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00009715 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009716 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00009717 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00009718
John McCallde3fd222010-10-12 23:13:28 +00009719 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00009720
John McCallde3fd222010-10-12 23:13:28 +00009721 // There are four cases here.
9722 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00009723 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00009724 // there as appropriate.
9725 // Recover from invalid scope qualifiers as if they just weren't there.
9726 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00009727 // C++0x [namespace.memdef]p3:
9728 // If the name in a friend declaration is neither qualified nor
9729 // a template-id and the declaration is a function or an
9730 // elaborated-type-specifier, the lookup to determine whether
9731 // the entity has been previously declared shall not consider
9732 // any scopes outside the innermost enclosing namespace.
9733 // C++0x [class.friend]p11:
9734 // If a friend declaration appears in a local class and the name
9735 // specified is an unqualified name, a prior declaration is
9736 // looked up without considering scopes that are outside the
9737 // innermost enclosing non-class scope. For a friend function
9738 // declaration, if there is no prior declaration, the program is
9739 // ill-formed.
9740 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00009741 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00009742
John McCallf7cfb222010-10-13 05:45:15 +00009743 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00009744 DC = CurContext;
9745 while (true) {
9746 // Skip class contexts. If someone can cite chapter and verse
9747 // for this behavior, that would be nice --- it's what GCC and
9748 // EDG do, and it seems like a reasonable intent, but the spec
9749 // really only says that checks for unqualified existing
9750 // declarations should stop at the nearest enclosing namespace,
9751 // not that they should only consider the nearest enclosing
9752 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009753 while (DC->isRecord())
9754 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00009755
John McCall1f82f242009-11-18 22:49:29 +00009756 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00009757
9758 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00009759 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00009760 break;
John McCallf7cfb222010-10-13 05:45:15 +00009761
John McCallf4776592010-10-14 22:22:28 +00009762 if (isTemplateId) {
9763 if (isa<TranslationUnitDecl>(DC)) break;
9764 } else {
9765 if (DC->isFileContext()) break;
9766 }
John McCall07e91c02009-08-06 02:15:43 +00009767 DC = DC->getParent();
9768 }
9769
9770 // C++ [class.friend]p1: A friend of a class is a function or
9771 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00009772 // C++0x changes this for both friend types and functions.
9773 // Most C++ 98 compilers do seem to give an error here, so
9774 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00009775 if (!Previous.empty() && DC->Equals(CurContext)
9776 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00009777 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00009778
John McCallccbc0322010-10-13 06:22:15 +00009779 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00009780
John McCallde3fd222010-10-12 23:13:28 +00009781 // - There's a non-dependent scope specifier, in which case we
9782 // compute it and do a previous lookup there for a function
9783 // or function template.
9784 } else if (!SS.getScopeRep()->isDependent()) {
9785 DC = computeDeclContext(SS);
9786 if (!DC) return 0;
9787
9788 if (RequireCompleteDeclContext(SS, DC)) return 0;
9789
9790 LookupQualifiedName(Previous, DC);
9791
9792 // Ignore things found implicitly in the wrong scope.
9793 // TODO: better diagnostics for this case. Suggesting the right
9794 // qualified scope would be nice...
9795 LookupResult::Filter F = Previous.makeFilter();
9796 while (F.hasNext()) {
9797 NamedDecl *D = F.next();
9798 if (!DC->InEnclosingNamespaceSetOf(
9799 D->getDeclContext()->getRedeclContext()))
9800 F.erase();
9801 }
9802 F.done();
9803
9804 if (Previous.empty()) {
9805 D.setInvalidType();
9806 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9807 return 0;
9808 }
9809
9810 // C++ [class.friend]p1: A friend of a class is a function or
9811 // class that is not a member of the class . . .
9812 if (DC->Equals(CurContext))
9813 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9814
9815 // - There's a scope specifier that does not match any template
9816 // parameter lists, in which case we use some arbitrary context,
9817 // create a method or method template, and wait for instantiation.
9818 // - There's a scope specifier that does match some template
9819 // parameter lists, which we don't handle right now.
9820 } else {
9821 DC = CurContext;
9822 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00009823 }
9824
John McCallf7cfb222010-10-13 05:45:15 +00009825 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00009826 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00009827 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9828 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9829 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00009830 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00009831 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9832 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00009833 return 0;
John McCall07e91c02009-08-06 02:15:43 +00009834 }
John McCall07e91c02009-08-06 02:15:43 +00009835 }
9836
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009837 bool Redeclaration = false;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00009838 bool AddToScope = true;
John McCallccbc0322010-10-13 06:22:15 +00009839 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00009840 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00009841 IsDefinition,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00009842 Redeclaration, AddToScope);
John McCall48871652010-08-21 09:40:31 +00009843 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00009844
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009845 assert(ND->getDeclContext() == DC);
9846 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00009847
John McCall759e32b2009-08-31 22:39:49 +00009848 // Add the function declaration to the appropriate lookup tables,
9849 // adjusting the redeclarations list as necessary. We don't
9850 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00009851 //
John McCall759e32b2009-08-31 22:39:49 +00009852 // Also update the scope-based lookup if the target context's
9853 // lookup context is in lexical scope.
9854 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00009855 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009856 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00009857 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009858 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00009859 }
John McCallaa74a0c2009-08-28 07:59:38 +00009860
9861 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009862 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00009863 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00009864 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00009865 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00009866
John McCallde3fd222010-10-12 23:13:28 +00009867 if (ND->isInvalidDecl())
9868 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00009869 else {
9870 FunctionDecl *FD;
9871 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9872 FD = FTD->getTemplatedDecl();
9873 else
9874 FD = cast<FunctionDecl>(ND);
9875
9876 // Mark templated-scope function declarations as unsupported.
9877 if (FD->getNumTemplateParameterLists())
9878 FrD->setUnsupportedFriend(true);
9879 }
John McCallde3fd222010-10-12 23:13:28 +00009880
John McCall48871652010-08-21 09:40:31 +00009881 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00009882}
9883
John McCall48871652010-08-21 09:40:31 +00009884void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9885 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00009886
Sebastian Redlf769df52009-03-24 22:27:57 +00009887 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9888 if (!Fn) {
9889 Diag(DelLoc, diag::err_deleted_non_function);
9890 return;
9891 }
9892 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9893 Diag(DelLoc, diag::err_deleted_decl_not_first);
9894 Diag(Prev->getLocation(), diag::note_previous_declaration);
9895 // If the declaration wasn't the first, we delete the function anyway for
9896 // recovery.
9897 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009898 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00009899}
Sebastian Redl4c018662009-04-27 21:33:24 +00009900
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009901void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9902 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9903
9904 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +00009905 if (MD->getParent()->isDependentType()) {
9906 MD->setDefaulted();
9907 MD->setExplicitlyDefaulted();
9908 return;
9909 }
9910
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009911 CXXSpecialMember Member = getSpecialMember(MD);
9912 if (Member == CXXInvalid) {
9913 Diag(DefaultLoc, diag::err_default_special_members);
9914 return;
9915 }
9916
9917 MD->setDefaulted();
9918 MD->setExplicitlyDefaulted();
9919
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009920 // If this definition appears within the record, do the checking when
9921 // the record is complete.
9922 const FunctionDecl *Primary = MD;
9923 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9924 // Find the uninstantiated declaration that actually had the '= default'
9925 // on it.
9926 MD->getTemplateInstantiationPattern()->isDefined(Primary);
9927
9928 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009929 return;
9930
9931 switch (Member) {
9932 case CXXDefaultConstructor: {
9933 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9934 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +00009935 if (!CD->isInvalidDecl())
9936 DefineImplicitDefaultConstructor(DefaultLoc, CD);
9937 break;
9938 }
9939
9940 case CXXCopyConstructor: {
9941 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9942 CheckExplicitlyDefaultedCopyConstructor(CD);
9943 if (!CD->isInvalidDecl())
9944 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009945 break;
9946 }
Alexis Huntf91729462011-05-12 22:46:25 +00009947
Alexis Huntc9a55732011-05-14 05:23:28 +00009948 case CXXCopyAssignment: {
9949 CheckExplicitlyDefaultedCopyAssignment(MD);
9950 if (!MD->isInvalidDecl())
9951 DefineImplicitCopyAssignment(DefaultLoc, MD);
9952 break;
9953 }
9954
Alexis Huntf91729462011-05-12 22:46:25 +00009955 case CXXDestructor: {
9956 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9957 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +00009958 if (!DD->isInvalidDecl())
9959 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +00009960 break;
9961 }
9962
Sebastian Redl22653ba2011-08-30 19:58:05 +00009963 case CXXMoveConstructor: {
9964 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9965 CheckExplicitlyDefaultedMoveConstructor(CD);
9966 if (!CD->isInvalidDecl())
9967 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +00009968 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009969 }
Alexis Hunt119c10e2011-05-25 23:16:36 +00009970
Sebastian Redl22653ba2011-08-30 19:58:05 +00009971 case CXXMoveAssignment: {
9972 CheckExplicitlyDefaultedMoveAssignment(MD);
9973 if (!MD->isInvalidDecl())
9974 DefineImplicitMoveAssignment(DefaultLoc, MD);
9975 break;
9976 }
9977
9978 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +00009979 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009980 }
9981 } else {
9982 Diag(DefaultLoc, diag::err_default_special_members);
9983 }
9984}
9985
Sebastian Redl4c018662009-04-27 21:33:24 +00009986static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00009987 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00009988 Stmt *SubStmt = *CI;
9989 if (!SubStmt)
9990 continue;
9991 if (isa<ReturnStmt>(SubStmt))
9992 Self.Diag(SubStmt->getSourceRange().getBegin(),
9993 diag::err_return_in_constructor_handler);
9994 if (!isa<Expr>(SubStmt))
9995 SearchForReturnInStmt(Self, SubStmt);
9996 }
9997}
9998
9999void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10000 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10001 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10002 SearchForReturnInStmt(*this, Handler);
10003 }
10004}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010005
Mike Stump11289f42009-09-09 15:08:12 +000010006bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010007 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000010008 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10009 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010010
Chandler Carruth284bb2e2010-02-15 11:53:20 +000010011 if (Context.hasSameType(NewTy, OldTy) ||
10012 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010013 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010014
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010015 // Check if the return types are covariant
10016 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000010017
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010018 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010019 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10020 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010021 NewClassTy = NewPT->getPointeeType();
10022 OldClassTy = OldPT->getPointeeType();
10023 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010024 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10025 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10026 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10027 NewClassTy = NewRT->getPointeeType();
10028 OldClassTy = OldRT->getPointeeType();
10029 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010030 }
10031 }
Mike Stump11289f42009-09-09 15:08:12 +000010032
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010033 // The return types aren't either both pointers or references to a class type.
10034 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000010035 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010036 diag::err_different_return_type_for_overriding_virtual_function)
10037 << New->getDeclName() << NewTy << OldTy;
10038 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000010039
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010040 return true;
10041 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010042
Anders Carlssone60365b2009-12-31 18:34:24 +000010043 // C++ [class.virtual]p6:
10044 // If the return type of D::f differs from the return type of B::f, the
10045 // class type in the return type of D::f shall be complete at the point of
10046 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010047 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10048 if (!RT->isBeingDefined() &&
10049 RequireCompleteType(New->getLocation(), NewClassTy,
10050 PDiag(diag::err_covariant_return_incomplete)
10051 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000010052 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010053 }
Anders Carlssone60365b2009-12-31 18:34:24 +000010054
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000010055 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010056 // Check if the new class derives from the old class.
10057 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10058 Diag(New->getLocation(),
10059 diag::err_covariant_return_not_derived)
10060 << New->getDeclName() << NewTy << OldTy;
10061 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10062 return true;
10063 }
Mike Stump11289f42009-09-09 15:08:12 +000010064
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010065 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000010066 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000010067 diag::err_covariant_return_inaccessible_base,
10068 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10069 // FIXME: Should this point to the return type?
10070 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000010071 // FIXME: this note won't trigger for delayed access control
10072 // diagnostics, and it's impossible to get an undelayed error
10073 // here from access control during the original parse because
10074 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010075 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10076 return true;
10077 }
10078 }
Mike Stump11289f42009-09-09 15:08:12 +000010079
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010080 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010081 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010082 Diag(New->getLocation(),
10083 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010084 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010085 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10086 return true;
10087 };
Mike Stump11289f42009-09-09 15:08:12 +000010088
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010089
10090 // The new class type must have the same or less qualifiers as the old type.
10091 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10092 Diag(New->getLocation(),
10093 diag::err_covariant_return_type_class_type_more_qualified)
10094 << New->getDeclName() << NewTy << OldTy;
10095 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10096 return true;
10097 };
Mike Stump11289f42009-09-09 15:08:12 +000010098
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010099 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010100}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010101
Douglas Gregor21920e372009-12-01 17:24:26 +000010102/// \brief Mark the given method pure.
10103///
10104/// \param Method the method to be marked pure.
10105///
10106/// \param InitRange the source range that covers the "0" initializer.
10107bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010108 SourceLocation EndLoc = InitRange.getEnd();
10109 if (EndLoc.isValid())
10110 Method->setRangeEnd(EndLoc);
10111
Douglas Gregor21920e372009-12-01 17:24:26 +000010112 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10113 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000010114 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010115 }
Douglas Gregor21920e372009-12-01 17:24:26 +000010116
10117 if (!Method->isInvalidDecl())
10118 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10119 << Method->getDeclName() << InitRange;
10120 return true;
10121}
10122
John McCall1f4ee7b2009-12-19 09:28:58 +000010123/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10124/// an initializer for the out-of-line declaration 'Dcl'. The scope
10125/// is a fresh scope pushed for just this purpose.
10126///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010127/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10128/// static data member of class X, names should be looked up in the scope of
10129/// class X.
John McCall48871652010-08-21 09:40:31 +000010130void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010131 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010132 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010133
John McCall1f4ee7b2009-12-19 09:28:58 +000010134 // We should only get called for declarations with scope specifiers, like:
10135 // int foo::bar;
10136 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010137 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010138}
10139
10140/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000010141/// initializer for the out-of-line declaration 'D'.
10142void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010143 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010144 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010145
John McCall1f4ee7b2009-12-19 09:28:58 +000010146 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010147 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010148}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010149
10150/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10151/// C++ if/switch/while/for statement.
10152/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000010153DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010154 // C++ 6.4p2:
10155 // The declarator shall not specify a function or an array.
10156 // The type-specifier-seq shall not contain typedef and shall not declare a
10157 // new class or enumeration.
10158 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10159 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010160
10161 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010162 if (!Dcl)
10163 return true;
10164
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010165 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10166 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010167 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010168 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010169 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010170
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010171 return Dcl;
10172}
Anders Carlssonf98849e2009-12-02 17:15:43 +000010173
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010174void Sema::LoadExternalVTableUses() {
10175 if (!ExternalSource)
10176 return;
10177
10178 SmallVector<ExternalVTableUse, 4> VTables;
10179 ExternalSource->ReadUsedVTables(VTables);
10180 SmallVector<VTableUse, 4> NewUses;
10181 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10182 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10183 = VTablesUsed.find(VTables[I].Record);
10184 // Even if a definition wasn't required before, it may be required now.
10185 if (Pos != VTablesUsed.end()) {
10186 if (!Pos->second && VTables[I].DefinitionRequired)
10187 Pos->second = true;
10188 continue;
10189 }
10190
10191 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10192 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10193 }
10194
10195 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10196}
10197
Douglas Gregor88d292c2010-05-13 16:44:06 +000010198void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10199 bool DefinitionRequired) {
10200 // Ignore any vtable uses in unevaluated operands or for classes that do
10201 // not have a vtable.
10202 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10203 CurContext->isDependentContext() ||
10204 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +000010205 return;
10206
Douglas Gregor88d292c2010-05-13 16:44:06 +000010207 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010208 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010209 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10210 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10211 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10212 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000010213 // If we already had an entry, check to see if we are promoting this vtable
10214 // to required a definition. If so, we need to reappend to the VTableUses
10215 // list, since we may have already processed the first entry.
10216 if (DefinitionRequired && !Pos.first->second) {
10217 Pos.first->second = true;
10218 } else {
10219 // Otherwise, we can early exit.
10220 return;
10221 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010222 }
10223
10224 // Local classes need to have their virtual members marked
10225 // immediately. For all other classes, we mark their virtual members
10226 // at the end of the translation unit.
10227 if (Class->isLocalClass())
10228 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000010229 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000010230 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000010231}
10232
Douglas Gregor88d292c2010-05-13 16:44:06 +000010233bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010234 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010235 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000010236 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000010237
Douglas Gregor88d292c2010-05-13 16:44:06 +000010238 // Note: The VTableUses vector could grow as a result of marking
10239 // the members of a class as "used", so we check the size each
10240 // time through the loop and prefer indices (with are stable) to
10241 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000010242 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010243 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000010244 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010245 if (!Class)
10246 continue;
10247
10248 SourceLocation Loc = VTableUses[I].second;
10249
10250 // If this class has a key function, but that key function is
10251 // defined in another translation unit, we don't need to emit the
10252 // vtable even though we're using it.
10253 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010254 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000010255 switch (KeyFunction->getTemplateSpecializationKind()) {
10256 case TSK_Undeclared:
10257 case TSK_ExplicitSpecialization:
10258 case TSK_ExplicitInstantiationDeclaration:
10259 // The key function is in another translation unit.
10260 continue;
10261
10262 case TSK_ExplicitInstantiationDefinition:
10263 case TSK_ImplicitInstantiation:
10264 // We will be instantiating the key function.
10265 break;
10266 }
10267 } else if (!KeyFunction) {
10268 // If we have a class with no key function that is the subject
10269 // of an explicit instantiation declaration, suppress the
10270 // vtable; it will live with the explicit instantiation
10271 // definition.
10272 bool IsExplicitInstantiationDeclaration
10273 = Class->getTemplateSpecializationKind()
10274 == TSK_ExplicitInstantiationDeclaration;
10275 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10276 REnd = Class->redecls_end();
10277 R != REnd; ++R) {
10278 TemplateSpecializationKind TSK
10279 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10280 if (TSK == TSK_ExplicitInstantiationDeclaration)
10281 IsExplicitInstantiationDeclaration = true;
10282 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10283 IsExplicitInstantiationDeclaration = false;
10284 break;
10285 }
10286 }
10287
10288 if (IsExplicitInstantiationDeclaration)
10289 continue;
10290 }
10291
10292 // Mark all of the virtual members of this class as referenced, so
10293 // that we can build a vtable. Then, tell the AST consumer that a
10294 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000010295 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010296 MarkVirtualMembersReferenced(Loc, Class);
10297 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10298 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10299
10300 // Optionally warn if we're emitting a weak vtable.
10301 if (Class->getLinkage() == ExternalLinkage &&
10302 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000010303 const FunctionDecl *KeyFunctionDef = 0;
10304 if (!KeyFunction ||
10305 (KeyFunction->hasBody(KeyFunctionDef) &&
10306 KeyFunctionDef->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +000010307 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10308 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000010309 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010310 VTableUses.clear();
10311
Douglas Gregor97509692011-04-22 22:25:37 +000010312 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000010313}
Anders Carlsson82fccd02009-12-07 08:24:59 +000010314
Rafael Espindola5b334082010-03-26 00:36:59 +000010315void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10316 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +000010317 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10318 e = RD->method_end(); i != e; ++i) {
10319 CXXMethodDecl *MD = *i;
10320
10321 // C++ [basic.def.odr]p2:
10322 // [...] A virtual member function is used if it is not pure. [...]
10323 if (MD->isVirtual() && !MD->isPure())
10324 MarkDeclarationReferenced(Loc, MD);
10325 }
Rafael Espindola5b334082010-03-26 00:36:59 +000010326
10327 // Only classes that have virtual bases need a VTT.
10328 if (RD->getNumVBases() == 0)
10329 return;
10330
10331 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10332 e = RD->bases_end(); i != e; ++i) {
10333 const CXXRecordDecl *Base =
10334 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000010335 if (Base->getNumVBases() == 0)
10336 continue;
10337 MarkVirtualMembersReferenced(Loc, Base);
10338 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000010339}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010340
10341/// SetIvarInitializers - This routine builds initialization ASTs for the
10342/// Objective-C implementation whose ivars need be initialized.
10343void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10344 if (!getLangOptions().CPlusPlus)
10345 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000010346 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010347 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010348 CollectIvarsToConstructOrDestruct(OID, ivars);
10349 if (ivars.empty())
10350 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010351 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010352 for (unsigned i = 0; i < ivars.size(); i++) {
10353 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000010354 if (Field->isInvalidDecl())
10355 continue;
10356
Alexis Hunt1d792652011-01-08 20:30:50 +000010357 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010358 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10359 InitializationKind InitKind =
10360 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10361
10362 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +000010363 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +000010364 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +000010365 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010366 // Note, MemberInit could actually come back empty if no initialization
10367 // is required (e.g., because it would call a trivial default constructor)
10368 if (!MemberInit.get() || MemberInit.isInvalid())
10369 continue;
John McCallacf0ee52010-10-08 02:01:28 +000010370
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010371 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000010372 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10373 SourceLocation(),
10374 MemberInit.takeAs<Expr>(),
10375 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010376 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000010377
10378 // Be sure that the destructor is accessible and is marked as referenced.
10379 if (const RecordType *RecordTy
10380 = Context.getBaseElementType(Field->getType())
10381 ->getAs<RecordType>()) {
10382 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000010383 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +000010384 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10385 CheckDestructorAccess(Field->getLocation(), Destructor,
10386 PDiag(diag::err_access_dtor_ivar)
10387 << Context.getBaseElementType(Field->getType()));
10388 }
10389 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010390 }
10391 ObjCImplementation->setIvarInitializers(Context,
10392 AllToInit.data(), AllToInit.size());
10393 }
10394}
Alexis Hunt6118d662011-05-04 05:57:24 +000010395
Alexis Hunt27a761d2011-05-04 23:29:54 +000010396static
10397void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10398 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10399 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10400 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10401 Sema &S) {
10402 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10403 CE = Current.end();
10404 if (Ctor->isInvalidDecl())
10405 return;
10406
10407 const FunctionDecl *FNTarget = 0;
10408 CXXConstructorDecl *Target;
10409
10410 // We ignore the result here since if we don't have a body, Target will be
10411 // null below.
10412 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10413 Target
10414= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10415
10416 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10417 // Avoid dereferencing a null pointer here.
10418 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10419
10420 if (!Current.insert(Canonical))
10421 return;
10422
10423 // We know that beyond here, we aren't chaining into a cycle.
10424 if (!Target || !Target->isDelegatingConstructor() ||
10425 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10426 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10427 Valid.insert(*CI);
10428 Current.clear();
10429 // We've hit a cycle.
10430 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10431 Current.count(TCanonical)) {
10432 // If we haven't diagnosed this cycle yet, do so now.
10433 if (!Invalid.count(TCanonical)) {
10434 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000010435 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000010436 << Ctor;
10437
10438 // Don't add a note for a function delegating directo to itself.
10439 if (TCanonical != Canonical)
10440 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10441
10442 CXXConstructorDecl *C = Target;
10443 while (C->getCanonicalDecl() != Canonical) {
10444 (void)C->getTargetConstructor()->hasBody(FNTarget);
10445 assert(FNTarget && "Ctor cycle through bodiless function");
10446
10447 C
10448 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10449 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10450 }
10451 }
10452
10453 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10454 Invalid.insert(*CI);
10455 Current.clear();
10456 } else {
10457 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10458 }
10459}
10460
10461
Alexis Hunt6118d662011-05-04 05:57:24 +000010462void Sema::CheckDelegatingCtorCycles() {
10463 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10464
Alexis Hunt27a761d2011-05-04 23:29:54 +000010465 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10466 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000010467
Douglas Gregorbae31202011-07-27 21:57:17 +000010468 for (DelegatingCtorDeclsType::iterator
10469 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000010470 E = DelegatingCtorDecls.end();
10471 I != E; ++I) {
10472 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +000010473 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000010474
10475 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10476 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000010477}