blob: ecbff96297ed7f185b2d73f999572c416a20b48e [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 Gregora007d362010-10-13 22:19:53 +00001124 if (SS.isSet() && !SS.isInvalid()) {
1125 // The user provided a superfluous scope specifier inside a class
1126 // definition:
1127 //
1128 // class X {
1129 // int X::member;
1130 // };
1131 DeclContext *DC = 0;
1132 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1133 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1134 << Name << FixItHint::CreateRemoval(SS.getRange());
1135 else
1136 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1137 << Name << SS.getRange();
1138
1139 SS.clear();
1140 }
1141
Douglas Gregor3447e762009-08-20 22:52:58 +00001142 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001143 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001144 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001145 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001146 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001147 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001148 assert(!HasDeferredInit);
1149
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001150 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001151 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001152 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001153 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001154
1155 // Non-instance-fields can't have a bitfield.
1156 if (BitWidth) {
1157 if (Member->isInvalidDecl()) {
1158 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001159 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001160 // C++ 9.6p3: A bit-field shall not be a static member.
1161 // "static member 'A' cannot be a bit-field"
1162 Diag(Loc, diag::err_static_not_bitfield)
1163 << Name << BitWidth->getSourceRange();
1164 } else if (isa<TypedefDecl>(Member)) {
1165 // "typedef member 'x' cannot be a bit-field"
1166 Diag(Loc, diag::err_typedef_not_bitfield)
1167 << Name << BitWidth->getSourceRange();
1168 } else {
1169 // A function typedef ("typedef int f(); f a;").
1170 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1171 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001172 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001173 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001174 }
Mike Stump11289f42009-09-09 15:08:12 +00001175
Chris Lattnerd26760a2009-03-05 23:01:03 +00001176 BitWidth = 0;
1177 Member->setInvalidDecl();
1178 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001179
1180 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001181
Douglas Gregor3447e762009-08-20 22:52:58 +00001182 // If we have declared a member function template, set the access of the
1183 // templated declaration as well.
1184 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1185 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001186 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001187
Anders Carlsson13a69102011-01-20 04:34:22 +00001188 if (VS.isOverrideSpecified()) {
1189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1190 if (!MD || !MD->isVirtual()) {
1191 Diag(Member->getLocStart(),
1192 diag::override_keyword_only_allowed_on_virtual_member_functions)
1193 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001194 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001195 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001196 }
1197 if (VS.isFinalSpecified()) {
1198 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1199 if (!MD || !MD->isVirtual()) {
1200 Diag(Member->getLocStart(),
1201 diag::override_keyword_only_allowed_on_virtual_member_functions)
1202 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001203 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001204 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001205 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001206
Douglas Gregorf2f08062011-03-08 17:10:18 +00001207 if (VS.getLastLocation().isValid()) {
1208 // Update the end location of a method that has a virt-specifiers.
1209 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1210 MD->setRangeEnd(VS.getLastLocation());
1211 }
1212
Anders Carlssonc87f8612011-01-20 06:29:02 +00001213 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001214
Douglas Gregor92751d42008-11-17 22:58:34 +00001215 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001216
Douglas Gregor0c880302009-03-11 23:00:04 +00001217 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001218 AddInitializerToDecl(Member, Init, false,
1219 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith938f40b2011-06-11 17:19:42 +00001220 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1221 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1222 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1223 // data member if a brace-or-equal-initializer is provided.
1224 Diag(Loc, diag::err_auto_var_requires_init)
1225 << Name << cast<ValueDecl>(Member)->getType();
1226 Member->setInvalidDecl();
1227 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001228
Richard Smithb2bc2e62011-02-21 20:05:19 +00001229 FinalizeDeclaration(Member);
1230
John McCall25849ca2011-02-15 07:12:36 +00001231 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001232 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001233 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001234}
1235
Richard Smith938f40b2011-06-11 17:19:42 +00001236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00001237/// in-class initializer for a non-static C++ class member, and after
1238/// instantiating an in-class initializer in a class template. Such actions
1239/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00001240void
1241Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1242 Expr *InitExpr) {
1243 FieldDecl *FD = cast<FieldDecl>(D);
1244
1245 if (!InitExpr) {
1246 FD->setInvalidDecl();
1247 FD->removeInClassInitializer();
1248 return;
1249 }
1250
1251 ExprResult Init = InitExpr;
1252 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1253 // FIXME: if there is no EqualLoc, this is list-initialization.
1254 Init = PerformCopyInitialization(
1255 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1256 if (Init.isInvalid()) {
1257 FD->setInvalidDecl();
1258 return;
1259 }
1260
1261 CheckImplicitConversions(Init.get(), EqualLoc);
1262 }
1263
1264 // C++0x [class.base.init]p7:
1265 // The initialization of each base and member constitutes a
1266 // full-expression.
1267 Init = MaybeCreateExprWithCleanups(Init);
1268 if (Init.isInvalid()) {
1269 FD->setInvalidDecl();
1270 return;
1271 }
1272
1273 InitExpr = Init.release();
1274
1275 FD->setInClassInitializer(InitExpr);
1276}
1277
Douglas Gregor15e77a22009-12-31 09:10:24 +00001278/// \brief Find the direct and/or virtual base specifiers that
1279/// correspond to the given base type, for use in base initialization
1280/// within a constructor.
1281static bool FindBaseInitializer(Sema &SemaRef,
1282 CXXRecordDecl *ClassDecl,
1283 QualType BaseType,
1284 const CXXBaseSpecifier *&DirectBaseSpec,
1285 const CXXBaseSpecifier *&VirtualBaseSpec) {
1286 // First, check for a direct base class.
1287 DirectBaseSpec = 0;
1288 for (CXXRecordDecl::base_class_const_iterator Base
1289 = ClassDecl->bases_begin();
1290 Base != ClassDecl->bases_end(); ++Base) {
1291 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1292 // We found a direct base of this type. That's what we're
1293 // initializing.
1294 DirectBaseSpec = &*Base;
1295 break;
1296 }
1297 }
1298
1299 // Check for a virtual base class.
1300 // FIXME: We might be able to short-circuit this if we know in advance that
1301 // there are no virtual bases.
1302 VirtualBaseSpec = 0;
1303 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1304 // We haven't found a base yet; search the class hierarchy for a
1305 // virtual base class.
1306 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1307 /*DetectVirtual=*/false);
1308 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1309 BaseType, Paths)) {
1310 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1311 Path != Paths.end(); ++Path) {
1312 if (Path->back().Base->isVirtual()) {
1313 VirtualBaseSpec = Path->back().Base;
1314 break;
1315 }
1316 }
1317 }
1318 }
1319
1320 return DirectBaseSpec || VirtualBaseSpec;
1321}
1322
Douglas Gregore8381c02008-11-05 04:29:56 +00001323/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001324MemInitResult
John McCall48871652010-08-21 09:40:31 +00001325Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001326 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001327 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001328 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001329 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001330 SourceLocation IdLoc,
1331 SourceLocation LParenLoc,
Richard Trieu2bd04012011-09-09 02:00:50 +00001332 Expr **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001333 SourceLocation RParenLoc,
1334 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001335 if (!ConstructorD)
1336 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001337
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001338 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001339
1340 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001341 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001342 if (!Constructor) {
1343 // The user wrote a constructor initializer on a function that is
1344 // not a C++ constructor. Ignore the error for now, because we may
1345 // have more member initializers coming; we'll diagnose it just
1346 // once in ActOnMemInitializers.
1347 return true;
1348 }
1349
1350 CXXRecordDecl *ClassDecl = Constructor->getParent();
1351
1352 // C++ [class.base.init]p2:
1353 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001354 // constructor's class and, if not found in that scope, are looked
1355 // up in the scope containing the constructor's definition.
1356 // [Note: if the constructor's class contains a member with the
1357 // same name as a direct or virtual base class of the class, a
1358 // mem-initializer-id naming the member or base class and composed
1359 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001360 // mem-initializer-id for the hidden base class may be specified
1361 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001362 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001363 // Look for a member, first.
1364 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001365 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001366 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001367 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001368 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001369
Douglas Gregor44e7df62011-01-04 00:32:56 +00001370 if (Member) {
1371 if (EllipsisLoc.isValid())
1372 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1373 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1374
Francois Pichetd583da02010-12-04 09:14:42 +00001375 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001376 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001377 }
1378
Francois Pichetd583da02010-12-04 09:14:42 +00001379 // Handle anonymous union case.
1380 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001381 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1382 if (EllipsisLoc.isValid())
1383 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1384 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1385
Francois Pichetd583da02010-12-04 09:14:42 +00001386 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1387 NumArgs, IdLoc,
1388 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001389 }
Francois Pichetd583da02010-12-04 09:14:42 +00001390 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001391 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001392 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001393 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001394 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001395
1396 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001397 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001398 } else {
1399 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1400 LookupParsedName(R, S, &SS);
1401
1402 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1403 if (!TyD) {
1404 if (R.isAmbiguous()) return true;
1405
John McCallda6841b2010-04-09 19:01:14 +00001406 // We don't want access-control diagnostics here.
1407 R.suppressDiagnostics();
1408
Douglas Gregora3b624a2010-01-19 06:46:48 +00001409 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1410 bool NotUnknownSpecialization = false;
1411 DeclContext *DC = computeDeclContext(SS, false);
1412 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1413 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1414
1415 if (!NotUnknownSpecialization) {
1416 // When the scope specifier can refer to a member of an unknown
1417 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001418 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1419 SS.getWithLocInContext(Context),
1420 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001421 if (BaseType.isNull())
1422 return true;
1423
Douglas Gregora3b624a2010-01-19 06:46:48 +00001424 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001425 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001426 }
1427 }
1428
Douglas Gregor15e77a22009-12-31 09:10:24 +00001429 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001430 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00001431 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001432 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1433 ClassDecl, false, CTC_NoKeywords))) {
1434 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1435 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1436 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001437 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001438 // We have found a non-static data member with a similar
1439 // name to what was typed; complain and initialize that
1440 // member.
1441 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001442 << MemberOrBase << true << CorrectedQuotedStr
1443 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor6da83622010-01-07 00:17:44 +00001444 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001445 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001446
1447 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1448 LParenLoc, RParenLoc);
1449 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001450 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001451 const CXXBaseSpecifier *DirectBaseSpec;
1452 const CXXBaseSpecifier *VirtualBaseSpec;
1453 if (FindBaseInitializer(*this, ClassDecl,
1454 Context.getTypeDeclType(Type),
1455 DirectBaseSpec, VirtualBaseSpec)) {
1456 // We have found a direct or virtual base class with a
1457 // similar name to what was typed; complain and initialize
1458 // that base class.
1459 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001460 << MemberOrBase << false << CorrectedQuotedStr
1461 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001462
1463 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1464 : VirtualBaseSpec;
1465 Diag(BaseSpec->getSourceRange().getBegin(),
1466 diag::note_base_class_specified_here)
1467 << BaseSpec->getType()
1468 << BaseSpec->getSourceRange();
1469
Douglas Gregor15e77a22009-12-31 09:10:24 +00001470 TyD = Type;
1471 }
1472 }
1473 }
1474
Douglas Gregora3b624a2010-01-19 06:46:48 +00001475 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001476 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1477 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1478 return true;
1479 }
John McCallb5a0d312009-12-21 10:41:20 +00001480 }
1481
Douglas Gregora3b624a2010-01-19 06:46:48 +00001482 if (BaseType.isNull()) {
1483 BaseType = Context.getTypeDeclType(TyD);
1484 if (SS.isSet()) {
1485 NestedNameSpecifier *Qualifier =
1486 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001487
Douglas Gregora3b624a2010-01-19 06:46:48 +00001488 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001489 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001490 }
John McCallb5a0d312009-12-21 10:41:20 +00001491 }
1492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
John McCallbcd03502009-12-07 02:54:59 +00001494 if (!TInfo)
1495 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001496
John McCallbcd03502009-12-07 02:54:59 +00001497 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001498 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001499}
1500
Chandler Carruth599deef2011-09-03 01:14:15 +00001501/// Checks a member initializer expression for cases where reference (or
1502/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00001503static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1504 Expr *Init,
1505 SourceLocation IdLoc) {
1506 QualType MemberTy = Member->getType();
1507
1508 // We only handle pointers and references currently.
1509 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1510 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1511 return;
1512
1513 const bool IsPointer = MemberTy->isPointerType();
1514 if (IsPointer) {
1515 if (const UnaryOperator *Op
1516 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1517 // The only case we're worried about with pointers requires taking the
1518 // address.
1519 if (Op->getOpcode() != UO_AddrOf)
1520 return;
1521
1522 Init = Op->getSubExpr();
1523 } else {
1524 // We only handle address-of expression initializers for pointers.
1525 return;
1526 }
1527 }
1528
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001529 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1530 // Taking the address of a temporary will be diagnosed as a hard error.
1531 if (IsPointer)
1532 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001533
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001534 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1535 << Member << Init->getSourceRange();
1536 } else if (const DeclRefExpr *DRE
1537 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1538 // We only warn when referring to a non-reference parameter declaration.
1539 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1540 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00001541 return;
1542
1543 S.Diag(Init->getExprLoc(),
1544 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1545 : diag::warn_bind_ref_member_to_parameter)
1546 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001547 } else {
1548 // Other initializers are fine.
1549 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001550 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001551
1552 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1553 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00001554}
1555
John McCalle22a04a2009-11-04 23:02:40 +00001556/// Checks an initializer expression for use of uninitialized fields, such as
1557/// containing the field that is being initialized. Returns true if there is an
1558/// uninitialized field was used an updates the SourceLocation parameter; false
1559/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001560static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001561 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001562 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001563 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1564
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001565 if (isa<CallExpr>(S)) {
1566 // Do not descend into function calls or constructors, as the use
1567 // of an uninitialized field may be valid. One would have to inspect
1568 // the contents of the function/ctor to determine if it is safe or not.
1569 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1570 // may be safe, depending on what the function/ctor does.
1571 return false;
1572 }
1573 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1574 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001575
1576 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1577 // The member expression points to a static data member.
1578 assert(VD->isStaticDataMember() &&
1579 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001580 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001581 return false;
1582 }
1583
1584 if (isa<EnumConstantDecl>(RhsField)) {
1585 // The member expression points to an enum.
1586 return false;
1587 }
1588
John McCalle22a04a2009-11-04 23:02:40 +00001589 if (RhsField == LhsField) {
1590 // Initializing a field with itself. Throw a warning.
1591 // But wait; there are exceptions!
1592 // Exception #1: The field may not belong to this record.
1593 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001594 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001595 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1596 // Even though the field matches, it does not belong to this record.
1597 return false;
1598 }
1599 // None of the exceptions triggered; return true to indicate an
1600 // uninitialized field was used.
1601 *L = ME->getMemberLoc();
1602 return true;
1603 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001604 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001605 // sizeof/alignof doesn't reference contents, do not warn.
1606 return false;
1607 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1608 // address-of doesn't reference contents (the pointer may be dereferenced
1609 // in the same expression but it would be rare; and weird).
1610 if (UOE->getOpcode() == UO_AddrOf)
1611 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001612 }
John McCall8322c3a2011-02-13 04:07:26 +00001613 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001614 if (!*it) {
1615 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001616 continue;
1617 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001618 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1619 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001620 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001621 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001622}
1623
John McCallfaf5fb42010-08-26 23:41:50 +00001624MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001625Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001626 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001627 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001628 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001629 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1630 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1631 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001632 "Member must be a FieldDecl or IndirectFieldDecl");
1633
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001634 if (Member->isInvalidDecl())
1635 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001636
John McCalle22a04a2009-11-04 23:02:40 +00001637 // Diagnose value-uses of fields to initialize themselves, e.g.
1638 // foo(foo)
1639 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001640 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001641 for (unsigned i = 0; i < NumArgs; ++i) {
1642 SourceLocation L;
1643 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1644 // FIXME: Return true in the case when other fields are used before being
1645 // uninitialized. For example, let this field be the i'th field. When
1646 // initializing the i'th field, throw a warning if any of the >= i'th
1647 // fields are used, as they are not yet initialized.
1648 // Right now we are only handling the case where the i'th field uses
1649 // itself in its initializer.
1650 Diag(L, diag::warn_field_is_uninit);
1651 }
1652 }
1653
Eli Friedman8e1433b2009-07-29 19:44:27 +00001654 bool HasDependentArg = false;
1655 for (unsigned i = 0; i < NumArgs; i++)
1656 HasDependentArg |= Args[i]->isTypeDependent();
1657
Chandler Carruthd44c3102010-12-06 09:23:57 +00001658 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001659 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001660 // Can't check initialization for a member of dependent type or when
1661 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001662 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001663 RParenLoc,
1664 Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001665
John McCall31168b02011-06-15 23:02:42 +00001666 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00001667 } else {
1668 // Initialize the member.
1669 InitializedEntity MemberEntity =
1670 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1671 : InitializedEntity::InitializeMember(IndirectMember, 0);
1672 InitializationKind Kind =
1673 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001674
Chandler Carruthd44c3102010-12-06 09:23:57 +00001675 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1676
1677 ExprResult MemberInit =
1678 InitSeq.Perform(*this, MemberEntity, Kind,
1679 MultiExprArg(*this, Args, NumArgs), 0);
1680 if (MemberInit.isInvalid())
1681 return true;
1682
1683 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1684
1685 // C++0x [class.base.init]p7:
1686 // The initialization of each base and member constitutes a
1687 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001688 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001689 if (MemberInit.isInvalid())
1690 return true;
1691
1692 // If we are in a dependent context, template instantiation will
1693 // perform this type-checking again. Just save the arguments that we
1694 // received in a ParenListExpr.
1695 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1696 // of the information that we have about the member
1697 // initializer. However, deconstructing the ASTs is a dicey process,
1698 // and this approach is far more likely to get the corner cases right.
Chandler Carruth599deef2011-09-03 01:14:15 +00001699 if (CurContext->isDependentContext()) {
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001700 Init = new (Context) ParenListExpr(
1701 Context, LParenLoc, Args, NumArgs, RParenLoc,
1702 Member->getType().getNonReferenceType());
Chandler Carruth599deef2011-09-03 01:14:15 +00001703 } else {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001704 Init = MemberInit.get();
Chandler Carruth599deef2011-09-03 01:14:15 +00001705 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
1706 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001707 }
1708
Chandler Carruthd44c3102010-12-06 09:23:57 +00001709 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001710 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001711 IdLoc, LParenLoc, Init,
1712 RParenLoc);
1713 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001714 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001715 IdLoc, LParenLoc, Init,
1716 RParenLoc);
1717 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001718}
1719
John McCallfaf5fb42010-08-26 23:41:50 +00001720MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001721Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1722 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001723 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001724 SourceLocation LParenLoc,
1725 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001726 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001727 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1728 if (!LangOpts.CPlusPlus0x)
1729 return Diag(Loc, diag::err_delegation_0x_only)
1730 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001731
Alexis Huntc5575cc2011-02-26 19:13:13 +00001732 // Initialize the object.
1733 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1734 QualType(ClassDecl->getTypeForDecl(), 0));
1735 InitializationKind Kind =
1736 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1737
1738 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1739
1740 ExprResult DelegationInit =
1741 InitSeq.Perform(*this, DelegationEntity, Kind,
1742 MultiExprArg(*this, Args, NumArgs), 0);
1743 if (DelegationInit.isInvalid())
1744 return true;
1745
1746 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00001747 CXXConstructorDecl *Constructor
1748 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00001749 assert(Constructor && "Delegating constructor with no target?");
1750
1751 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1752
1753 // C++0x [class.base.init]p7:
1754 // The initialization of each base and member constitutes a
1755 // full-expression.
1756 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1757 if (DelegationInit.isInvalid())
1758 return true;
1759
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001760 assert(!CurContext->isDependentContext());
Alexis Huntc5575cc2011-02-26 19:13:13 +00001761 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1762 DelegationInit.takeAs<Expr>(),
1763 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001764}
1765
1766MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001767Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001768 Expr **Args, unsigned NumArgs,
1769 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001770 CXXRecordDecl *ClassDecl,
1771 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001772 bool HasDependentArg = false;
1773 for (unsigned i = 0; i < NumArgs; i++)
1774 HasDependentArg |= Args[i]->isTypeDependent();
1775
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001776 SourceLocation BaseLoc
1777 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1778
1779 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1780 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1781 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1782
1783 // C++ [class.base.init]p2:
1784 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001785 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001786 // of that class, the mem-initializer is ill-formed. A
1787 // mem-initializer-list can initialize a base class using any
1788 // name that denotes that base class type.
1789 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1790
Douglas Gregor44e7df62011-01-04 00:32:56 +00001791 if (EllipsisLoc.isValid()) {
1792 // This is a pack expansion.
1793 if (!BaseType->containsUnexpandedParameterPack()) {
1794 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1795 << SourceRange(BaseLoc, RParenLoc);
1796
1797 EllipsisLoc = SourceLocation();
1798 }
1799 } else {
1800 // Check for any unexpanded parameter packs.
1801 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1802 return true;
1803
1804 for (unsigned I = 0; I != NumArgs; ++I)
1805 if (DiagnoseUnexpandedParameterPack(Args[I]))
1806 return true;
1807 }
1808
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001809 // Check for direct and virtual base classes.
1810 const CXXBaseSpecifier *DirectBaseSpec = 0;
1811 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1812 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001813 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1814 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001815 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1816 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001817
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001818 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1819 VirtualBaseSpec);
1820
1821 // C++ [base.class.init]p2:
1822 // Unless the mem-initializer-id names a nonstatic data member of the
1823 // constructor's class or a direct or virtual base of that class, the
1824 // mem-initializer is ill-formed.
1825 if (!DirectBaseSpec && !VirtualBaseSpec) {
1826 // If the class has any dependent bases, then it's possible that
1827 // one of those types will resolve to the same type as
1828 // BaseType. Therefore, just treat this as a dependent base
1829 // class initialization. FIXME: Should we try to check the
1830 // initialization anyway? It seems odd.
1831 if (ClassDecl->hasAnyDependentBases())
1832 Dependent = true;
1833 else
1834 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1835 << BaseType << Context.getTypeDeclType(ClassDecl)
1836 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1837 }
1838 }
1839
1840 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001841 // Can't check initialization for a base of dependent type or when
1842 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001843 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001844 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001845 RParenLoc, BaseType));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001846
John McCall31168b02011-06-15 23:02:42 +00001847 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001848
Alexis Hunt1d792652011-01-08 20:30:50 +00001849 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001850 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001851 LParenLoc,
1852 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001853 RParenLoc,
1854 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001855 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001856
1857 // C++ [base.class.init]p2:
1858 // If a mem-initializer-id is ambiguous because it designates both
1859 // a direct non-virtual base class and an inherited virtual base
1860 // class, the mem-initializer is ill-formed.
1861 if (DirectBaseSpec && VirtualBaseSpec)
1862 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001863 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001864
1865 CXXBaseSpecifier *BaseSpec
1866 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1867 if (!BaseSpec)
1868 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1869
1870 // Initialize the base.
1871 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001872 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001873 InitializationKind Kind =
1874 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1875
1876 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1877
John McCalldadc5752010-08-24 06:29:42 +00001878 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001879 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001880 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001881 if (BaseInit.isInvalid())
1882 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001883
1884 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001885
1886 // C++0x [class.base.init]p7:
1887 // The initialization of each base and member constitutes a
1888 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001889 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001890 if (BaseInit.isInvalid())
1891 return true;
1892
1893 // If we are in a dependent context, template instantiation will
1894 // perform this type-checking again. Just save the arguments that we
1895 // received in a ParenListExpr.
1896 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1897 // of the information that we have about the base
1898 // initializer. However, deconstructing the ASTs is a dicey process,
1899 // and this approach is far more likely to get the corner cases right.
1900 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001901 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001902 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001903 RParenLoc, BaseType));
Alexis Hunt1d792652011-01-08 20:30:50 +00001904 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001905 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001906 LParenLoc,
1907 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001908 RParenLoc,
1909 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001910 }
1911
Alexis Hunt1d792652011-01-08 20:30:50 +00001912 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001913 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001914 LParenLoc,
1915 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001916 RParenLoc,
1917 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001918}
1919
Sebastian Redl22653ba2011-08-30 19:58:05 +00001920// Create a static_cast\<T&&>(expr).
1921static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
1922 QualType ExprType = E->getType();
1923 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
1924 SourceLocation ExprLoc = E->getLocStart();
1925 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
1926 TargetType, ExprLoc);
1927
1928 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1929 SourceRange(ExprLoc, ExprLoc),
1930 E->getSourceRange()).take();
1931}
1932
Anders Carlsson1b00e242010-04-23 03:10:23 +00001933/// ImplicitInitializerKind - How an implicit base or member initializer should
1934/// initialize its base or member.
1935enum ImplicitInitializerKind {
1936 IIK_Default,
1937 IIK_Copy,
1938 IIK_Move
1939};
1940
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001941static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001942BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001943 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001944 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001945 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001946 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001947 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001948 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1949 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001950
John McCalldadc5752010-08-24 06:29:42 +00001951 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001952
1953 switch (ImplicitInitKind) {
1954 case IIK_Default: {
1955 InitializationKind InitKind
1956 = InitializationKind::CreateDefault(Constructor->getLocation());
1957 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1958 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001959 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001960 break;
1961 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001962
Sebastian Redl22653ba2011-08-30 19:58:05 +00001963 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00001964 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00001965 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001966 ParmVarDecl *Param = Constructor->getParamDecl(0);
1967 QualType ParamType = Param->getType().getNonReferenceType();
1968
1969 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001970 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001971 Constructor->getLocation(), ParamType,
1972 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00001973
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001974 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001975 QualType ArgTy =
1976 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1977 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001978
Sebastian Redl22653ba2011-08-30 19:58:05 +00001979 if (Moving) {
1980 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
1981 }
1982
John McCallcf142162010-08-07 06:22:56 +00001983 CXXCastPath BasePath;
1984 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001985 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1986 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00001987 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00001988 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001989
Anders Carlsson1b00e242010-04-23 03:10:23 +00001990 InitializationKind InitKind
1991 = InitializationKind::CreateDirect(Constructor->getLocation(),
1992 SourceLocation(), SourceLocation());
1993 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1994 &CopyCtorArg, 1);
1995 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001996 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001997 break;
1998 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00001999 }
John McCallb268a282010-08-23 23:25:46 +00002000
Douglas Gregora40433a2010-12-07 00:41:46 +00002001 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002002 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002003 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002004
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002005 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002006 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002007 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2008 SourceLocation()),
2009 BaseSpec->isVirtual(),
2010 SourceLocation(),
2011 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002012 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002013 SourceLocation());
2014
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002015 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002016}
2017
Sebastian Redl22653ba2011-08-30 19:58:05 +00002018static bool RefersToRValueRef(Expr *MemRef) {
2019 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2020 return Referenced->getType()->isRValueReferenceType();
2021}
2022
Anders Carlsson3c1db572010-04-23 02:15:47 +00002023static bool
2024BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002025 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002026 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002027 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002028 if (Field->isInvalidDecl())
2029 return true;
2030
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002031 SourceLocation Loc = Constructor->getLocation();
2032
Sebastian Redl22653ba2011-08-30 19:58:05 +00002033 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2034 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002035 ParmVarDecl *Param = Constructor->getParamDecl(0);
2036 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002037
2038 // Suppress copying zero-width bitfields.
2039 if (const Expr *Width = Field->getBitWidth())
2040 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2041 return false;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002042
2043 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00002044 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002045 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002046
Sebastian Redl22653ba2011-08-30 19:58:05 +00002047 if (Moving) {
2048 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2049 }
2050
Douglas Gregor94f9a482010-05-05 05:51:00 +00002051 // Build a reference to this field within the parameter.
2052 CXXScopeSpec SS;
2053 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2054 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002055 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2056 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002057 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002058 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002059 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002060 ParamType, Loc,
2061 /*IsArrow=*/false,
2062 SS,
2063 /*FirstQualifierInScope=*/0,
2064 MemberLookup,
2065 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002066 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002067 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002068
2069 // C++11 [class.copy]p15:
2070 // - if a member m has rvalue reference type T&&, it is direct-initialized
2071 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002072 if (RefersToRValueRef(CtorArg.get())) {
2073 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002074 }
2075
Douglas Gregor94f9a482010-05-05 05:51:00 +00002076 // When the field we are copying is an array, create index variables for
2077 // each dimension of the array. We use these index variables to subscript
2078 // the source array, and other clients (e.g., CodeGen) will perform the
2079 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002080 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002081 QualType BaseType = Field->getType();
2082 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002083 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002084 while (const ConstantArrayType *Array
2085 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002086 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002087 // Create the iteration variable for this array index.
2088 IdentifierInfo *IterationVarName = 0;
2089 {
2090 llvm::SmallString<8> Str;
2091 llvm::raw_svector_ostream OS(Str);
2092 OS << "__i" << IndexVariables.size();
2093 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2094 }
2095 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002096 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002097 IterationVarName, SizeType,
2098 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002099 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002100 IndexVariables.push_back(IterationVar);
2101
2102 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002103 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00002104 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002105 assert(!IterationVarRef.isInvalid() &&
2106 "Reference to invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00002107
Douglas Gregor94f9a482010-05-05 05:51:00 +00002108 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00002109 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00002110 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00002111 Loc);
2112 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00002113 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002114
Douglas Gregor94f9a482010-05-05 05:51:00 +00002115 BaseType = Array->getElementType();
2116 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00002117
2118 // The array subscript expression is an lvalue, which is wrong for moving.
2119 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00002120 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002121
Douglas Gregor94f9a482010-05-05 05:51:00 +00002122 // Construct the entity that we will be initializing. For an array, this
2123 // will be first element in the array, which may require several levels
2124 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002125 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002126 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00002127 if (Indirect)
2128 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2129 else
2130 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00002131 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2132 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2133 0,
2134 Entities.back()));
2135
2136 // Direct-initialize to use the copy constructor.
2137 InitializationKind InitKind =
2138 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2139
Sebastian Redle9c4e842011-09-04 18:14:28 +00002140 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregor94f9a482010-05-05 05:51:00 +00002141 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002142 &CtorArgE, 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002143
John McCalldadc5752010-08-24 06:29:42 +00002144 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002145 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002146 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002147 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002148 if (MemberInit.isInvalid())
2149 return true;
2150
Douglas Gregor493627b2011-08-10 15:22:55 +00002151 if (Indirect) {
2152 assert(IndexVariables.size() == 0 &&
2153 "Indirect field improperly initialized");
2154 CXXMemberInit
2155 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2156 Loc, Loc,
2157 MemberInit.takeAs<Expr>(),
2158 Loc);
2159 } else
2160 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2161 Loc, MemberInit.takeAs<Expr>(),
2162 Loc,
2163 IndexVariables.data(),
2164 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002165 return false;
2166 }
2167
Anders Carlsson423f5d82010-04-23 16:04:08 +00002168 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2169
Anders Carlsson3c1db572010-04-23 02:15:47 +00002170 QualType FieldBaseElementType =
2171 SemaRef.Context.getBaseElementType(Field->getType());
2172
Anders Carlsson3c1db572010-04-23 02:15:47 +00002173 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002174 InitializedEntity InitEntity
2175 = Indirect? InitializedEntity::InitializeMember(Indirect)
2176 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002177 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002178 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002179
2180 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002181 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002182 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002183
Douglas Gregora40433a2010-12-07 00:41:46 +00002184 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002185 if (MemberInit.isInvalid())
2186 return true;
2187
Douglas Gregor493627b2011-08-10 15:22:55 +00002188 if (Indirect)
2189 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2190 Indirect, Loc,
2191 Loc,
2192 MemberInit.get(),
2193 Loc);
2194 else
2195 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2196 Field, Loc, Loc,
2197 MemberInit.get(),
2198 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002199 return false;
2200 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002201
Alexis Hunt8b455182011-05-17 00:19:05 +00002202 if (!Field->getParent()->isUnion()) {
2203 if (FieldBaseElementType->isReferenceType()) {
2204 SemaRef.Diag(Constructor->getLocation(),
2205 diag::err_uninitialized_member_in_ctor)
2206 << (int)Constructor->isImplicit()
2207 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2208 << 0 << Field->getDeclName();
2209 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2210 return true;
2211 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002212
Alexis Hunt8b455182011-05-17 00:19:05 +00002213 if (FieldBaseElementType.isConstQualified()) {
2214 SemaRef.Diag(Constructor->getLocation(),
2215 diag::err_uninitialized_member_in_ctor)
2216 << (int)Constructor->isImplicit()
2217 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2218 << 1 << Field->getDeclName();
2219 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2220 return true;
2221 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002222 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002223
John McCall31168b02011-06-15 23:02:42 +00002224 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2225 FieldBaseElementType->isObjCRetainableType() &&
2226 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2227 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2228 // Instant objects:
2229 // Default-initialize Objective-C pointers to NULL.
2230 CXXMemberInit
2231 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2232 Loc, Loc,
2233 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2234 Loc);
2235 return false;
2236 }
2237
Anders Carlsson3c1db572010-04-23 02:15:47 +00002238 // Nothing to initialize.
2239 CXXMemberInit = 0;
2240 return false;
2241}
John McCallbc83b3f2010-05-20 23:23:51 +00002242
2243namespace {
2244struct BaseAndFieldInfo {
2245 Sema &S;
2246 CXXConstructorDecl *Ctor;
2247 bool AnyErrorsInInits;
2248 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002249 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002250 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002251
2252 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2253 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002254 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2255 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00002256 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002257 else if (Generated && Ctor->isMoveConstructor())
2258 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00002259 else
2260 IIK = IIK_Default;
2261 }
2262};
2263}
2264
Richard Smithc94ec842011-09-19 13:34:43 +00002265/// \brief Determine whether the given indirect field declaration is somewhere
2266/// within an anonymous union.
2267static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2268 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2269 CEnd = F->chain_end();
2270 C != CEnd; ++C)
2271 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2272 if (Record->isUnion())
2273 return true;
2274
2275 return false;
2276}
2277
Richard Smith938f40b2011-06-11 17:19:42 +00002278static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00002279 FieldDecl *Field,
2280 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00002281
Chandler Carruth139e9622010-06-30 02:59:29 +00002282 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002283 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002284 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002285 return false;
2286 }
2287
Richard Smith938f40b2011-06-11 17:19:42 +00002288 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2289 // has a brace-or-equal-initializer, the entity is initialized as specified
2290 // in [dcl.init].
2291 if (Field->hasInClassInitializer()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002292 CXXCtorInitializer *Init;
2293 if (Indirect)
2294 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2295 SourceLocation(),
2296 SourceLocation(), 0,
2297 SourceLocation());
2298 else
2299 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2300 SourceLocation(),
2301 SourceLocation(), 0,
2302 SourceLocation());
2303 Info.AllToInit.push_back(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002304 return false;
2305 }
2306
Richard Smith12d5ed82011-09-18 11:14:50 +00002307 // Don't build an implicit initializer for union members if none was
2308 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00002309 if (Field->getParent()->isUnion() ||
2310 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00002311 return false;
2312
John McCallbc83b3f2010-05-20 23:23:51 +00002313 // Don't try to build an implicit initializer if there were semantic
2314 // errors in any of the initializers (and therefore we might be
2315 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002316 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002317 return false;
2318
Alexis Hunt1d792652011-01-08 20:30:50 +00002319 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00002320 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2321 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00002322 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002323
Francois Pichetd583da02010-12-04 09:14:42 +00002324 if (Init)
2325 Info.AllToInit.push_back(Init);
2326
John McCallbc83b3f2010-05-20 23:23:51 +00002327 return false;
2328}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002329
2330bool
2331Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2332 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002333 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002334 Constructor->setNumCtorInitializers(1);
2335 CXXCtorInitializer **initializer =
2336 new (Context) CXXCtorInitializer*[1];
2337 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2338 Constructor->setCtorInitializers(initializer);
2339
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002340 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2341 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2342 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2343 }
2344
Alexis Hunte2622992011-05-05 00:05:47 +00002345 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002346
Alexis Hunt61bc1732011-05-01 07:04:31 +00002347 return false;
2348}
Douglas Gregor493627b2011-08-10 15:22:55 +00002349
John McCall1b1a1db2011-06-17 00:18:42 +00002350bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2351 CXXCtorInitializer **Initializers,
2352 unsigned NumInitializers,
2353 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002354 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002355 // Just store the initializers as written, they will be checked during
2356 // instantiation.
2357 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002358 Constructor->setNumCtorInitializers(NumInitializers);
2359 CXXCtorInitializer **baseOrMemberInitializers =
2360 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002361 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002362 NumInitializers * sizeof(CXXCtorInitializer*));
2363 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002364 }
2365
2366 return false;
2367 }
2368
John McCallbc83b3f2010-05-20 23:23:51 +00002369 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002370
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002371 // We need to build the initializer AST according to order of construction
2372 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002373 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002374 if (!ClassDecl)
2375 return true;
2376
Eli Friedman9cf6b592009-11-09 19:20:36 +00002377 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002378
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002379 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002380 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002381
2382 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002383 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002384 else
Francois Pichetd583da02010-12-04 09:14:42 +00002385 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002386 }
2387
Anders Carlsson43c64af2010-04-21 19:52:01 +00002388 // Keep track of the direct virtual bases.
2389 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2390 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2391 E = ClassDecl->bases_end(); I != E; ++I) {
2392 if (I->isVirtual())
2393 DirectVBases.insert(I);
2394 }
2395
Anders Carlssondb0a9652010-04-02 06:26:44 +00002396 // Push virtual bases before others.
2397 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2398 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2399
Alexis Hunt1d792652011-01-08 20:30:50 +00002400 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002401 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2402 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002403 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002404 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002405 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002406 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002407 VBase, IsInheritedVirtualBase,
2408 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002409 HadError = true;
2410 continue;
2411 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002412
John McCallbc83b3f2010-05-20 23:23:51 +00002413 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002414 }
2415 }
Mike Stump11289f42009-09-09 15:08:12 +00002416
John McCallbc83b3f2010-05-20 23:23:51 +00002417 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002418 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2419 E = ClassDecl->bases_end(); Base != E; ++Base) {
2420 // Virtuals are in the virtual base list and already constructed.
2421 if (Base->isVirtual())
2422 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002423
Alexis Hunt1d792652011-01-08 20:30:50 +00002424 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002425 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2426 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002427 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002428 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002429 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002430 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002431 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002432 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002433 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002434 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002435
John McCallbc83b3f2010-05-20 23:23:51 +00002436 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002437 }
2438 }
Mike Stump11289f42009-09-09 15:08:12 +00002439
John McCallbc83b3f2010-05-20 23:23:51 +00002440 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00002441 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2442 MemEnd = ClassDecl->decls_end();
2443 Mem != MemEnd; ++Mem) {
2444 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2445 if (F->getType()->isIncompleteArrayType()) {
2446 assert(ClassDecl->hasFlexibleArrayMember() &&
2447 "Incomplete array type is not valid");
2448 continue;
2449 }
2450
Sebastian Redl22653ba2011-08-30 19:58:05 +00002451 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00002452 // handle anonymous struct/union fields based on their individual
2453 // indirect fields.
2454 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2455 continue;
2456
2457 if (CollectFieldInitializer(*this, Info, F))
2458 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002459 continue;
2460 }
Douglas Gregor493627b2011-08-10 15:22:55 +00002461
2462 // Beyond this point, we only consider default initialization.
2463 if (Info.IIK != IIK_Default)
2464 continue;
2465
2466 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2467 if (F->getType()->isIncompleteArrayType()) {
2468 assert(ClassDecl->hasFlexibleArrayMember() &&
2469 "Incomplete array type is not valid");
2470 continue;
2471 }
2472
Douglas Gregor493627b2011-08-10 15:22:55 +00002473 // Initialize each field of an anonymous struct individually.
2474 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2475 HadError = true;
2476
2477 continue;
2478 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002479 }
Mike Stump11289f42009-09-09 15:08:12 +00002480
John McCallbc83b3f2010-05-20 23:23:51 +00002481 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002482 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002483 Constructor->setNumCtorInitializers(NumInitializers);
2484 CXXCtorInitializer **baseOrMemberInitializers =
2485 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002486 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002487 NumInitializers * sizeof(CXXCtorInitializer*));
2488 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002489
John McCalla6309952010-03-16 21:39:52 +00002490 // Constructors implicitly reference the base and member
2491 // destructors.
2492 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2493 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002494 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002495
2496 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002497}
2498
Eli Friedman952c15d2009-07-21 19:28:10 +00002499static void *GetKeyForTopLevelField(FieldDecl *Field) {
2500 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002501 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002502 if (RT->getDecl()->isAnonymousStructOrUnion())
2503 return static_cast<void *>(RT->getDecl());
2504 }
2505 return static_cast<void *>(Field);
2506}
2507
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002508static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002509 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002510}
2511
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002512static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002513 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002514 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002515 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002516
Eli Friedman952c15d2009-07-21 19:28:10 +00002517 // For fields injected into the class via declaration of an anonymous union,
2518 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002519 FieldDecl *Field = Member->getAnyMember();
2520
John McCall23eebd92010-04-10 09:28:51 +00002521 // If the field is a member of an anonymous struct or union, our key
2522 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002523 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002524 if (RD->isAnonymousStructOrUnion()) {
2525 while (true) {
2526 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2527 if (Parent->isAnonymousStructOrUnion())
2528 RD = Parent;
2529 else
2530 break;
2531 }
2532
Anders Carlsson83ac3122010-03-30 16:19:37 +00002533 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002534 }
Mike Stump11289f42009-09-09 15:08:12 +00002535
Anders Carlssona942dcd2010-03-30 15:39:27 +00002536 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002537}
2538
Anders Carlssone857b292010-04-02 03:37:03 +00002539static void
2540DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002541 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002542 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002543 unsigned NumInits) {
2544 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002545 return;
Mike Stump11289f42009-09-09 15:08:12 +00002546
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002547 // Don't check initializers order unless the warning is enabled at the
2548 // location of at least one initializer.
2549 bool ShouldCheckOrder = false;
2550 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002551 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002552 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2553 Init->getSourceLocation())
2554 != Diagnostic::Ignored) {
2555 ShouldCheckOrder = true;
2556 break;
2557 }
2558 }
2559 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002560 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002561
John McCallbb7b6582010-04-10 07:37:23 +00002562 // Build the list of bases and members in the order that they'll
2563 // actually be initialized. The explicit initializers should be in
2564 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002565 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002566
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002567 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2568
John McCallbb7b6582010-04-10 07:37:23 +00002569 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002570 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002571 ClassDecl->vbases_begin(),
2572 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002573 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002574
John McCallbb7b6582010-04-10 07:37:23 +00002575 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002576 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002577 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002578 if (Base->isVirtual())
2579 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002580 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
John McCallbb7b6582010-04-10 07:37:23 +00002583 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002584 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2585 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002586 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002587
John McCallbb7b6582010-04-10 07:37:23 +00002588 unsigned NumIdealInits = IdealInitKeys.size();
2589 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002590
Alexis Hunt1d792652011-01-08 20:30:50 +00002591 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002592 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002593 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002594 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002595
2596 // Scan forward to try to find this initializer in the idealized
2597 // initializers list.
2598 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2599 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002600 break;
John McCallbb7b6582010-04-10 07:37:23 +00002601
2602 // If we didn't find this initializer, it must be because we
2603 // scanned past it on a previous iteration. That can only
2604 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002605 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002606 Sema::SemaDiagnosticBuilder D =
2607 SemaRef.Diag(PrevInit->getSourceLocation(),
2608 diag::warn_initializer_out_of_order);
2609
Francois Pichetd583da02010-12-04 09:14:42 +00002610 if (PrevInit->isAnyMemberInitializer())
2611 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002612 else
2613 D << 1 << PrevInit->getBaseClassInfo()->getType();
2614
Francois Pichetd583da02010-12-04 09:14:42 +00002615 if (Init->isAnyMemberInitializer())
2616 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002617 else
2618 D << 1 << Init->getBaseClassInfo()->getType();
2619
2620 // Move back to the initializer's location in the ideal list.
2621 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2622 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002623 break;
John McCallbb7b6582010-04-10 07:37:23 +00002624
2625 assert(IdealIndex != NumIdealInits &&
2626 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002627 }
John McCallbb7b6582010-04-10 07:37:23 +00002628
2629 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002630 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002631}
2632
John McCall23eebd92010-04-10 09:28:51 +00002633namespace {
2634bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002635 CXXCtorInitializer *Init,
2636 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002637 if (!PrevInit) {
2638 PrevInit = Init;
2639 return false;
2640 }
2641
2642 if (FieldDecl *Field = Init->getMember())
2643 S.Diag(Init->getSourceLocation(),
2644 diag::err_multiple_mem_initialization)
2645 << Field->getDeclName()
2646 << Init->getSourceRange();
2647 else {
John McCall424cec92011-01-19 06:33:43 +00002648 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002649 assert(BaseClass && "neither field nor base");
2650 S.Diag(Init->getSourceLocation(),
2651 diag::err_multiple_base_initialization)
2652 << QualType(BaseClass, 0)
2653 << Init->getSourceRange();
2654 }
2655 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2656 << 0 << PrevInit->getSourceRange();
2657
2658 return true;
2659}
2660
Alexis Hunt1d792652011-01-08 20:30:50 +00002661typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002662typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2663
2664bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002665 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002666 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002667 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002668 RecordDecl *Parent = Field->getParent();
2669 if (!Parent->isAnonymousStructOrUnion())
2670 return false;
2671
2672 NamedDecl *Child = Field;
2673 do {
2674 if (Parent->isUnion()) {
2675 UnionEntry &En = Unions[Parent];
2676 if (En.first && En.first != Child) {
2677 S.Diag(Init->getSourceLocation(),
2678 diag::err_multiple_mem_union_initialization)
2679 << Field->getDeclName()
2680 << Init->getSourceRange();
2681 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2682 << 0 << En.second->getSourceRange();
2683 return true;
2684 } else if (!En.first) {
2685 En.first = Child;
2686 En.second = Init;
2687 }
2688 }
2689
2690 Child = Parent;
2691 Parent = cast<RecordDecl>(Parent->getDeclContext());
2692 } while (Parent->isAnonymousStructOrUnion());
2693
2694 return false;
2695}
2696}
2697
Anders Carlssone857b292010-04-02 03:37:03 +00002698/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002699void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002700 SourceLocation ColonLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00002701 CXXCtorInitializer **meminits,
2702 unsigned NumMemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00002703 bool AnyErrors) {
2704 if (!ConstructorDecl)
2705 return;
2706
2707 AdjustDeclIfTemplate(ConstructorDecl);
2708
2709 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002710 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002711
2712 if (!Constructor) {
2713 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2714 return;
2715 }
2716
Alexis Hunt1d792652011-01-08 20:30:50 +00002717 CXXCtorInitializer **MemInits =
2718 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002719
2720 // Mapping for the duplicate initializers check.
2721 // For member initializers, this is keyed with a FieldDecl*.
2722 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002723 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002724
2725 // Mapping for the inconsistent anonymous-union initializers check.
2726 RedundantUnionMap MemberUnions;
2727
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002728 bool HadError = false;
2729 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002730 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002731
Abramo Bagnara341d7832010-05-26 18:09:23 +00002732 // Set the source order index.
2733 Init->setSourceOrder(i);
2734
Francois Pichetd583da02010-12-04 09:14:42 +00002735 if (Init->isAnyMemberInitializer()) {
2736 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002737 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2738 CheckRedundantUnionInit(*this, Init, MemberUnions))
2739 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002740 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002741 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2742 if (CheckRedundantInit(*this, Init, Members[Key]))
2743 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002744 } else {
2745 assert(Init->isDelegatingInitializer());
2746 // This must be the only initializer
2747 if (i != 0 || NumMemInits > 1) {
2748 Diag(MemInits[0]->getSourceLocation(),
2749 diag::err_delegating_initializer_alone)
2750 << MemInits[0]->getSourceRange();
2751 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002752 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002753 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002754 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002755 // Return immediately as the initializer is set.
2756 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002757 }
Anders Carlssone857b292010-04-02 03:37:03 +00002758 }
2759
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002760 if (HadError)
2761 return;
2762
Anders Carlssone857b292010-04-02 03:37:03 +00002763 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002764
Alexis Hunt1d792652011-01-08 20:30:50 +00002765 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002766}
2767
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002768void
John McCalla6309952010-03-16 21:39:52 +00002769Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2770 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00002771 // Ignore dependent contexts. Also ignore unions, since their members never
2772 // have destructors implicitly called.
2773 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00002774 return;
John McCall1064d7e2010-03-16 05:22:47 +00002775
2776 // FIXME: all the access-control diagnostics are positioned on the
2777 // field/base declaration. That's probably good; that said, the
2778 // user might reasonably want to know why the destructor is being
2779 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002780
Anders Carlssondee9a302009-11-17 04:44:12 +00002781 // Non-static data members.
2782 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2783 E = ClassDecl->field_end(); I != E; ++I) {
2784 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002785 if (Field->isInvalidDecl())
2786 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002787 QualType FieldType = Context.getBaseElementType(Field->getType());
2788
2789 const RecordType* RT = FieldType->getAs<RecordType>();
2790 if (!RT)
2791 continue;
2792
2793 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002794 if (FieldClassDecl->isInvalidDecl())
2795 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002796 if (FieldClassDecl->hasTrivialDestructor())
2797 continue;
2798
Douglas Gregore71edda2010-07-01 22:47:18 +00002799 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002800 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002801 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002802 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002803 << Field->getDeclName()
2804 << FieldType);
2805
John McCalla6309952010-03-16 21:39:52 +00002806 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002807 }
2808
John McCall1064d7e2010-03-16 05:22:47 +00002809 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2810
Anders Carlssondee9a302009-11-17 04:44:12 +00002811 // Bases.
2812 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2813 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002814 // Bases are always records in a well-formed non-dependent class.
2815 const RecordType *RT = Base->getType()->getAs<RecordType>();
2816
2817 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002818 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002819 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002820
John McCall1064d7e2010-03-16 05:22:47 +00002821 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002822 // If our base class is invalid, we probably can't get its dtor anyway.
2823 if (BaseClassDecl->isInvalidDecl())
2824 continue;
2825 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002826 if (BaseClassDecl->hasTrivialDestructor())
2827 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002828
Douglas Gregore71edda2010-07-01 22:47:18 +00002829 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002830 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002831
2832 // FIXME: caret should be on the start of the class name
2833 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002834 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002835 << Base->getType()
2836 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002837
John McCalla6309952010-03-16 21:39:52 +00002838 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002839 }
2840
2841 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002842 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2843 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002844
2845 // Bases are always records in a well-formed non-dependent class.
2846 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2847
2848 // Ignore direct virtual bases.
2849 if (DirectVirtualBases.count(RT))
2850 continue;
2851
John McCall1064d7e2010-03-16 05:22:47 +00002852 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002853 // If our base class is invalid, we probably can't get its dtor anyway.
2854 if (BaseClassDecl->isInvalidDecl())
2855 continue;
2856 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002857 if (BaseClassDecl->hasTrivialDestructor())
2858 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002859
Douglas Gregore71edda2010-07-01 22:47:18 +00002860 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002861 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002862 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002863 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002864 << VBase->getType());
2865
John McCalla6309952010-03-16 21:39:52 +00002866 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002867 }
2868}
2869
John McCall48871652010-08-21 09:40:31 +00002870void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002871 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002872 return;
Mike Stump11289f42009-09-09 15:08:12 +00002873
Mike Stump11289f42009-09-09 15:08:12 +00002874 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002875 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002876 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002877}
2878
Mike Stump11289f42009-09-09 15:08:12 +00002879bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002880 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002881 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002882 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002883 else
John McCall02db245d2010-08-18 09:41:07 +00002884 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002885}
2886
Anders Carlssoneabf7702009-08-27 00:13:57 +00002887bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002888 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002889 if (!getLangOptions().CPlusPlus)
2890 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002891
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002892 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002893 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002894
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002895 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002896 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002897 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002898 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002899
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002900 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002901 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002902 }
Mike Stump11289f42009-09-09 15:08:12 +00002903
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002904 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002905 if (!RT)
2906 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002907
John McCall67da35c2010-02-04 22:26:26 +00002908 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002909
John McCall02db245d2010-08-18 09:41:07 +00002910 // We can't answer whether something is abstract until it has a
2911 // definition. If it's currently being defined, we'll walk back
2912 // over all the declarations when we have a full definition.
2913 const CXXRecordDecl *Def = RD->getDefinition();
2914 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002915 return false;
2916
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002917 if (!RD->isAbstract())
2918 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002919
Anders Carlssoneabf7702009-08-27 00:13:57 +00002920 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002921 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002922
John McCall02db245d2010-08-18 09:41:07 +00002923 return true;
2924}
2925
2926void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2927 // Check if we've already emitted the list of pure virtual functions
2928 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002929 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002930 return;
Mike Stump11289f42009-09-09 15:08:12 +00002931
Douglas Gregor4165bd62010-03-23 23:47:56 +00002932 CXXFinalOverriderMap FinalOverriders;
2933 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002934
Anders Carlssona2f74f32010-06-03 01:00:02 +00002935 // Keep a set of seen pure methods so we won't diagnose the same method
2936 // more than once.
2937 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2938
Douglas Gregor4165bd62010-03-23 23:47:56 +00002939 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2940 MEnd = FinalOverriders.end();
2941 M != MEnd;
2942 ++M) {
2943 for (OverridingMethods::iterator SO = M->second.begin(),
2944 SOEnd = M->second.end();
2945 SO != SOEnd; ++SO) {
2946 // C++ [class.abstract]p4:
2947 // A class is abstract if it contains or inherits at least one
2948 // pure virtual function for which the final overrider is pure
2949 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002950
Douglas Gregor4165bd62010-03-23 23:47:56 +00002951 //
2952 if (SO->second.size() != 1)
2953 continue;
2954
2955 if (!SO->second.front().Method->isPure())
2956 continue;
2957
Anders Carlssona2f74f32010-06-03 01:00:02 +00002958 if (!SeenPureMethods.insert(SO->second.front().Method))
2959 continue;
2960
Douglas Gregor4165bd62010-03-23 23:47:56 +00002961 Diag(SO->second.front().Method->getLocation(),
2962 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002963 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002964 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002965 }
2966
2967 if (!PureVirtualClassDiagSet)
2968 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2969 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002970}
2971
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002972namespace {
John McCall02db245d2010-08-18 09:41:07 +00002973struct AbstractUsageInfo {
2974 Sema &S;
2975 CXXRecordDecl *Record;
2976 CanQualType AbstractType;
2977 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002978
John McCall02db245d2010-08-18 09:41:07 +00002979 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2980 : S(S), Record(Record),
2981 AbstractType(S.Context.getCanonicalType(
2982 S.Context.getTypeDeclType(Record))),
2983 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002984
John McCall02db245d2010-08-18 09:41:07 +00002985 void DiagnoseAbstractType() {
2986 if (Invalid) return;
2987 S.DiagnoseAbstractType(Record);
2988 Invalid = true;
2989 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002990
John McCall02db245d2010-08-18 09:41:07 +00002991 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2992};
2993
2994struct CheckAbstractUsage {
2995 AbstractUsageInfo &Info;
2996 const NamedDecl *Ctx;
2997
2998 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2999 : Info(Info), Ctx(Ctx) {}
3000
3001 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3002 switch (TL.getTypeLocClass()) {
3003#define ABSTRACT_TYPELOC(CLASS, PARENT)
3004#define TYPELOC(CLASS, PARENT) \
3005 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3006#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003007 }
John McCall02db245d2010-08-18 09:41:07 +00003008 }
Mike Stump11289f42009-09-09 15:08:12 +00003009
John McCall02db245d2010-08-18 09:41:07 +00003010 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3011 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3012 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003013 if (!TL.getArg(I))
3014 continue;
3015
John McCall02db245d2010-08-18 09:41:07 +00003016 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3017 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003018 }
John McCall02db245d2010-08-18 09:41:07 +00003019 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003020
John McCall02db245d2010-08-18 09:41:07 +00003021 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3022 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3023 }
Mike Stump11289f42009-09-09 15:08:12 +00003024
John McCall02db245d2010-08-18 09:41:07 +00003025 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3026 // Visit the type parameters from a permissive context.
3027 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3028 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3029 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3030 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3031 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3032 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003033 }
John McCall02db245d2010-08-18 09:41:07 +00003034 }
Mike Stump11289f42009-09-09 15:08:12 +00003035
John McCall02db245d2010-08-18 09:41:07 +00003036 // Visit pointee types from a permissive context.
3037#define CheckPolymorphic(Type) \
3038 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3039 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3040 }
3041 CheckPolymorphic(PointerTypeLoc)
3042 CheckPolymorphic(ReferenceTypeLoc)
3043 CheckPolymorphic(MemberPointerTypeLoc)
3044 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00003045
John McCall02db245d2010-08-18 09:41:07 +00003046 /// Handle all the types we haven't given a more specific
3047 /// implementation for above.
3048 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3049 // Every other kind of type that we haven't called out already
3050 // that has an inner type is either (1) sugar or (2) contains that
3051 // inner type in some way as a subobject.
3052 if (TypeLoc Next = TL.getNextTypeLoc())
3053 return Visit(Next, Sel);
3054
3055 // If there's no inner type and we're in a permissive context,
3056 // don't diagnose.
3057 if (Sel == Sema::AbstractNone) return;
3058
3059 // Check whether the type matches the abstract type.
3060 QualType T = TL.getType();
3061 if (T->isArrayType()) {
3062 Sel = Sema::AbstractArrayType;
3063 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003064 }
John McCall02db245d2010-08-18 09:41:07 +00003065 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3066 if (CT != Info.AbstractType) return;
3067
3068 // It matched; do some magic.
3069 if (Sel == Sema::AbstractArrayType) {
3070 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3071 << T << TL.getSourceRange();
3072 } else {
3073 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3074 << Sel << T << TL.getSourceRange();
3075 }
3076 Info.DiagnoseAbstractType();
3077 }
3078};
3079
3080void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3081 Sema::AbstractDiagSelID Sel) {
3082 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3083}
3084
3085}
3086
3087/// Check for invalid uses of an abstract type in a method declaration.
3088static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3089 CXXMethodDecl *MD) {
3090 // No need to do the check on definitions, which require that
3091 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003092 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00003093 return;
3094
3095 // For safety's sake, just ignore it if we don't have type source
3096 // information. This should never happen for non-implicit methods,
3097 // but...
3098 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3099 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3100}
3101
3102/// Check for invalid uses of an abstract type within a class definition.
3103static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3104 CXXRecordDecl *RD) {
3105 for (CXXRecordDecl::decl_iterator
3106 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3107 Decl *D = *I;
3108 if (D->isImplicit()) continue;
3109
3110 // Methods and method templates.
3111 if (isa<CXXMethodDecl>(D)) {
3112 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3113 } else if (isa<FunctionTemplateDecl>(D)) {
3114 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3115 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3116
3117 // Fields and static variables.
3118 } else if (isa<FieldDecl>(D)) {
3119 FieldDecl *FD = cast<FieldDecl>(D);
3120 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3121 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3122 } else if (isa<VarDecl>(D)) {
3123 VarDecl *VD = cast<VarDecl>(D);
3124 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3125 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3126
3127 // Nested classes and class templates.
3128 } else if (isa<CXXRecordDecl>(D)) {
3129 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3130 } else if (isa<ClassTemplateDecl>(D)) {
3131 CheckAbstractClassUsage(Info,
3132 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3133 }
3134 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003135}
3136
Douglas Gregorc99f1552009-12-03 18:33:45 +00003137/// \brief Perform semantic checks on a class definition that has been
3138/// completing, introducing implicitly-declared members, checking for
3139/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003140void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003141 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003142 return;
3143
John McCall02db245d2010-08-18 09:41:07 +00003144 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3145 AbstractUsageInfo Info(*this, Record);
3146 CheckAbstractClassUsage(Info, Record);
3147 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003148
3149 // If this is not an aggregate type and has no user-declared constructor,
3150 // complain about any non-static data members of reference or const scalar
3151 // type, since they will never get initializers.
3152 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3153 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3154 bool Complained = false;
3155 for (RecordDecl::field_iterator F = Record->field_begin(),
3156 FEnd = Record->field_end();
3157 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00003158 if (F->hasInClassInitializer())
3159 continue;
3160
Douglas Gregor454a5b62010-04-15 00:00:53 +00003161 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003162 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003163 if (!Complained) {
3164 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3165 << Record->getTagKind() << Record;
3166 Complained = true;
3167 }
3168
3169 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3170 << F->getType()->isReferenceType()
3171 << F->getDeclName();
3172 }
3173 }
3174 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003175
Anders Carlssone771e762011-01-25 18:08:22 +00003176 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003177 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003178
3179 if (Record->getIdentifier()) {
3180 // C++ [class.mem]p13:
3181 // If T is the name of a class, then each of the following shall have a
3182 // name different from T:
3183 // - every member of every anonymous union that is a member of class T.
3184 //
3185 // C++ [class.mem]p14:
3186 // In addition, if class T has a user-declared constructor (12.1), every
3187 // non-static data member of class T shall have a name different from T.
3188 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003189 R.first != R.second; ++R.first) {
3190 NamedDecl *D = *R.first;
3191 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3192 isa<IndirectFieldDecl>(D)) {
3193 Diag(D->getLocation(), diag::err_member_name_of_class)
3194 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003195 break;
3196 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003197 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003198 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003199
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003200 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003201 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003202 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003203 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003204 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3205 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3206 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003207
3208 // See if a method overloads virtual methods in a base
3209 /// class without overriding any.
3210 if (!Record->isDependentType()) {
3211 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3212 MEnd = Record->method_end();
3213 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003214 if (!(*M)->isStatic())
3215 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003216 }
3217 }
Sebastian Redl08905022011-02-05 19:23:19 +00003218
3219 // Declare inherited constructors. We do this eagerly here because:
3220 // - The standard requires an eager diagnostic for conflicting inherited
3221 // constructors from different classes.
3222 // - The lazy declaration of the other implicit constructors is so as to not
3223 // waste space and performance on classes that are not meant to be
3224 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3225 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003226 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003227
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003228 if (!Record->isDependentType())
3229 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003230}
3231
3232void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003233 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3234 ME = Record->method_end();
3235 MI != ME; ++MI) {
3236 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3237 switch (getSpecialMember(*MI)) {
3238 case CXXDefaultConstructor:
3239 CheckExplicitlyDefaultedDefaultConstructor(
3240 cast<CXXConstructorDecl>(*MI));
3241 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003242
Alexis Huntf91729462011-05-12 22:46:25 +00003243 case CXXDestructor:
3244 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3245 break;
3246
3247 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003248 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3249 break;
3250
Alexis Huntf91729462011-05-12 22:46:25 +00003251 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003252 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003253 break;
3254
Alexis Hunt119c10e2011-05-25 23:16:36 +00003255 case CXXMoveConstructor:
Sebastian Redl22653ba2011-08-30 19:58:05 +00003256 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Alexis Hunt119c10e2011-05-25 23:16:36 +00003257 break;
3258
Sebastian Redl22653ba2011-08-30 19:58:05 +00003259 case CXXMoveAssignment:
3260 CheckExplicitlyDefaultedMoveAssignment(*MI);
3261 break;
3262
3263 case CXXInvalid:
Alexis Huntf91729462011-05-12 22:46:25 +00003264 llvm_unreachable("non-special member explicitly defaulted!");
3265 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003266 }
3267 }
3268
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003269}
3270
3271void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3272 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3273
3274 // Whether this was the first-declared instance of the constructor.
3275 // This affects whether we implicitly add an exception spec (and, eventually,
3276 // constexpr). It is also ill-formed to explicitly default a constructor such
3277 // that it would be deleted. (C++0x [decl.fct.def.default])
3278 bool First = CD == CD->getCanonicalDecl();
3279
Alexis Hunt913820d2011-05-13 06:10:58 +00003280 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003281 if (CD->getNumParams() != 0) {
3282 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3283 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003284 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003285 }
3286
3287 ImplicitExceptionSpecification Spec
3288 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3289 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003290 if (EPI.ExceptionSpecType == EST_Delayed) {
3291 // Exception specification depends on some deferred part of the class. We'll
3292 // try again when the class's definition has been fully processed.
3293 return;
3294 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003295 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3296 *ExceptionType = Context.getFunctionType(
3297 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3298
3299 if (CtorType->hasExceptionSpec()) {
3300 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003301 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003302 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003303 PDiag(),
3304 ExceptionType, SourceLocation(),
3305 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003306 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003307 }
3308 } else if (First) {
3309 // We set the declaration to have the computed exception spec here.
3310 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003311 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003312 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3313 }
Alexis Huntb3153022011-05-12 03:51:48 +00003314
Alexis Hunt913820d2011-05-13 06:10:58 +00003315 if (HadError) {
3316 CD->setInvalidDecl();
3317 return;
3318 }
3319
Alexis Huntb3153022011-05-12 03:51:48 +00003320 if (ShouldDeleteDefaultConstructor(CD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003321 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003322 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003323 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003324 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003325 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003326 CD->setInvalidDecl();
3327 }
3328 }
3329}
3330
3331void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3332 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3333
3334 // Whether this was the first-declared instance of the constructor.
3335 bool First = CD == CD->getCanonicalDecl();
3336
3337 bool HadError = false;
3338 if (CD->getNumParams() != 1) {
3339 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3340 << CD->getSourceRange();
3341 HadError = true;
3342 }
3343
3344 ImplicitExceptionSpecification Spec(Context);
3345 bool Const;
3346 llvm::tie(Spec, Const) =
3347 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3348
3349 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3350 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3351 *ExceptionType = Context.getFunctionType(
3352 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3353
3354 // Check for parameter type matching.
3355 // This is a copy ctor so we know it's a cv-qualified reference to T.
3356 QualType ArgType = CtorType->getArgType(0);
3357 if (ArgType->getPointeeType().isVolatileQualified()) {
3358 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3359 HadError = true;
3360 }
3361 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3362 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3363 HadError = true;
3364 }
3365
3366 if (CtorType->hasExceptionSpec()) {
3367 if (CheckEquivalentExceptionSpec(
3368 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003369 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003370 PDiag(),
3371 ExceptionType, SourceLocation(),
3372 CtorType, CD->getLocation())) {
3373 HadError = true;
3374 }
3375 } else if (First) {
3376 // We set the declaration to have the computed exception spec here.
3377 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003378 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003379 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3380 }
3381
3382 if (HadError) {
3383 CD->setInvalidDecl();
3384 return;
3385 }
3386
3387 if (ShouldDeleteCopyConstructor(CD)) {
3388 if (First) {
3389 CD->setDeletedAsWritten();
3390 } else {
3391 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003392 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003393 CD->setInvalidDecl();
3394 }
Alexis Huntb3153022011-05-12 03:51:48 +00003395 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003396}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003397
Alexis Huntc9a55732011-05-14 05:23:28 +00003398void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3399 assert(MD->isExplicitlyDefaulted());
3400
3401 // Whether this was the first-declared instance of the operator
3402 bool First = MD == MD->getCanonicalDecl();
3403
3404 bool HadError = false;
3405 if (MD->getNumParams() != 1) {
3406 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3407 << MD->getSourceRange();
3408 HadError = true;
3409 }
3410
3411 QualType ReturnType =
3412 MD->getType()->getAs<FunctionType>()->getResultType();
3413 if (!ReturnType->isLValueReferenceType() ||
3414 !Context.hasSameType(
3415 Context.getCanonicalType(ReturnType->getPointeeType()),
3416 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3417 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3418 HadError = true;
3419 }
3420
3421 ImplicitExceptionSpecification Spec(Context);
3422 bool Const;
3423 llvm::tie(Spec, Const) =
3424 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3425
3426 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3427 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3428 *ExceptionType = Context.getFunctionType(
3429 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3430
Alexis Huntc9a55732011-05-14 05:23:28 +00003431 QualType ArgType = OperType->getArgType(0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003432 if (!ArgType->isLValueReferenceType()) {
Alexis Hunt604aeb32011-05-17 20:44:43 +00003433 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003434 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003435 } else {
3436 if (ArgType->getPointeeType().isVolatileQualified()) {
3437 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3438 HadError = true;
3439 }
3440 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3441 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3442 HadError = true;
3443 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003444 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003445
Alexis Huntc9a55732011-05-14 05:23:28 +00003446 if (OperType->getTypeQuals()) {
3447 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3448 HadError = true;
3449 }
3450
3451 if (OperType->hasExceptionSpec()) {
3452 if (CheckEquivalentExceptionSpec(
3453 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003454 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003455 PDiag(),
3456 ExceptionType, SourceLocation(),
3457 OperType, MD->getLocation())) {
3458 HadError = true;
3459 }
3460 } else if (First) {
3461 // We set the declaration to have the computed exception spec here.
3462 // We duplicate the one parameter type.
3463 EPI.RefQualifier = OperType->getRefQualifier();
3464 EPI.ExtInfo = OperType->getExtInfo();
3465 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3466 }
3467
3468 if (HadError) {
3469 MD->setInvalidDecl();
3470 return;
3471 }
3472
3473 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3474 if (First) {
3475 MD->setDeletedAsWritten();
3476 } else {
3477 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003478 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003479 MD->setInvalidDecl();
3480 }
3481 }
3482}
3483
Sebastian Redl22653ba2011-08-30 19:58:05 +00003484void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3485 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3486
3487 // Whether this was the first-declared instance of the constructor.
3488 bool First = CD == CD->getCanonicalDecl();
3489
3490 bool HadError = false;
3491 if (CD->getNumParams() != 1) {
3492 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3493 << CD->getSourceRange();
3494 HadError = true;
3495 }
3496
3497 ImplicitExceptionSpecification Spec(
3498 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3499
3500 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3501 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3502 *ExceptionType = Context.getFunctionType(
3503 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3504
3505 // Check for parameter type matching.
3506 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3507 QualType ArgType = CtorType->getArgType(0);
3508 if (ArgType->getPointeeType().isVolatileQualified()) {
3509 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3510 HadError = true;
3511 }
3512 if (ArgType->getPointeeType().isConstQualified()) {
3513 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3514 HadError = true;
3515 }
3516
3517 if (CtorType->hasExceptionSpec()) {
3518 if (CheckEquivalentExceptionSpec(
3519 PDiag(diag::err_incorrect_defaulted_exception_spec)
3520 << CXXMoveConstructor,
3521 PDiag(),
3522 ExceptionType, SourceLocation(),
3523 CtorType, CD->getLocation())) {
3524 HadError = true;
3525 }
3526 } else if (First) {
3527 // We set the declaration to have the computed exception spec here.
3528 // We duplicate the one parameter type.
3529 EPI.ExtInfo = CtorType->getExtInfo();
3530 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3531 }
3532
3533 if (HadError) {
3534 CD->setInvalidDecl();
3535 return;
3536 }
3537
3538 if (ShouldDeleteMoveConstructor(CD)) {
3539 if (First) {
3540 CD->setDeletedAsWritten();
3541 } else {
3542 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3543 << CXXMoveConstructor;
3544 CD->setInvalidDecl();
3545 }
3546 }
3547}
3548
3549void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3550 assert(MD->isExplicitlyDefaulted());
3551
3552 // Whether this was the first-declared instance of the operator
3553 bool First = MD == MD->getCanonicalDecl();
3554
3555 bool HadError = false;
3556 if (MD->getNumParams() != 1) {
3557 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3558 << MD->getSourceRange();
3559 HadError = true;
3560 }
3561
3562 QualType ReturnType =
3563 MD->getType()->getAs<FunctionType>()->getResultType();
3564 if (!ReturnType->isLValueReferenceType() ||
3565 !Context.hasSameType(
3566 Context.getCanonicalType(ReturnType->getPointeeType()),
3567 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3568 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3569 HadError = true;
3570 }
3571
3572 ImplicitExceptionSpecification Spec(
3573 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3574
3575 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3576 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3577 *ExceptionType = Context.getFunctionType(
3578 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3579
3580 QualType ArgType = OperType->getArgType(0);
3581 if (!ArgType->isRValueReferenceType()) {
3582 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3583 HadError = true;
3584 } else {
3585 if (ArgType->getPointeeType().isVolatileQualified()) {
3586 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3587 HadError = true;
3588 }
3589 if (ArgType->getPointeeType().isConstQualified()) {
3590 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3591 HadError = true;
3592 }
3593 }
3594
3595 if (OperType->getTypeQuals()) {
3596 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3597 HadError = true;
3598 }
3599
3600 if (OperType->hasExceptionSpec()) {
3601 if (CheckEquivalentExceptionSpec(
3602 PDiag(diag::err_incorrect_defaulted_exception_spec)
3603 << CXXMoveAssignment,
3604 PDiag(),
3605 ExceptionType, SourceLocation(),
3606 OperType, MD->getLocation())) {
3607 HadError = true;
3608 }
3609 } else if (First) {
3610 // We set the declaration to have the computed exception spec here.
3611 // We duplicate the one parameter type.
3612 EPI.RefQualifier = OperType->getRefQualifier();
3613 EPI.ExtInfo = OperType->getExtInfo();
3614 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3615 }
3616
3617 if (HadError) {
3618 MD->setInvalidDecl();
3619 return;
3620 }
3621
3622 if (ShouldDeleteMoveAssignmentOperator(MD)) {
3623 if (First) {
3624 MD->setDeletedAsWritten();
3625 } else {
3626 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3627 << CXXMoveAssignment;
3628 MD->setInvalidDecl();
3629 }
3630 }
3631}
3632
Alexis Huntf91729462011-05-12 22:46:25 +00003633void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3634 assert(DD->isExplicitlyDefaulted());
3635
3636 // Whether this was the first-declared instance of the destructor.
3637 bool First = DD == DD->getCanonicalDecl();
3638
3639 ImplicitExceptionSpecification Spec
3640 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3641 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3642 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3643 *ExceptionType = Context.getFunctionType(
3644 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3645
3646 if (DtorType->hasExceptionSpec()) {
3647 if (CheckEquivalentExceptionSpec(
3648 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003649 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00003650 PDiag(),
3651 ExceptionType, SourceLocation(),
3652 DtorType, DD->getLocation())) {
3653 DD->setInvalidDecl();
3654 return;
3655 }
3656 } else if (First) {
3657 // We set the declaration to have the computed exception spec here.
3658 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003659 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00003660 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3661 }
3662
3663 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003664 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00003665 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003666 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00003667 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003668 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003669 DD->setInvalidDecl();
3670 }
Alexis Huntf91729462011-05-12 22:46:25 +00003671 }
Alexis Huntf91729462011-05-12 22:46:25 +00003672}
3673
Alexis Huntea6f0322011-05-11 22:34:38 +00003674bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3675 CXXRecordDecl *RD = CD->getParent();
3676 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00003677 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00003678 return false;
3679
Alexis Hunte77a28f2011-05-18 03:41:58 +00003680 SourceLocation Loc = CD->getLocation();
3681
Alexis Huntea6f0322011-05-11 22:34:38 +00003682 // Do access control from the constructor
3683 ContextRAII CtorContext(*this, CD);
3684
3685 bool Union = RD->isUnion();
3686 bool AllConst = true;
3687
Alexis Huntea6f0322011-05-11 22:34:38 +00003688 // We do this because we should never actually use an anonymous
3689 // union's constructor.
3690 if (Union && RD->isAnonymousStructOrUnion())
3691 return false;
3692
3693 // FIXME: We should put some diagnostic logic right into this function.
3694
3695 // C++0x [class.ctor]/5
Alexis Hunteef8ee02011-06-10 03:50:41 +00003696 // A defaulted default constructor for class X is defined as deleted if:
Alexis Huntea6f0322011-05-11 22:34:38 +00003697
3698 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3699 BE = RD->bases_end();
3700 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00003701 // We'll handle this one later
3702 if (BI->isVirtual())
3703 continue;
3704
Alexis Huntea6f0322011-05-11 22:34:38 +00003705 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3706 assert(BaseDecl && "base isn't a CXXRecordDecl");
3707
3708 // -- any [direct base class] has a type with a destructor that is
Alexis Hunteef8ee02011-06-10 03:50:41 +00003709 // deleted or inaccessible from the defaulted default constructor
Alexis Huntea6f0322011-05-11 22:34:38 +00003710 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3711 if (BaseDtor->isDeleted())
3712 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003713 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003714 AR_accessible)
3715 return true;
3716
Alexis Huntea6f0322011-05-11 22:34:38 +00003717 // -- any [direct base class either] has no default constructor or
3718 // overload resolution as applied to [its] default constructor
3719 // results in an ambiguity or in a function that is deleted or
3720 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003721 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3722 if (!BaseDefault || BaseDefault->isDeleted())
3723 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003724
Alexis Hunteef8ee02011-06-10 03:50:41 +00003725 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3726 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003727 return true;
3728 }
3729
3730 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3731 BE = RD->vbases_end();
3732 BI != BE; ++BI) {
3733 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3734 assert(BaseDecl && "base isn't a CXXRecordDecl");
3735
3736 // -- any [virtual base class] has a type with a destructor that is
3737 // delete or inaccessible from the defaulted default constructor
3738 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3739 if (BaseDtor->isDeleted())
3740 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003741 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003742 AR_accessible)
3743 return true;
3744
3745 // -- any [virtual base class either] has no default constructor or
3746 // overload resolution as applied to [its] default constructor
3747 // results in an ambiguity or in a function that is deleted or
3748 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003749 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3750 if (!BaseDefault || BaseDefault->isDeleted())
3751 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003752
Alexis Hunteef8ee02011-06-10 03:50:41 +00003753 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3754 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003755 return true;
3756 }
3757
3758 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3759 FE = RD->field_end();
3760 FI != FE; ++FI) {
Richard Smith938f40b2011-06-11 17:19:42 +00003761 if (FI->isInvalidDecl())
3762 continue;
3763
Alexis Huntea6f0322011-05-11 22:34:38 +00003764 QualType FieldType = Context.getBaseElementType(FI->getType());
3765 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00003766
Alexis Huntea6f0322011-05-11 22:34:38 +00003767 // -- any non-static data member with no brace-or-equal-initializer is of
3768 // reference type
Richard Smith938f40b2011-06-11 17:19:42 +00003769 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Alexis Huntea6f0322011-05-11 22:34:38 +00003770 return true;
3771
3772 // -- X is a union and all its variant members are of const-qualified type
3773 // (or array thereof)
3774 if (Union && !FieldType.isConstQualified())
3775 AllConst = false;
3776
3777 if (FieldRecord) {
3778 // -- X is a union-like class that has a variant member with a non-trivial
3779 // default constructor
3780 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3781 return true;
3782
3783 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3784 if (FieldDtor->isDeleted())
3785 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003786 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003787 AR_accessible)
3788 return true;
3789
3790 // -- any non-variant non-static data member of const-qualified type (or
3791 // array thereof) with no brace-or-equal-initializer does not have a
3792 // user-provided default constructor
3793 if (FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003794 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00003795 !FieldRecord->hasUserProvidedDefaultConstructor())
3796 return true;
3797
3798 if (!Union && FieldRecord->isUnion() &&
3799 FieldRecord->isAnonymousStructOrUnion()) {
3800 // We're okay to reuse AllConst here since we only care about the
3801 // value otherwise if we're in a union.
3802 AllConst = true;
3803
3804 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3805 UE = FieldRecord->field_end();
3806 UI != UE; ++UI) {
3807 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3808 CXXRecordDecl *UnionFieldRecord =
3809 UnionFieldType->getAsCXXRecordDecl();
3810
3811 if (!UnionFieldType.isConstQualified())
3812 AllConst = false;
3813
3814 if (UnionFieldRecord &&
3815 !UnionFieldRecord->hasTrivialDefaultConstructor())
3816 return true;
3817 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00003818
Alexis Huntea6f0322011-05-11 22:34:38 +00003819 if (AllConst)
3820 return true;
3821
3822 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00003823 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00003824 continue;
3825 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00003826
Richard Smith938f40b2011-06-11 17:19:42 +00003827 // -- any non-static data member with no brace-or-equal-initializer has
3828 // class type M (or array thereof) and either M has no default
3829 // constructor or overload resolution as applied to M's default
3830 // constructor results in an ambiguity or in a function that is deleted
3831 // or inaccessible from the defaulted default constructor.
3832 if (!FI->hasInClassInitializer()) {
3833 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3834 if (!FieldDefault || FieldDefault->isDeleted())
3835 return true;
3836 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3837 PDiag()) != AR_accessible)
3838 return true;
3839 }
3840 } else if (!Union && FieldType.isConstQualified() &&
3841 !FI->hasInClassInitializer()) {
Alexis Hunta671bca2011-05-20 21:43:47 +00003842 // -- any non-variant non-static data member of const-qualified type (or
3843 // array thereof) with no brace-or-equal-initializer does not have a
3844 // user-provided default constructor
3845 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003846 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003847 }
3848
3849 if (Union && AllConst)
3850 return true;
3851
3852 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003853}
3854
Alexis Hunt913820d2011-05-13 06:10:58 +00003855bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00003856 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00003857 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00003858 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Hunt913820d2011-05-13 06:10:58 +00003859 return false;
3860
Alexis Hunte77a28f2011-05-18 03:41:58 +00003861 SourceLocation Loc = CD->getLocation();
3862
Alexis Hunt913820d2011-05-13 06:10:58 +00003863 // Do access control from the constructor
3864 ContextRAII CtorContext(*this, CD);
3865
Alexis Hunt899bd442011-06-10 04:44:37 +00003866 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00003867
Alexis Huntc9a55732011-05-14 05:23:28 +00003868 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3869 "copy assignment arg has no pointee type");
Alexis Hunt899bd442011-06-10 04:44:37 +00003870 unsigned ArgQuals =
3871 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3872 Qualifiers::Const : 0;
Alexis Hunt913820d2011-05-13 06:10:58 +00003873
3874 // We do this because we should never actually use an anonymous
3875 // union's constructor.
3876 if (Union && RD->isAnonymousStructOrUnion())
3877 return false;
3878
3879 // FIXME: We should put some diagnostic logic right into this function.
3880
3881 // C++0x [class.copy]/11
3882 // A defaulted [copy] constructor for class X is defined as delete if X has:
3883
3884 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3885 BE = RD->bases_end();
3886 BI != BE; ++BI) {
3887 // We'll handle this one later
3888 if (BI->isVirtual())
3889 continue;
3890
3891 QualType BaseType = BI->getType();
3892 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3893 assert(BaseDecl && "base isn't a CXXRecordDecl");
3894
3895 // -- any [direct base class] of a type with a destructor that is deleted or
3896 // inaccessible from the defaulted constructor
3897 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3898 if (BaseDtor->isDeleted())
3899 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003900 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003901 AR_accessible)
3902 return true;
3903
3904 // -- a [direct base class] B that cannot be [copied] because overload
3905 // resolution, as applied to B's [copy] constructor, results in an
3906 // ambiguity or a function that is deleted or inaccessible from the
3907 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003908 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003909 if (!BaseCtor || BaseCtor->isDeleted())
3910 return true;
3911 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3912 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003913 return true;
3914 }
3915
3916 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3917 BE = RD->vbases_end();
3918 BI != BE; ++BI) {
3919 QualType BaseType = BI->getType();
3920 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3921 assert(BaseDecl && "base isn't a CXXRecordDecl");
3922
Alexis Hunteef8ee02011-06-10 03:50:41 +00003923 // -- any [virtual base class] of a type with a destructor that is deleted or
Alexis Hunt913820d2011-05-13 06:10:58 +00003924 // inaccessible from the defaulted constructor
3925 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3926 if (BaseDtor->isDeleted())
3927 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003928 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003929 AR_accessible)
3930 return true;
3931
3932 // -- a [virtual base class] B that cannot be [copied] because overload
3933 // resolution, as applied to B's [copy] constructor, results in an
3934 // ambiguity or a function that is deleted or inaccessible from the
3935 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003936 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003937 if (!BaseCtor || BaseCtor->isDeleted())
3938 return true;
3939 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3940 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003941 return true;
3942 }
3943
3944 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3945 FE = RD->field_end();
3946 FI != FE; ++FI) {
3947 QualType FieldType = Context.getBaseElementType(FI->getType());
3948
3949 // -- for a copy constructor, a non-static data member of rvalue reference
3950 // type
3951 if (FieldType->isRValueReferenceType())
3952 return true;
3953
3954 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3955
3956 if (FieldRecord) {
3957 // This is an anonymous union
3958 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3959 // Anonymous unions inside unions do not variant members create
3960 if (!Union) {
3961 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3962 UE = FieldRecord->field_end();
3963 UI != UE; ++UI) {
3964 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3965 CXXRecordDecl *UnionFieldRecord =
3966 UnionFieldType->getAsCXXRecordDecl();
3967
3968 // -- a variant member with a non-trivial [copy] constructor and X
3969 // is a union-like class
3970 if (UnionFieldRecord &&
3971 !UnionFieldRecord->hasTrivialCopyConstructor())
3972 return true;
3973 }
3974 }
3975
3976 // Don't try to initalize an anonymous union
3977 continue;
3978 } else {
3979 // -- a variant member with a non-trivial [copy] constructor and X is a
3980 // union-like class
3981 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3982 return true;
3983
3984 // -- any [non-static data member] of a type with a destructor that is
3985 // deleted or inaccessible from the defaulted constructor
3986 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3987 if (FieldDtor->isDeleted())
3988 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003989 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003990 AR_accessible)
3991 return true;
3992 }
Alexis Hunt899bd442011-06-10 04:44:37 +00003993
3994 // -- a [non-static data member of class type (or array thereof)] B that
3995 // cannot be [copied] because overload resolution, as applied to B's
3996 // [copy] constructor, results in an ambiguity or a function that is
3997 // deleted or inaccessible from the defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003998 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3999 ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00004000 if (!FieldCtor || FieldCtor->isDeleted())
4001 return true;
4002 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4003 PDiag()) != AR_accessible)
4004 return true;
Alexis Hunt913820d2011-05-13 06:10:58 +00004005 }
Alexis Hunt913820d2011-05-13 06:10:58 +00004006 }
4007
4008 return false;
4009}
4010
Alexis Huntb2f27802011-05-14 05:23:24 +00004011bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4012 CXXRecordDecl *RD = MD->getParent();
4013 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004014 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntb2f27802011-05-14 05:23:24 +00004015 return false;
4016
Alexis Hunte77a28f2011-05-18 03:41:58 +00004017 SourceLocation Loc = MD->getLocation();
4018
Alexis Huntb2f27802011-05-14 05:23:24 +00004019 // Do access control from the constructor
4020 ContextRAII MethodContext(*this, MD);
4021
4022 bool Union = RD->isUnion();
4023
Alexis Hunt491ec602011-06-21 23:42:56 +00004024 unsigned ArgQuals =
4025 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4026 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00004027
4028 // We do this because we should never actually use an anonymous
4029 // union's constructor.
4030 if (Union && RD->isAnonymousStructOrUnion())
4031 return false;
4032
Alexis Huntb2f27802011-05-14 05:23:24 +00004033 // FIXME: We should put some diagnostic logic right into this function.
4034
Sebastian Redl22653ba2011-08-30 19:58:05 +00004035 // C++0x [class.copy]/20
Alexis Huntb2f27802011-05-14 05:23:24 +00004036 // A defaulted [copy] assignment operator for class X is defined as deleted
4037 // if X has:
4038
4039 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4040 BE = RD->bases_end();
4041 BI != BE; ++BI) {
4042 // We'll handle this one later
4043 if (BI->isVirtual())
4044 continue;
4045
4046 QualType BaseType = BI->getType();
4047 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4048 assert(BaseDecl && "base isn't a CXXRecordDecl");
4049
4050 // -- a [direct base class] B that cannot be [copied] because overload
4051 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00004052 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00004053 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004054 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4055 0);
4056 if (!CopyOper || CopyOper->isDeleted())
4057 return true;
4058 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004059 return true;
4060 }
4061
4062 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4063 BE = RD->vbases_end();
4064 BI != BE; ++BI) {
4065 QualType BaseType = BI->getType();
4066 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4067 assert(BaseDecl && "base isn't a CXXRecordDecl");
4068
Alexis Huntb2f27802011-05-14 05:23:24 +00004069 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00004070 // resolution, as applied to B's [copy] assignment operator, results in
4071 // an ambiguity or a function that is deleted or inaccessible from the
4072 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004073 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4074 0);
4075 if (!CopyOper || CopyOper->isDeleted())
4076 return true;
4077 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004078 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00004079 }
4080
4081 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4082 FE = RD->field_end();
4083 FI != FE; ++FI) {
4084 QualType FieldType = Context.getBaseElementType(FI->getType());
4085
4086 // -- a non-static data member of reference type
4087 if (FieldType->isReferenceType())
4088 return true;
4089
4090 // -- a non-static data member of const non-class type (or array thereof)
4091 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4092 return true;
4093
4094 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4095
4096 if (FieldRecord) {
4097 // This is an anonymous union
4098 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4099 // Anonymous unions inside unions do not variant members create
4100 if (!Union) {
4101 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4102 UE = FieldRecord->field_end();
4103 UI != UE; ++UI) {
4104 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4105 CXXRecordDecl *UnionFieldRecord =
4106 UnionFieldType->getAsCXXRecordDecl();
4107
4108 // -- a variant member with a non-trivial [copy] assignment operator
4109 // and X is a union-like class
4110 if (UnionFieldRecord &&
4111 !UnionFieldRecord->hasTrivialCopyAssignment())
4112 return true;
4113 }
4114 }
4115
4116 // Don't try to initalize an anonymous union
4117 continue;
4118 // -- a variant member with a non-trivial [copy] assignment operator
4119 // and X is a union-like class
4120 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4121 return true;
4122 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004123
Alexis Hunt491ec602011-06-21 23:42:56 +00004124 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4125 false, 0);
4126 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl22653ba2011-08-30 19:58:05 +00004127 return true;
Alexis Hunt491ec602011-06-21 23:42:56 +00004128 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl22653ba2011-08-30 19:58:05 +00004129 return true;
4130 }
4131 }
4132
4133 return false;
4134}
4135
4136bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4137 CXXRecordDecl *RD = CD->getParent();
4138 assert(!RD->isDependentType() && "do deletion after instantiation");
4139 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4140 return false;
4141
4142 SourceLocation Loc = CD->getLocation();
4143
4144 // Do access control from the constructor
4145 ContextRAII CtorContext(*this, CD);
4146
4147 bool Union = RD->isUnion();
4148
4149 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4150 "copy assignment arg has no pointee type");
4151
4152 // We do this because we should never actually use an anonymous
4153 // union's constructor.
4154 if (Union && RD->isAnonymousStructOrUnion())
4155 return false;
4156
4157 // C++0x [class.copy]/11
4158 // A defaulted [move] constructor for class X is defined as deleted
4159 // if X has:
4160
4161 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4162 BE = RD->bases_end();
4163 BI != BE; ++BI) {
4164 // We'll handle this one later
4165 if (BI->isVirtual())
4166 continue;
4167
4168 QualType BaseType = BI->getType();
4169 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4170 assert(BaseDecl && "base isn't a CXXRecordDecl");
4171
4172 // -- any [direct base class] of a type with a destructor that is deleted or
4173 // inaccessible from the defaulted constructor
4174 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4175 if (BaseDtor->isDeleted())
4176 return true;
4177 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4178 AR_accessible)
4179 return true;
4180
4181 // -- a [direct base class] B that cannot be [moved] because overload
4182 // resolution, as applied to B's [move] constructor, results in an
4183 // ambiguity or a function that is deleted or inaccessible from the
4184 // defaulted constructor
4185 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4186 if (!BaseCtor || BaseCtor->isDeleted())
4187 return true;
4188 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4189 AR_accessible)
4190 return true;
4191
4192 // -- for a move constructor, a [direct base class] with a type that
4193 // does not have a move constructor and is not trivially copyable.
4194 // If the field isn't a record, it's always trivially copyable.
4195 // A moving constructor could be a copy constructor instead.
4196 if (!BaseCtor->isMoveConstructor() &&
4197 !BaseDecl->isTriviallyCopyable())
4198 return true;
4199 }
4200
4201 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4202 BE = RD->vbases_end();
4203 BI != BE; ++BI) {
4204 QualType BaseType = BI->getType();
4205 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4206 assert(BaseDecl && "base isn't a CXXRecordDecl");
4207
4208 // -- any [virtual base class] of a type with a destructor that is deleted
4209 // or inaccessible from the defaulted constructor
4210 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4211 if (BaseDtor->isDeleted())
4212 return true;
4213 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4214 AR_accessible)
4215 return true;
4216
4217 // -- a [virtual base class] B that cannot be [moved] because overload
4218 // resolution, as applied to B's [move] constructor, results in an
4219 // ambiguity or a function that is deleted or inaccessible from the
4220 // defaulted constructor
4221 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4222 if (!BaseCtor || BaseCtor->isDeleted())
4223 return true;
4224 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4225 AR_accessible)
4226 return true;
4227
4228 // -- for a move constructor, a [virtual base class] with a type that
4229 // does not have a move constructor and is not trivially copyable.
4230 // If the field isn't a record, it's always trivially copyable.
4231 // A moving constructor could be a copy constructor instead.
4232 if (!BaseCtor->isMoveConstructor() &&
4233 !BaseDecl->isTriviallyCopyable())
4234 return true;
4235 }
4236
4237 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4238 FE = RD->field_end();
4239 FI != FE; ++FI) {
4240 QualType FieldType = Context.getBaseElementType(FI->getType());
4241
4242 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4243 // This is an anonymous union
4244 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4245 // Anonymous unions inside unions do not variant members create
4246 if (!Union) {
4247 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4248 UE = FieldRecord->field_end();
4249 UI != UE; ++UI) {
4250 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4251 CXXRecordDecl *UnionFieldRecord =
4252 UnionFieldType->getAsCXXRecordDecl();
4253
4254 // -- a variant member with a non-trivial [move] constructor and X
4255 // is a union-like class
4256 if (UnionFieldRecord &&
4257 !UnionFieldRecord->hasTrivialMoveConstructor())
4258 return true;
4259 }
4260 }
4261
4262 // Don't try to initalize an anonymous union
4263 continue;
4264 } else {
4265 // -- a variant member with a non-trivial [move] constructor and X is a
4266 // union-like class
4267 if (Union && !FieldRecord->hasTrivialMoveConstructor())
4268 return true;
4269
4270 // -- any [non-static data member] of a type with a destructor that is
4271 // deleted or inaccessible from the defaulted constructor
4272 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4273 if (FieldDtor->isDeleted())
4274 return true;
4275 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4276 AR_accessible)
4277 return true;
4278 }
4279
4280 // -- a [non-static data member of class type (or array thereof)] B that
4281 // cannot be [moved] because overload resolution, as applied to B's
4282 // [move] constructor, results in an ambiguity or a function that is
4283 // deleted or inaccessible from the defaulted constructor
4284 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4285 if (!FieldCtor || FieldCtor->isDeleted())
4286 return true;
4287 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4288 PDiag()) != AR_accessible)
4289 return true;
4290
4291 // -- for a move constructor, a [non-static data member] with a type that
4292 // does not have a move constructor and is not trivially copyable.
4293 // If the field isn't a record, it's always trivially copyable.
4294 // A moving constructor could be a copy constructor instead.
4295 if (!FieldCtor->isMoveConstructor() &&
4296 !FieldRecord->isTriviallyCopyable())
4297 return true;
4298 }
4299 }
4300
4301 return false;
4302}
4303
4304bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4305 CXXRecordDecl *RD = MD->getParent();
4306 assert(!RD->isDependentType() && "do deletion after instantiation");
4307 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4308 return false;
4309
4310 SourceLocation Loc = MD->getLocation();
4311
4312 // Do access control from the constructor
4313 ContextRAII MethodContext(*this, MD);
4314
4315 bool Union = RD->isUnion();
4316
4317 // We do this because we should never actually use an anonymous
4318 // union's constructor.
4319 if (Union && RD->isAnonymousStructOrUnion())
4320 return false;
4321
4322 // C++0x [class.copy]/20
4323 // A defaulted [move] assignment operator for class X is defined as deleted
4324 // if X has:
4325
4326 // -- for the move constructor, [...] any direct or indirect virtual base
4327 // class.
4328 if (RD->getNumVBases() != 0)
4329 return true;
4330
4331 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4332 BE = RD->bases_end();
4333 BI != BE; ++BI) {
4334
4335 QualType BaseType = BI->getType();
4336 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4337 assert(BaseDecl && "base isn't a CXXRecordDecl");
4338
4339 // -- a [direct base class] B that cannot be [moved] because overload
4340 // resolution, as applied to B's [move] assignment operator, results in
4341 // an ambiguity or a function that is deleted or inaccessible from the
4342 // assignment operator
4343 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4344 if (!MoveOper || MoveOper->isDeleted())
4345 return true;
4346 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4347 return true;
4348
4349 // -- for the move assignment operator, a [direct base class] with a type
4350 // that does not have a move assignment operator and is not trivially
4351 // copyable.
4352 if (!MoveOper->isMoveAssignmentOperator() &&
4353 !BaseDecl->isTriviallyCopyable())
4354 return true;
4355 }
4356
4357 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4358 FE = RD->field_end();
4359 FI != FE; ++FI) {
4360 QualType FieldType = Context.getBaseElementType(FI->getType());
4361
4362 // -- a non-static data member of reference type
4363 if (FieldType->isReferenceType())
4364 return true;
4365
4366 // -- a non-static data member of const non-class type (or array thereof)
4367 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4368 return true;
4369
4370 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4371
4372 if (FieldRecord) {
4373 // This is an anonymous union
4374 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4375 // Anonymous unions inside unions do not variant members create
4376 if (!Union) {
4377 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4378 UE = FieldRecord->field_end();
4379 UI != UE; ++UI) {
4380 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4381 CXXRecordDecl *UnionFieldRecord =
4382 UnionFieldType->getAsCXXRecordDecl();
4383
4384 // -- a variant member with a non-trivial [move] assignment operator
4385 // and X is a union-like class
4386 if (UnionFieldRecord &&
4387 !UnionFieldRecord->hasTrivialMoveAssignment())
4388 return true;
4389 }
4390 }
4391
4392 // Don't try to initalize an anonymous union
4393 continue;
4394 // -- a variant member with a non-trivial [move] assignment operator
4395 // and X is a union-like class
4396 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4397 return true;
4398 }
4399
4400 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4401 if (!MoveOper || MoveOper->isDeleted())
4402 return true;
4403 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4404 return true;
4405
4406 // -- for the move assignment operator, a [non-static data member] with a
4407 // type that does not have a move assignment operator and is not
4408 // trivially copyable.
4409 if (!MoveOper->isMoveAssignmentOperator() &&
4410 !FieldRecord->isTriviallyCopyable())
4411 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004412 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004413 }
4414
4415 return false;
4416}
4417
Alexis Huntf91729462011-05-12 22:46:25 +00004418bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4419 CXXRecordDecl *RD = DD->getParent();
4420 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004421 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntf91729462011-05-12 22:46:25 +00004422 return false;
4423
Alexis Hunte77a28f2011-05-18 03:41:58 +00004424 SourceLocation Loc = DD->getLocation();
4425
Alexis Huntf91729462011-05-12 22:46:25 +00004426 // Do access control from the destructor
4427 ContextRAII CtorContext(*this, DD);
4428
4429 bool Union = RD->isUnion();
4430
Alexis Hunt913820d2011-05-13 06:10:58 +00004431 // We do this because we should never actually use an anonymous
4432 // union's destructor.
4433 if (Union && RD->isAnonymousStructOrUnion())
4434 return false;
4435
Alexis Huntf91729462011-05-12 22:46:25 +00004436 // C++0x [class.dtor]p5
4437 // A defaulted destructor for a class X is defined as deleted if:
4438 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4439 BE = RD->bases_end();
4440 BI != BE; ++BI) {
4441 // We'll handle this one later
4442 if (BI->isVirtual())
4443 continue;
4444
4445 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4446 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4447 assert(BaseDtor && "base has no destructor");
4448
4449 // -- any direct or virtual base class has a deleted destructor or
4450 // a destructor that is inaccessible from the defaulted destructor
4451 if (BaseDtor->isDeleted())
4452 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004453 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004454 AR_accessible)
4455 return true;
4456 }
4457
4458 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4459 BE = RD->vbases_end();
4460 BI != BE; ++BI) {
4461 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4462 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4463 assert(BaseDtor && "base has no destructor");
4464
4465 // -- any direct or virtual base class has a deleted destructor or
4466 // a destructor that is inaccessible from the defaulted destructor
4467 if (BaseDtor->isDeleted())
4468 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004469 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004470 AR_accessible)
4471 return true;
4472 }
4473
4474 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4475 FE = RD->field_end();
4476 FI != FE; ++FI) {
4477 QualType FieldType = Context.getBaseElementType(FI->getType());
4478 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4479 if (FieldRecord) {
4480 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4481 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4482 UE = FieldRecord->field_end();
4483 UI != UE; ++UI) {
4484 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4485 CXXRecordDecl *UnionFieldRecord =
4486 UnionFieldType->getAsCXXRecordDecl();
4487
4488 // -- X is a union-like class that has a variant member with a non-
4489 // trivial destructor.
4490 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4491 return true;
4492 }
4493 // Technically we are supposed to do this next check unconditionally.
4494 // But that makes absolutely no sense.
4495 } else {
4496 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4497
4498 // -- any of the non-static data members has class type M (or array
4499 // thereof) and M has a deleted destructor or a destructor that is
4500 // inaccessible from the defaulted destructor
4501 if (FieldDtor->isDeleted())
4502 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004503 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004504 AR_accessible)
4505 return true;
4506
4507 // -- X is a union-like class that has a variant member with a non-
4508 // trivial destructor.
4509 if (Union && !FieldDtor->isTrivial())
4510 return true;
4511 }
4512 }
4513 }
4514
4515 if (DD->isVirtual()) {
4516 FunctionDecl *OperatorDelete = 0;
4517 DeclarationName Name =
4518 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004519 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004520 false))
4521 return true;
4522 }
4523
4524
4525 return false;
4526}
4527
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004528/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004529namespace {
4530 struct FindHiddenVirtualMethodData {
4531 Sema *S;
4532 CXXMethodDecl *Method;
4533 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004534 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00004535 };
4536}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004537
4538/// \brief Member lookup function that determines whether a given C++
4539/// method overloads virtual methods in a base class without overriding any,
4540/// to be used with CXXRecordDecl::lookupInBases().
4541static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4542 CXXBasePath &Path,
4543 void *UserData) {
4544 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4545
4546 FindHiddenVirtualMethodData &Data
4547 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4548
4549 DeclarationName Name = Data.Method->getDeclName();
4550 assert(Name.getNameKind() == DeclarationName::Identifier);
4551
4552 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004553 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004554 for (Path.Decls = BaseRecord->lookup(Name);
4555 Path.Decls.first != Path.Decls.second;
4556 ++Path.Decls.first) {
4557 NamedDecl *D = *Path.Decls.first;
4558 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004559 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004560 foundSameNameMethod = true;
4561 // Interested only in hidden virtual methods.
4562 if (!MD->isVirtual())
4563 continue;
4564 // If the method we are checking overrides a method from its base
4565 // don't warn about the other overloaded methods.
4566 if (!Data.S->IsOverload(Data.Method, MD, false))
4567 return true;
4568 // Collect the overload only if its hidden.
4569 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4570 overloadedMethods.push_back(MD);
4571 }
4572 }
4573
4574 if (foundSameNameMethod)
4575 Data.OverloadedMethods.append(overloadedMethods.begin(),
4576 overloadedMethods.end());
4577 return foundSameNameMethod;
4578}
4579
4580/// \brief See if a method overloads virtual methods in a base class without
4581/// overriding any.
4582void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4583 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4584 MD->getLocation()) == Diagnostic::Ignored)
4585 return;
4586 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4587 return;
4588
4589 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4590 /*bool RecordPaths=*/false,
4591 /*bool DetectVirtual=*/false);
4592 FindHiddenVirtualMethodData Data;
4593 Data.Method = MD;
4594 Data.S = this;
4595
4596 // Keep the base methods that were overriden or introduced in the subclass
4597 // by 'using' in a set. A base method not in this set is hidden.
4598 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4599 res.first != res.second; ++res.first) {
4600 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4601 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4602 E = MD->end_overridden_methods();
4603 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004604 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004605 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4606 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004607 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004608 }
4609
4610 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4611 !Data.OverloadedMethods.empty()) {
4612 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4613 << MD << (Data.OverloadedMethods.size() > 1);
4614
4615 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4616 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4617 Diag(overloadedMD->getLocation(),
4618 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4619 }
4620 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00004621}
4622
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004623void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00004624 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004625 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004626 SourceLocation RBrac,
4627 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004628 if (!TagDecl)
4629 return;
Mike Stump11289f42009-09-09 15:08:12 +00004630
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004631 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00004632
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004633 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00004634 // strict aliasing violation!
4635 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004636 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00004637
Douglas Gregor0be31a22010-07-02 17:43:08 +00004638 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00004639 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004640}
4641
Douglas Gregor05379422008-11-03 17:51:48 +00004642/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4643/// special functions, such as the default constructor, copy
4644/// constructor, or destructor, to the given C++ class (C++
4645/// [special]p1). This routine can only be executed just before the
4646/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004647void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004648 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00004649 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004650
Douglas Gregor54be3392010-07-01 17:57:27 +00004651 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00004652 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004653
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004654 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4655 ++ASTContext::NumImplicitCopyAssignmentOperators;
4656
4657 // If we have a dynamic class, then the copy assignment operator may be
4658 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4659 // it shows up in the right place in the vtable and that we diagnose
4660 // problems with the implicit exception specification.
4661 if (ClassDecl->isDynamicClass())
4662 DeclareImplicitCopyAssignment(ClassDecl);
4663 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004664
Douglas Gregor7454c562010-07-02 20:37:36 +00004665 if (!ClassDecl->hasUserDeclaredDestructor()) {
4666 ++ASTContext::NumImplicitDestructors;
4667
4668 // If we have a dynamic class, then the destructor may be virtual, so we
4669 // have to declare the destructor immediately. This ensures that, e.g., it
4670 // shows up in the right place in the vtable and that we diagnose problems
4671 // with the implicit exception specification.
4672 if (ClassDecl->isDynamicClass())
4673 DeclareImplicitDestructor(ClassDecl);
4674 }
Douglas Gregor05379422008-11-03 17:51:48 +00004675}
4676
Francois Pichet1c229c02011-04-22 22:18:13 +00004677void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4678 if (!D)
4679 return;
4680
4681 int NumParamList = D->getNumTemplateParameterLists();
4682 for (int i = 0; i < NumParamList; i++) {
4683 TemplateParameterList* Params = D->getTemplateParameterList(i);
4684 for (TemplateParameterList::iterator Param = Params->begin(),
4685 ParamEnd = Params->end();
4686 Param != ParamEnd; ++Param) {
4687 NamedDecl *Named = cast<NamedDecl>(*Param);
4688 if (Named->getDeclName()) {
4689 S->AddDecl(Named);
4690 IdResolver.AddDecl(Named);
4691 }
4692 }
4693 }
4694}
4695
John McCall48871652010-08-21 09:40:31 +00004696void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00004697 if (!D)
4698 return;
4699
4700 TemplateParameterList *Params = 0;
4701 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4702 Params = Template->getTemplateParameters();
4703 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4704 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4705 Params = PartialSpec->getTemplateParameters();
4706 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004707 return;
4708
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004709 for (TemplateParameterList::iterator Param = Params->begin(),
4710 ParamEnd = Params->end();
4711 Param != ParamEnd; ++Param) {
4712 NamedDecl *Named = cast<NamedDecl>(*Param);
4713 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00004714 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004715 IdResolver.AddDecl(Named);
4716 }
4717 }
4718}
4719
John McCall48871652010-08-21 09:40:31 +00004720void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004721 if (!RecordD) return;
4722 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00004723 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00004724 PushDeclContext(S, Record);
4725}
4726
John McCall48871652010-08-21 09:40:31 +00004727void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004728 if (!RecordD) return;
4729 PopDeclContext();
4730}
4731
Douglas Gregor4d87df52008-12-16 21:30:33 +00004732/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4733/// parsing a top-level (non-nested) C++ class, and we are now
4734/// parsing those parts of the given Method declaration that could
4735/// not be parsed earlier (C++ [class.mem]p2), such as default
4736/// arguments. This action should enter the scope of the given
4737/// Method declaration as if we had just parsed the qualified method
4738/// name. However, it should not bring the parameters into scope;
4739/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00004740void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004741}
4742
4743/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4744/// C++ method declaration. We're (re-)introducing the given
4745/// function parameter into scope for use in parsing later parts of
4746/// the method declaration. For example, we could see an
4747/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00004748void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004749 if (!ParamD)
4750 return;
Mike Stump11289f42009-09-09 15:08:12 +00004751
John McCall48871652010-08-21 09:40:31 +00004752 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00004753
4754 // If this parameter has an unparsed default argument, clear it out
4755 // to make way for the parsed default argument.
4756 if (Param->hasUnparsedDefaultArg())
4757 Param->setDefaultArg(0);
4758
John McCall48871652010-08-21 09:40:31 +00004759 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004760 if (Param->getDeclName())
4761 IdResolver.AddDecl(Param);
4762}
4763
4764/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4765/// processing the delayed method declaration for Method. The method
4766/// declaration is now considered finished. There may be a separate
4767/// ActOnStartOfFunctionDef action later (not necessarily
4768/// immediately!) for this method, if it was also defined inside the
4769/// class body.
John McCall48871652010-08-21 09:40:31 +00004770void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004771 if (!MethodD)
4772 return;
Mike Stump11289f42009-09-09 15:08:12 +00004773
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004774 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00004775
John McCall48871652010-08-21 09:40:31 +00004776 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004777
4778 // Now that we have our default arguments, check the constructor
4779 // again. It could produce additional diagnostics or affect whether
4780 // the class has implicitly-declared destructors, among other
4781 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004782 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4783 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004784
4785 // Check the default arguments, which we may have added.
4786 if (!Method->isInvalidDecl())
4787 CheckCXXDefaultArguments(Method);
4788}
4789
Douglas Gregor831c93f2008-11-05 20:51:48 +00004790/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00004791/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00004792/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004793/// emit diagnostics and set the invalid bit to true. In any case, the type
4794/// will be updated to reflect a well-formed type for the constructor and
4795/// returned.
4796QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004797 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004798 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004799
4800 // C++ [class.ctor]p3:
4801 // A constructor shall not be virtual (10.3) or static (9.4). A
4802 // constructor can be invoked for a const, volatile or const
4803 // volatile object. A constructor shall not be declared const,
4804 // volatile, or const volatile (9.3.2).
4805 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004806 if (!D.isInvalidType())
4807 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4808 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4809 << SourceRange(D.getIdentifierLoc());
4810 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004811 }
John McCall8e7d6562010-08-26 03:08:43 +00004812 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004813 if (!D.isInvalidType())
4814 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4815 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4816 << SourceRange(D.getIdentifierLoc());
4817 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004818 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004819 }
Mike Stump11289f42009-09-09 15:08:12 +00004820
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004821 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004822 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00004823 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004824 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4825 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004826 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004827 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4828 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004829 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004830 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4831 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00004832 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004833 }
Mike Stump11289f42009-09-09 15:08:12 +00004834
Douglas Gregordb9d6642011-01-26 05:01:58 +00004835 // C++0x [class.ctor]p4:
4836 // A constructor shall not be declared with a ref-qualifier.
4837 if (FTI.hasRefQualifier()) {
4838 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4839 << FTI.RefQualifierIsLValueRef
4840 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4841 D.setInvalidType();
4842 }
4843
Douglas Gregor831c93f2008-11-05 20:51:48 +00004844 // Rebuild the function type "R" without any type qualifiers (in
4845 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00004846 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00004847 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004848 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4849 return R;
4850
4851 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4852 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004853 EPI.RefQualifier = RQ_None;
4854
Chris Lattner38378bf2009-04-25 08:28:21 +00004855 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00004856 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004857}
4858
Douglas Gregor4d87df52008-12-16 21:30:33 +00004859/// CheckConstructor - Checks a fully-formed constructor for
4860/// well-formedness, issuing any diagnostics required. Returns true if
4861/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004862void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00004863 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004864 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4865 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004866 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004867
4868 // C++ [class.copy]p3:
4869 // A declaration of a constructor for a class X is ill-formed if
4870 // its first parameter is of type (optionally cv-qualified) X and
4871 // either there are no other parameters or else all other
4872 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004873 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00004874 ((Constructor->getNumParams() == 1) ||
4875 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00004876 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4877 Constructor->getTemplateSpecializationKind()
4878 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004879 QualType ParamType = Constructor->getParamDecl(0)->getType();
4880 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4881 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00004882 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00004883 const char *ConstRef
4884 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4885 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00004886 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00004887 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00004888
4889 // FIXME: Rather that making the constructor invalid, we should endeavor
4890 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004891 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004892 }
4893 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00004894}
4895
John McCalldeb646e2010-08-04 01:04:25 +00004896/// CheckDestructor - Checks a fully-formed destructor definition for
4897/// well-formedness, issuing any diagnostics required. Returns true
4898/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00004899bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00004900 CXXRecordDecl *RD = Destructor->getParent();
4901
4902 if (Destructor->isVirtual()) {
4903 SourceLocation Loc;
4904
4905 if (!Destructor->isImplicit())
4906 Loc = Destructor->getLocation();
4907 else
4908 Loc = RD->getLocation();
4909
4910 // If we have a virtual destructor, look up the deallocation function
4911 FunctionDecl *OperatorDelete = 0;
4912 DeclarationName Name =
4913 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00004914 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00004915 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00004916
4917 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00004918
4919 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004920 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00004921
4922 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00004923}
4924
Mike Stump11289f42009-09-09 15:08:12 +00004925static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00004926FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4927 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4928 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004929 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00004930}
4931
Douglas Gregor831c93f2008-11-05 20:51:48 +00004932/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4933/// the well-formednes of the destructor declarator @p D with type @p
4934/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004935/// emit diagnostics and set the declarator to invalid. Even if this happens,
4936/// will be updated to reflect a well-formed type for the destructor and
4937/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00004938QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004939 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004940 // C++ [class.dtor]p1:
4941 // [...] A typedef-name that names a class is a class-name
4942 // (7.1.3); however, a typedef-name that names a class shall not
4943 // be used as the identifier in the declarator for a destructor
4944 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00004945 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00004946 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00004947 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00004948 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004949 else if (const TemplateSpecializationType *TST =
4950 DeclaratorType->getAs<TemplateSpecializationType>())
4951 if (TST->isTypeAlias())
4952 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4953 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004954
4955 // C++ [class.dtor]p2:
4956 // A destructor is used to destroy objects of its class type. A
4957 // destructor takes no parameters, and no return type can be
4958 // specified for it (not even void). The address of a destructor
4959 // shall not be taken. A destructor shall not be static. A
4960 // destructor can be invoked for a const, volatile or const
4961 // volatile object. A destructor shall not be declared const,
4962 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00004963 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004964 if (!D.isInvalidType())
4965 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4966 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00004967 << SourceRange(D.getIdentifierLoc())
4968 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4969
John McCall8e7d6562010-08-26 03:08:43 +00004970 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004971 }
Chris Lattner38378bf2009-04-25 08:28:21 +00004972 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004973 // Destructors don't have return types, but the parser will
4974 // happily parse something like:
4975 //
4976 // class X {
4977 // float ~X();
4978 // };
4979 //
4980 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00004981 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4982 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4983 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00004984 }
Mike Stump11289f42009-09-09 15:08:12 +00004985
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004986 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004987 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004988 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004989 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4990 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004991 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004992 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4993 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004994 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004995 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4996 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00004997 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004998 }
4999
Douglas Gregordb9d6642011-01-26 05:01:58 +00005000 // C++0x [class.dtor]p2:
5001 // A destructor shall not be declared with a ref-qualifier.
5002 if (FTI.hasRefQualifier()) {
5003 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5004 << FTI.RefQualifierIsLValueRef
5005 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5006 D.setInvalidType();
5007 }
5008
Douglas Gregor831c93f2008-11-05 20:51:48 +00005009 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00005010 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005011 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5012
5013 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00005014 FTI.freeArgs();
5015 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005016 }
5017
Mike Stump11289f42009-09-09 15:08:12 +00005018 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00005019 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005020 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00005021 D.setInvalidType();
5022 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00005023
5024 // Rebuild the function type "R" without any type qualifiers or
5025 // parameters (in case any of the errors above fired) and with
5026 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00005027 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00005028 if (!D.isInvalidType())
5029 return R;
5030
Douglas Gregor95755162010-07-01 05:10:53 +00005031 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005032 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5033 EPI.Variadic = false;
5034 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005035 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005036 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005037}
5038
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005039/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5040/// well-formednes of the conversion function declarator @p D with
5041/// type @p R. If there are any errors in the declarator, this routine
5042/// will emit diagnostics and return true. Otherwise, it will return
5043/// false. Either way, the type @p R will be updated to reflect a
5044/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005045void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00005046 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005047 // C++ [class.conv.fct]p1:
5048 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00005049 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00005050 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00005051 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005052 if (!D.isInvalidType())
5053 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5054 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5055 << SourceRange(D.getIdentifierLoc());
5056 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005057 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005058 }
John McCall212fa2e2010-04-13 00:04:31 +00005059
5060 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5061
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005062 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005063 // Conversion functions don't have return types, but the parser will
5064 // happily parse something like:
5065 //
5066 // class X {
5067 // float operator bool();
5068 // };
5069 //
5070 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00005071 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5072 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5073 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00005074 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005075 }
5076
John McCall212fa2e2010-04-13 00:04:31 +00005077 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5078
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005079 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00005080 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005081 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5082
5083 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005084 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005085 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00005086 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005087 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005088 D.setInvalidType();
5089 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005090
John McCall212fa2e2010-04-13 00:04:31 +00005091 // Diagnose "&operator bool()" and other such nonsense. This
5092 // is actually a gcc extension which we don't support.
5093 if (Proto->getResultType() != ConvType) {
5094 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5095 << Proto->getResultType();
5096 D.setInvalidType();
5097 ConvType = Proto->getResultType();
5098 }
5099
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005100 // C++ [class.conv.fct]p4:
5101 // The conversion-type-id shall not represent a function type nor
5102 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005103 if (ConvType->isArrayType()) {
5104 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5105 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005106 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005107 } else if (ConvType->isFunctionType()) {
5108 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5109 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005110 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005111 }
5112
5113 // Rebuild the function type "R" without any parameters (in case any
5114 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00005115 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00005116 if (D.isInvalidType())
5117 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005118
Douglas Gregor5fb53972009-01-14 15:45:31 +00005119 // C++0x explicit conversion operators.
5120 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00005121 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00005122 diag::warn_explicit_conversion_functions)
5123 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005124}
5125
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005126/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5127/// the declaration of the given C++ conversion function. This routine
5128/// is responsible for recording the conversion function in the C++
5129/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00005130Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005131 assert(Conversion && "Expected to receive a conversion function declaration");
5132
Douglas Gregor4287b372008-12-12 08:25:50 +00005133 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005134
5135 // Make sure we aren't redeclaring the conversion function.
5136 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005137
5138 // C++ [class.conv.fct]p1:
5139 // [...] A conversion function is never used to convert a
5140 // (possibly cv-qualified) object to the (possibly cv-qualified)
5141 // same object type (or a reference to it), to a (possibly
5142 // cv-qualified) base class of that type (or a reference to it),
5143 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00005144 // FIXME: Suppress this warning if the conversion function ends up being a
5145 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00005146 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005147 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005148 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005149 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005150 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5151 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00005152 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005153 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005154 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5155 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005156 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005157 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005158 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005159 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005160 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005161 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005162 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005163 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005164 }
5165
Douglas Gregor457104e2010-09-29 04:25:11 +00005166 if (FunctionTemplateDecl *ConversionTemplate
5167 = Conversion->getDescribedFunctionTemplate())
5168 return ConversionTemplate;
5169
John McCall48871652010-08-21 09:40:31 +00005170 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005171}
5172
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005173//===----------------------------------------------------------------------===//
5174// Namespace Handling
5175//===----------------------------------------------------------------------===//
5176
John McCallb1be5232010-08-26 09:15:37 +00005177
5178
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005179/// ActOnStartNamespaceDef - This is called at the start of a namespace
5180/// definition.
John McCall48871652010-08-21 09:40:31 +00005181Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00005182 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005183 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00005184 SourceLocation IdentLoc,
5185 IdentifierInfo *II,
5186 SourceLocation LBrace,
5187 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005188 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5189 // For anonymous namespace, take the location of the left brace.
5190 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00005191 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005192 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005193 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005194
5195 Scope *DeclRegionScope = NamespcScope->getParent();
5196
Anders Carlssona7bcade2010-02-07 01:09:23 +00005197 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5198
John McCall2faf32c2010-12-10 02:59:44 +00005199 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5200 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00005201
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005202 if (II) {
5203 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00005204 // The identifier in an original-namespace-definition shall not
5205 // have been previously defined in the declarative region in
5206 // which the original-namespace-definition appears. The
5207 // identifier in an original-namespace-definition is the name of
5208 // the namespace. Subsequently in that declarative region, it is
5209 // treated as an original-namespace-name.
5210 //
5211 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005212 // look through using directives, just look for any ordinary names.
5213
5214 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5215 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5216 Decl::IDNS_Namespace;
5217 NamedDecl *PrevDecl = 0;
5218 for (DeclContext::lookup_result R
5219 = CurContext->getRedeclContext()->lookup(II);
5220 R.first != R.second; ++R.first) {
5221 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5222 PrevDecl = *R.first;
5223 break;
5224 }
5225 }
5226
Douglas Gregor91f84212008-12-11 16:49:14 +00005227 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5228 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005229 if (Namespc->isInline() != OrigNS->isInline()) {
5230 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00005231 if (OrigNS->isInline()) {
5232 // The user probably just forgot the 'inline', so suggest that it
5233 // be added back.
5234 Diag(Namespc->getLocation(),
5235 diag::warn_inline_namespace_reopened_noninline)
5236 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5237 } else {
5238 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5239 << Namespc->isInline();
5240 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005241 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00005242
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005243 // Recover by ignoring the new namespace's inline status.
5244 Namespc->setInline(OrigNS->isInline());
5245 }
5246
Douglas Gregor91f84212008-12-11 16:49:14 +00005247 // Attach this namespace decl to the chain of extended namespace
5248 // definitions.
5249 OrigNS->setNextNamespace(Namespc);
5250 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005251
Mike Stump11289f42009-09-09 15:08:12 +00005252 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00005253 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00005254 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00005255 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005256 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005257 } else if (PrevDecl) {
5258 // This is an invalid name redefinition.
5259 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5260 << Namespc->getDeclName();
5261 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5262 Namespc->setInvalidDecl();
5263 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00005264 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00005265 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005266 // This is the first "real" definition of the namespace "std", so update
5267 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005268 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005269 // We had already defined a dummy namespace "std". Link this new
5270 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005271 StdNS->setNextNamespace(Namespc);
5272 StdNS->setLocation(IdentLoc);
5273 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00005274 }
5275
5276 // Make our StdNamespace cache point at the first real definition of the
5277 // "std" namespace.
5278 StdNamespace = Namespc;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005279
5280 // Add this instance of "std" to the set of known namespaces
5281 KnownNamespaces[Namespc] = false;
5282 } else if (!Namespc->isInline()) {
5283 // Since this is an "original" namespace, add it to the known set of
5284 // namespaces if it is not an inline namespace.
5285 KnownNamespaces[Namespc] = false;
Mike Stump11289f42009-09-09 15:08:12 +00005286 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005287
5288 PushOnScopeChains(Namespc, DeclRegionScope);
5289 } else {
John McCall4fa53422009-10-01 00:25:31 +00005290 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00005291 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00005292
5293 // Link the anonymous namespace into its parent.
5294 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00005295 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00005296 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5297 PrevDecl = TU->getAnonymousNamespace();
5298 TU->setAnonymousNamespace(Namespc);
5299 } else {
5300 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5301 PrevDecl = ND->getAnonymousNamespace();
5302 ND->setAnonymousNamespace(Namespc);
5303 }
5304
5305 // Link the anonymous namespace with its previous declaration.
5306 if (PrevDecl) {
5307 assert(PrevDecl->isAnonymousNamespace());
5308 assert(!PrevDecl->getNextNamespace());
5309 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5310 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005311
5312 if (Namespc->isInline() != PrevDecl->isInline()) {
5313 // inline-ness must match
5314 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5315 << Namespc->isInline();
5316 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5317 Namespc->setInvalidDecl();
5318 // Recover by ignoring the new namespace's inline status.
5319 Namespc->setInline(PrevDecl->isInline());
5320 }
John McCall0db42252009-12-16 02:06:49 +00005321 }
John McCall4fa53422009-10-01 00:25:31 +00005322
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00005323 CurContext->addDecl(Namespc);
5324
John McCall4fa53422009-10-01 00:25:31 +00005325 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5326 // behaves as if it were replaced by
5327 // namespace unique { /* empty body */ }
5328 // using namespace unique;
5329 // namespace unique { namespace-body }
5330 // where all occurrences of 'unique' in a translation unit are
5331 // replaced by the same identifier and this identifier differs
5332 // from all other identifiers in the entire program.
5333
5334 // We just create the namespace with an empty name and then add an
5335 // implicit using declaration, just like the standard suggests.
5336 //
5337 // CodeGen enforces the "universally unique" aspect by giving all
5338 // declarations semantically contained within an anonymous
5339 // namespace internal linkage.
5340
John McCall0db42252009-12-16 02:06:49 +00005341 if (!PrevDecl) {
5342 UsingDirectiveDecl* UD
5343 = UsingDirectiveDecl::Create(Context, CurContext,
5344 /* 'using' */ LBrace,
5345 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00005346 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00005347 /* identifier */ SourceLocation(),
5348 Namespc,
5349 /* Ancestor */ CurContext);
5350 UD->setImplicit();
5351 CurContext->addDecl(UD);
5352 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005353 }
5354
5355 // Although we could have an invalid decl (i.e. the namespace name is a
5356 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00005357 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5358 // for the namespace has the declarations that showed up in that particular
5359 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00005360 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00005361 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005362}
5363
Sebastian Redla6602e92009-11-23 15:34:23 +00005364/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5365/// is a namespace alias, returns the namespace it points to.
5366static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5367 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5368 return AD->getNamespace();
5369 return dyn_cast_or_null<NamespaceDecl>(D);
5370}
5371
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005372/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5373/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00005374void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005375 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5376 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005377 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005378 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00005379 if (Namespc->hasAttr<VisibilityAttr>())
5380 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005381}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005382
John McCall28a0cf72010-08-25 07:42:41 +00005383CXXRecordDecl *Sema::getStdBadAlloc() const {
5384 return cast_or_null<CXXRecordDecl>(
5385 StdBadAlloc.get(Context.getExternalSource()));
5386}
5387
5388NamespaceDecl *Sema::getStdNamespace() const {
5389 return cast_or_null<NamespaceDecl>(
5390 StdNamespace.get(Context.getExternalSource()));
5391}
5392
Douglas Gregorcdf87022010-06-29 17:53:46 +00005393/// \brief Retrieve the special "std" namespace, which may require us to
5394/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005395NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00005396 if (!StdNamespace) {
5397 // The "std" namespace has not yet been defined, so build one implicitly.
5398 StdNamespace = NamespaceDecl::Create(Context,
5399 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005400 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00005401 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005402 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005403 }
5404
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005405 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005406}
5407
Douglas Gregora172e082011-03-26 22:25:30 +00005408/// \brief Determine whether a using statement is in a context where it will be
5409/// apply in all contexts.
5410static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5411 switch (CurContext->getDeclKind()) {
5412 case Decl::TranslationUnit:
5413 return true;
5414 case Decl::LinkageSpec:
5415 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5416 default:
5417 return false;
5418 }
5419}
5420
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005421static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5422 CXXScopeSpec &SS,
5423 SourceLocation IdentLoc,
5424 IdentifierInfo *Ident) {
5425 R.clear();
5426 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5427 R.getLookupKind(), Sc, &SS, NULL,
5428 false, S.CTC_NoKeywords, NULL)) {
5429 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5430 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5431 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5432 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5433 if (DeclContext *DC = S.computeDeclContext(SS, false))
5434 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5435 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5436 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5437 else
5438 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5439 << Ident << CorrectedQuotedStr
5440 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5441
5442 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5443 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5444
5445 Ident = Corrected.getCorrectionAsIdentifierInfo();
5446 R.addDecl(Corrected.getCorrectionDecl());
5447 return true;
5448 }
5449 R.setLookupName(Ident);
5450 }
5451 return false;
5452}
5453
John McCall48871652010-08-21 09:40:31 +00005454Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005455 SourceLocation UsingLoc,
5456 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005457 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00005458 SourceLocation IdentLoc,
5459 IdentifierInfo *NamespcName,
5460 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00005461 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5462 assert(NamespcName && "Invalid NamespcName.");
5463 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00005464
5465 // This can only happen along a recovery path.
5466 while (S->getFlags() & Scope::TemplateParamScope)
5467 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00005468 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00005469
Douglas Gregor889ceb72009-02-03 19:21:40 +00005470 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00005471 NestedNameSpecifier *Qualifier = 0;
5472 if (SS.isSet())
5473 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5474
Douglas Gregor34074322009-01-14 22:20:51 +00005475 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005476 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5477 LookupParsedName(R, S, &SS);
5478 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005479 return 0;
John McCall27b18f82009-11-17 02:14:36 +00005480
Douglas Gregorcdf87022010-06-29 17:53:46 +00005481 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005482 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005483 // Allow "using namespace std;" or "using namespace ::std;" even if
5484 // "std" hasn't been defined yet, for GCC compatibility.
5485 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5486 NamespcName->isStr("std")) {
5487 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005488 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00005489 R.resolveKind();
5490 }
5491 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005492 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005493 }
5494
John McCall9f3059a2009-10-09 21:13:30 +00005495 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00005496 NamedDecl *Named = R.getFoundDecl();
5497 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5498 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00005499 // C++ [namespace.udir]p1:
5500 // A using-directive specifies that the names in the nominated
5501 // namespace can be used in the scope in which the
5502 // using-directive appears after the using-directive. During
5503 // unqualified name lookup (3.4.1), the names appear as if they
5504 // were declared in the nearest enclosing namespace which
5505 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00005506 // namespace. [Note: in this context, "contains" means "contains
5507 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00005508
5509 // Find enclosing context containing both using-directive and
5510 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00005511 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005512 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5513 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5514 CommonAncestor = CommonAncestor->getParent();
5515
Sebastian Redla6602e92009-11-23 15:34:23 +00005516 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00005517 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00005518 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005519
Douglas Gregora172e082011-03-26 22:25:30 +00005520 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00005521 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005522 Diag(IdentLoc, diag::warn_using_directive_in_header);
5523 }
5524
Douglas Gregor889ceb72009-02-03 19:21:40 +00005525 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005526 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00005527 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00005528 }
5529
Douglas Gregor889ceb72009-02-03 19:21:40 +00005530 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00005531 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00005532}
5533
5534void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5535 // If scope has associated entity, then using directive is at namespace
5536 // or translation unit scope. We add UsingDirectiveDecls, into
5537 // it's lookup structure.
5538 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005539 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005540 else
5541 // Otherwise it is block-sope. using-directives will affect lookup
5542 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00005543 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005544}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005545
Douglas Gregorfec52632009-06-20 00:51:54 +00005546
John McCall48871652010-08-21 09:40:31 +00005547Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00005548 AccessSpecifier AS,
5549 bool HasUsingKeyword,
5550 SourceLocation UsingLoc,
5551 CXXScopeSpec &SS,
5552 UnqualifiedId &Name,
5553 AttributeList *AttrList,
5554 bool IsTypeName,
5555 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00005556 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00005557
Douglas Gregor220f4272009-11-04 16:30:06 +00005558 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00005559 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00005560 case UnqualifiedId::IK_Identifier:
5561 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00005562 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00005563 case UnqualifiedId::IK_ConversionFunctionId:
5564 break;
5565
5566 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005567 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00005568 // C++0x inherited constructors.
5569 if (getLangOptions().CPlusPlus0x) break;
5570
Douglas Gregor220f4272009-11-04 16:30:06 +00005571 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5572 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005573 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005574
5575 case UnqualifiedId::IK_DestructorName:
5576 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5577 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005578 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005579
5580 case UnqualifiedId::IK_TemplateId:
5581 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5582 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00005583 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005584 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005585
5586 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5587 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00005588 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00005589 return 0;
John McCall3969e302009-12-08 07:46:18 +00005590
John McCalla0097262009-12-11 02:10:03 +00005591 // Warn about using declarations.
5592 // TODO: store that the declaration was written without 'using' and
5593 // talk about access decls instead of using decls in the
5594 // diagnostics.
5595 if (!HasUsingKeyword) {
5596 UsingLoc = Name.getSourceRange().getBegin();
5597
5598 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00005599 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00005600 }
5601
Douglas Gregorc4356532010-12-16 00:46:58 +00005602 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5603 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5604 return 0;
5605
John McCall3f746822009-11-17 05:59:44 +00005606 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005607 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005608 /* IsInstantiation */ false,
5609 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00005610 if (UD)
5611 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00005612
John McCall48871652010-08-21 09:40:31 +00005613 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00005614}
5615
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005616/// \brief Determine whether a using declaration considers the given
5617/// declarations as "equivalent", e.g., if they are redeclarations of
5618/// the same entity or are both typedefs of the same type.
5619static bool
5620IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5621 bool &SuppressRedeclaration) {
5622 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5623 SuppressRedeclaration = false;
5624 return true;
5625 }
5626
Richard Smithdda56e42011-04-15 14:24:37 +00005627 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5628 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005629 SuppressRedeclaration = true;
5630 return Context.hasSameType(TD1->getUnderlyingType(),
5631 TD2->getUnderlyingType());
5632 }
5633
5634 return false;
5635}
5636
5637
John McCall84d87672009-12-10 09:41:52 +00005638/// Determines whether to create a using shadow decl for a particular
5639/// decl, given the set of decls existing prior to this using lookup.
5640bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5641 const LookupResult &Previous) {
5642 // Diagnose finding a decl which is not from a base class of the
5643 // current class. We do this now because there are cases where this
5644 // function will silently decide not to build a shadow decl, which
5645 // will pre-empt further diagnostics.
5646 //
5647 // We don't need to do this in C++0x because we do the check once on
5648 // the qualifier.
5649 //
5650 // FIXME: diagnose the following if we care enough:
5651 // struct A { int foo; };
5652 // struct B : A { using A::foo; };
5653 // template <class T> struct C : A {};
5654 // template <class T> struct D : C<T> { using B::foo; } // <---
5655 // This is invalid (during instantiation) in C++03 because B::foo
5656 // resolves to the using decl in B, which is not a base class of D<T>.
5657 // We can't diagnose it immediately because C<T> is an unknown
5658 // specialization. The UsingShadowDecl in D<T> then points directly
5659 // to A::foo, which will look well-formed when we instantiate.
5660 // The right solution is to not collapse the shadow-decl chain.
5661 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5662 DeclContext *OrigDC = Orig->getDeclContext();
5663
5664 // Handle enums and anonymous structs.
5665 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5666 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5667 while (OrigRec->isAnonymousStructOrUnion())
5668 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5669
5670 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5671 if (OrigDC == CurContext) {
5672 Diag(Using->getLocation(),
5673 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005674 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005675 Diag(Orig->getLocation(), diag::note_using_decl_target);
5676 return true;
5677 }
5678
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005679 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00005680 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005681 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00005682 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005683 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005684 Diag(Orig->getLocation(), diag::note_using_decl_target);
5685 return true;
5686 }
5687 }
5688
5689 if (Previous.empty()) return false;
5690
5691 NamedDecl *Target = Orig;
5692 if (isa<UsingShadowDecl>(Target))
5693 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5694
John McCalla17e83e2009-12-11 02:33:26 +00005695 // If the target happens to be one of the previous declarations, we
5696 // don't have a conflict.
5697 //
5698 // FIXME: but we might be increasing its access, in which case we
5699 // should redeclare it.
5700 NamedDecl *NonTag = 0, *Tag = 0;
5701 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5702 I != E; ++I) {
5703 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005704 bool Result;
5705 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5706 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00005707
5708 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5709 }
5710
John McCall84d87672009-12-10 09:41:52 +00005711 if (Target->isFunctionOrFunctionTemplate()) {
5712 FunctionDecl *FD;
5713 if (isa<FunctionTemplateDecl>(Target))
5714 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5715 else
5716 FD = cast<FunctionDecl>(Target);
5717
5718 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00005719 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00005720 case Ovl_Overload:
5721 return false;
5722
5723 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00005724 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005725 break;
5726
5727 // We found a decl with the exact signature.
5728 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005729 // If we're in a record, we want to hide the target, so we
5730 // return true (without a diagnostic) to tell the caller not to
5731 // build a shadow decl.
5732 if (CurContext->isRecord())
5733 return true;
5734
5735 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00005736 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005737 break;
5738 }
5739
5740 Diag(Target->getLocation(), diag::note_using_decl_target);
5741 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5742 return true;
5743 }
5744
5745 // Target is not a function.
5746
John McCall84d87672009-12-10 09:41:52 +00005747 if (isa<TagDecl>(Target)) {
5748 // No conflict between a tag and a non-tag.
5749 if (!Tag) return false;
5750
John McCalle29c5cd2009-12-10 19:51:03 +00005751 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005752 Diag(Target->getLocation(), diag::note_using_decl_target);
5753 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5754 return true;
5755 }
5756
5757 // No conflict between a tag and a non-tag.
5758 if (!NonTag) return false;
5759
John McCalle29c5cd2009-12-10 19:51:03 +00005760 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005761 Diag(Target->getLocation(), diag::note_using_decl_target);
5762 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5763 return true;
5764}
5765
John McCall3f746822009-11-17 05:59:44 +00005766/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00005767UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00005768 UsingDecl *UD,
5769 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00005770
5771 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00005772 NamedDecl *Target = Orig;
5773 if (isa<UsingShadowDecl>(Target)) {
5774 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5775 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00005776 }
5777
5778 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00005779 = UsingShadowDecl::Create(Context, CurContext,
5780 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00005781 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00005782
5783 Shadow->setAccess(UD->getAccess());
5784 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5785 Shadow->setInvalidDecl();
5786
John McCall3f746822009-11-17 05:59:44 +00005787 if (S)
John McCall3969e302009-12-08 07:46:18 +00005788 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00005789 else
John McCall3969e302009-12-08 07:46:18 +00005790 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00005791
John McCall3969e302009-12-08 07:46:18 +00005792
John McCall84d87672009-12-10 09:41:52 +00005793 return Shadow;
5794}
John McCall3969e302009-12-08 07:46:18 +00005795
John McCall84d87672009-12-10 09:41:52 +00005796/// Hides a using shadow declaration. This is required by the current
5797/// using-decl implementation when a resolvable using declaration in a
5798/// class is followed by a declaration which would hide or override
5799/// one or more of the using decl's targets; for example:
5800///
5801/// struct Base { void foo(int); };
5802/// struct Derived : Base {
5803/// using Base::foo;
5804/// void foo(int);
5805/// };
5806///
5807/// The governing language is C++03 [namespace.udecl]p12:
5808///
5809/// When a using-declaration brings names from a base class into a
5810/// derived class scope, member functions in the derived class
5811/// override and/or hide member functions with the same name and
5812/// parameter types in a base class (rather than conflicting).
5813///
5814/// There are two ways to implement this:
5815/// (1) optimistically create shadow decls when they're not hidden
5816/// by existing declarations, or
5817/// (2) don't create any shadow decls (or at least don't make them
5818/// visible) until we've fully parsed/instantiated the class.
5819/// The problem with (1) is that we might have to retroactively remove
5820/// a shadow decl, which requires several O(n) operations because the
5821/// decl structures are (very reasonably) not designed for removal.
5822/// (2) avoids this but is very fiddly and phase-dependent.
5823void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00005824 if (Shadow->getDeclName().getNameKind() ==
5825 DeclarationName::CXXConversionFunctionName)
5826 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5827
John McCall84d87672009-12-10 09:41:52 +00005828 // Remove it from the DeclContext...
5829 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005830
John McCall84d87672009-12-10 09:41:52 +00005831 // ...and the scope, if applicable...
5832 if (S) {
John McCall48871652010-08-21 09:40:31 +00005833 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00005834 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005835 }
5836
John McCall84d87672009-12-10 09:41:52 +00005837 // ...and the using decl.
5838 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5839
5840 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00005841 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00005842}
5843
John McCalle61f2ba2009-11-18 02:36:19 +00005844/// Builds a using declaration.
5845///
5846/// \param IsInstantiation - Whether this call arises from an
5847/// instantiation of an unresolved using declaration. We treat
5848/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00005849NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5850 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005851 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005852 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00005853 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005854 bool IsInstantiation,
5855 bool IsTypeName,
5856 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00005857 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005858 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00005859 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00005860
Anders Carlssonf038fc22009-08-28 05:49:21 +00005861 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00005862
Anders Carlsson59140b32009-08-28 03:16:11 +00005863 if (SS.isEmpty()) {
5864 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00005865 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00005866 }
Mike Stump11289f42009-09-09 15:08:12 +00005867
John McCall84d87672009-12-10 09:41:52 +00005868 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005869 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00005870 ForRedeclaration);
5871 Previous.setHideTags(false);
5872 if (S) {
5873 LookupName(Previous, S);
5874
5875 // It is really dumb that we have to do this.
5876 LookupResult::Filter F = Previous.makeFilter();
5877 while (F.hasNext()) {
5878 NamedDecl *D = F.next();
5879 if (!isDeclInScope(D, CurContext, S))
5880 F.erase();
5881 }
5882 F.done();
5883 } else {
5884 assert(IsInstantiation && "no scope in non-instantiation");
5885 assert(CurContext->isRecord() && "scope not record in instantiation");
5886 LookupQualifiedName(Previous, CurContext);
5887 }
5888
John McCall84d87672009-12-10 09:41:52 +00005889 // Check for invalid redeclarations.
5890 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5891 return 0;
5892
5893 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00005894 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5895 return 0;
5896
John McCall84c16cf2009-11-12 03:15:40 +00005897 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005898 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005899 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00005900 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00005901 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00005902 // FIXME: not all declaration name kinds are legal here
5903 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5904 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005905 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005906 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00005907 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005908 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5909 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00005910 }
John McCallb96ec562009-12-04 22:46:56 +00005911 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005912 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5913 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00005914 }
John McCallb96ec562009-12-04 22:46:56 +00005915 D->setAccess(AS);
5916 CurContext->addDecl(D);
5917
5918 if (!LookupContext) return D;
5919 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00005920
John McCall0b66eb32010-05-01 00:40:08 +00005921 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00005922 UD->setInvalidDecl();
5923 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00005924 }
5925
Sebastian Redl08905022011-02-05 19:23:19 +00005926 // Constructor inheriting using decls get special treatment.
5927 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00005928 if (CheckInheritedConstructorUsingDecl(UD))
5929 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00005930 return UD;
5931 }
5932
5933 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00005934
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005935 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetefb1af92011-05-23 03:43:44 +00005936 R.setUsingDeclaration(true);
John McCalle61f2ba2009-11-18 02:36:19 +00005937
John McCall3969e302009-12-08 07:46:18 +00005938 // Unlike most lookups, we don't always want to hide tag
5939 // declarations: tag names are visible through the using declaration
5940 // even if hidden by ordinary names, *except* in a dependent context
5941 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00005942 if (!IsInstantiation)
5943 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00005944
John McCall27b18f82009-11-17 02:14:36 +00005945 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00005946
John McCall9f3059a2009-10-09 21:13:30 +00005947 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00005948 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005949 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005950 UD->setInvalidDecl();
5951 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005952 }
5953
John McCallb96ec562009-12-04 22:46:56 +00005954 if (R.isAmbiguous()) {
5955 UD->setInvalidDecl();
5956 return UD;
5957 }
Mike Stump11289f42009-09-09 15:08:12 +00005958
John McCalle61f2ba2009-11-18 02:36:19 +00005959 if (IsTypeName) {
5960 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00005961 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005962 Diag(IdentLoc, diag::err_using_typename_non_type);
5963 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5964 Diag((*I)->getUnderlyingDecl()->getLocation(),
5965 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005966 UD->setInvalidDecl();
5967 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005968 }
5969 } else {
5970 // If we asked for a non-typename and we got a type, error out,
5971 // but only if this is an instantiation of an unresolved using
5972 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00005973 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005974 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5975 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005976 UD->setInvalidDecl();
5977 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005978 }
Anders Carlsson59140b32009-08-28 03:16:11 +00005979 }
5980
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005981 // C++0x N2914 [namespace.udecl]p6:
5982 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00005983 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005984 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5985 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005986 UD->setInvalidDecl();
5987 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005988 }
Mike Stump11289f42009-09-09 15:08:12 +00005989
John McCall84d87672009-12-10 09:41:52 +00005990 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5991 if (!CheckUsingShadowDecl(UD, *I, Previous))
5992 BuildUsingShadowDecl(S, UD, *I);
5993 }
John McCall3f746822009-11-17 05:59:44 +00005994
5995 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005996}
5997
Sebastian Redl08905022011-02-05 19:23:19 +00005998/// Additional checks for a using declaration referring to a constructor name.
5999bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6000 if (UD->isTypeName()) {
6001 // FIXME: Cannot specify typename when specifying constructor
6002 return true;
6003 }
6004
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006005 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00006006 assert(SourceType &&
6007 "Using decl naming constructor doesn't have type in scope spec.");
6008 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6009
6010 // Check whether the named type is a direct base class.
6011 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6012 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6013 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6014 BaseIt != BaseE; ++BaseIt) {
6015 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6016 if (CanonicalSourceType == BaseType)
6017 break;
6018 }
6019
6020 if (BaseIt == BaseE) {
6021 // Did not find SourceType in the bases.
6022 Diag(UD->getUsingLocation(),
6023 diag::err_using_decl_constructor_not_in_direct_base)
6024 << UD->getNameInfo().getSourceRange()
6025 << QualType(SourceType, 0) << TargetClass;
6026 return true;
6027 }
6028
6029 BaseIt->setInheritConstructors();
6030
6031 return false;
6032}
6033
John McCall84d87672009-12-10 09:41:52 +00006034/// Checks that the given using declaration is not an invalid
6035/// redeclaration. Note that this is checking only for the using decl
6036/// itself, not for any ill-formedness among the UsingShadowDecls.
6037bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6038 bool isTypeName,
6039 const CXXScopeSpec &SS,
6040 SourceLocation NameLoc,
6041 const LookupResult &Prev) {
6042 // C++03 [namespace.udecl]p8:
6043 // C++0x [namespace.udecl]p10:
6044 // A using-declaration is a declaration and can therefore be used
6045 // repeatedly where (and only where) multiple declarations are
6046 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00006047 //
John McCall032092f2010-11-29 18:01:58 +00006048 // That's in non-member contexts.
6049 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00006050 return false;
6051
6052 NestedNameSpecifier *Qual
6053 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6054
6055 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6056 NamedDecl *D = *I;
6057
6058 bool DTypename;
6059 NestedNameSpecifier *DQual;
6060 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6061 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006062 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006063 } else if (UnresolvedUsingValueDecl *UD
6064 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6065 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006066 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006067 } else if (UnresolvedUsingTypenameDecl *UD
6068 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6069 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006070 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006071 } else continue;
6072
6073 // using decls differ if one says 'typename' and the other doesn't.
6074 // FIXME: non-dependent using decls?
6075 if (isTypeName != DTypename) continue;
6076
6077 // using decls differ if they name different scopes (but note that
6078 // template instantiation can cause this check to trigger when it
6079 // didn't before instantiation).
6080 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6081 Context.getCanonicalNestedNameSpecifier(DQual))
6082 continue;
6083
6084 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00006085 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00006086 return true;
6087 }
6088
6089 return false;
6090}
6091
John McCall3969e302009-12-08 07:46:18 +00006092
John McCallb96ec562009-12-04 22:46:56 +00006093/// Checks that the given nested-name qualifier used in a using decl
6094/// in the current context is appropriately related to the current
6095/// scope. If an error is found, diagnoses it and returns true.
6096bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6097 const CXXScopeSpec &SS,
6098 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00006099 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006100
John McCall3969e302009-12-08 07:46:18 +00006101 if (!CurContext->isRecord()) {
6102 // C++03 [namespace.udecl]p3:
6103 // C++0x [namespace.udecl]p8:
6104 // A using-declaration for a class member shall be a member-declaration.
6105
6106 // If we weren't able to compute a valid scope, it must be a
6107 // dependent class scope.
6108 if (!NamedContext || NamedContext->isRecord()) {
6109 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6110 << SS.getRange();
6111 return true;
6112 }
6113
6114 // Otherwise, everything is known to be fine.
6115 return false;
6116 }
6117
6118 // The current scope is a record.
6119
6120 // If the named context is dependent, we can't decide much.
6121 if (!NamedContext) {
6122 // FIXME: in C++0x, we can diagnose if we can prove that the
6123 // nested-name-specifier does not refer to a base class, which is
6124 // still possible in some cases.
6125
6126 // Otherwise we have to conservatively report that things might be
6127 // okay.
6128 return false;
6129 }
6130
6131 if (!NamedContext->isRecord()) {
6132 // Ideally this would point at the last name in the specifier,
6133 // but we don't have that level of source info.
6134 Diag(SS.getRange().getBegin(),
6135 diag::err_using_decl_nested_name_specifier_is_not_class)
6136 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6137 return true;
6138 }
6139
Douglas Gregor7c842292010-12-21 07:41:49 +00006140 if (!NamedContext->isDependentContext() &&
6141 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6142 return true;
6143
John McCall3969e302009-12-08 07:46:18 +00006144 if (getLangOptions().CPlusPlus0x) {
6145 // C++0x [namespace.udecl]p3:
6146 // In a using-declaration used as a member-declaration, the
6147 // nested-name-specifier shall name a base class of the class
6148 // being defined.
6149
6150 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6151 cast<CXXRecordDecl>(NamedContext))) {
6152 if (CurContext == NamedContext) {
6153 Diag(NameLoc,
6154 diag::err_using_decl_nested_name_specifier_is_current_class)
6155 << SS.getRange();
6156 return true;
6157 }
6158
6159 Diag(SS.getRange().getBegin(),
6160 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6161 << (NestedNameSpecifier*) SS.getScopeRep()
6162 << cast<CXXRecordDecl>(CurContext)
6163 << SS.getRange();
6164 return true;
6165 }
6166
6167 return false;
6168 }
6169
6170 // C++03 [namespace.udecl]p4:
6171 // A using-declaration used as a member-declaration shall refer
6172 // to a member of a base class of the class being defined [etc.].
6173
6174 // Salient point: SS doesn't have to name a base class as long as
6175 // lookup only finds members from base classes. Therefore we can
6176 // diagnose here only if we can prove that that can't happen,
6177 // i.e. if the class hierarchies provably don't intersect.
6178
6179 // TODO: it would be nice if "definitely valid" results were cached
6180 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6181 // need to be repeated.
6182
6183 struct UserData {
6184 llvm::DenseSet<const CXXRecordDecl*> Bases;
6185
6186 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6187 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6188 Data->Bases.insert(Base);
6189 return true;
6190 }
6191
6192 bool hasDependentBases(const CXXRecordDecl *Class) {
6193 return !Class->forallBases(collect, this);
6194 }
6195
6196 /// Returns true if the base is dependent or is one of the
6197 /// accumulated base classes.
6198 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6199 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6200 return !Data->Bases.count(Base);
6201 }
6202
6203 bool mightShareBases(const CXXRecordDecl *Class) {
6204 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6205 }
6206 };
6207
6208 UserData Data;
6209
6210 // Returns false if we find a dependent base.
6211 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6212 return false;
6213
6214 // Returns false if the class has a dependent base or if it or one
6215 // of its bases is present in the base set of the current context.
6216 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6217 return false;
6218
6219 Diag(SS.getRange().getBegin(),
6220 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6221 << (NestedNameSpecifier*) SS.getScopeRep()
6222 << cast<CXXRecordDecl>(CurContext)
6223 << SS.getRange();
6224
6225 return true;
John McCallb96ec562009-12-04 22:46:56 +00006226}
6227
Richard Smithdda56e42011-04-15 14:24:37 +00006228Decl *Sema::ActOnAliasDeclaration(Scope *S,
6229 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006230 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00006231 SourceLocation UsingLoc,
6232 UnqualifiedId &Name,
6233 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00006234 // Skip up to the relevant declaration scope.
6235 while (S->getFlags() & Scope::TemplateParamScope)
6236 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00006237 assert((S->getFlags() & Scope::DeclScope) &&
6238 "got alias-declaration outside of declaration scope");
6239
6240 if (Type.isInvalid())
6241 return 0;
6242
6243 bool Invalid = false;
6244 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6245 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00006246 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00006247
6248 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6249 return 0;
6250
6251 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006252 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00006253 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006254 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6255 TInfo->getTypeLoc().getBeginLoc());
6256 }
Richard Smithdda56e42011-04-15 14:24:37 +00006257
6258 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6259 LookupName(Previous, S);
6260
6261 // Warn about shadowing the name of a template parameter.
6262 if (Previous.isSingleResult() &&
6263 Previous.getFoundDecl()->isTemplateParameter()) {
6264 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6265 Previous.getFoundDecl()))
6266 Invalid = true;
6267 Previous.clear();
6268 }
6269
6270 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6271 "name in alias declaration must be an identifier");
6272 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6273 Name.StartLocation,
6274 Name.Identifier, TInfo);
6275
6276 NewTD->setAccess(AS);
6277
6278 if (Invalid)
6279 NewTD->setInvalidDecl();
6280
Richard Smith3f1b5d02011-05-05 21:57:07 +00006281 CheckTypedefForVariablyModifiedType(S, NewTD);
6282 Invalid |= NewTD->isInvalidDecl();
6283
Richard Smithdda56e42011-04-15 14:24:37 +00006284 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006285
6286 NamedDecl *NewND;
6287 if (TemplateParamLists.size()) {
6288 TypeAliasTemplateDecl *OldDecl = 0;
6289 TemplateParameterList *OldTemplateParams = 0;
6290
6291 if (TemplateParamLists.size() != 1) {
6292 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6293 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6294 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6295 }
6296 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6297
6298 // Only consider previous declarations in the same scope.
6299 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6300 /*ExplicitInstantiationOrSpecialization*/false);
6301 if (!Previous.empty()) {
6302 Redeclaration = true;
6303
6304 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6305 if (!OldDecl && !Invalid) {
6306 Diag(UsingLoc, diag::err_redefinition_different_kind)
6307 << Name.Identifier;
6308
6309 NamedDecl *OldD = Previous.getRepresentativeDecl();
6310 if (OldD->getLocation().isValid())
6311 Diag(OldD->getLocation(), diag::note_previous_definition);
6312
6313 Invalid = true;
6314 }
6315
6316 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6317 if (TemplateParameterListsAreEqual(TemplateParams,
6318 OldDecl->getTemplateParameters(),
6319 /*Complain=*/true,
6320 TPL_TemplateMatch))
6321 OldTemplateParams = OldDecl->getTemplateParameters();
6322 else
6323 Invalid = true;
6324
6325 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6326 if (!Invalid &&
6327 !Context.hasSameType(OldTD->getUnderlyingType(),
6328 NewTD->getUnderlyingType())) {
6329 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6330 // but we can't reasonably accept it.
6331 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6332 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6333 if (OldTD->getLocation().isValid())
6334 Diag(OldTD->getLocation(), diag::note_previous_definition);
6335 Invalid = true;
6336 }
6337 }
6338 }
6339
6340 // Merge any previous default template arguments into our parameters,
6341 // and check the parameter list.
6342 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6343 TPC_TypeAliasTemplate))
6344 return 0;
6345
6346 TypeAliasTemplateDecl *NewDecl =
6347 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6348 Name.Identifier, TemplateParams,
6349 NewTD);
6350
6351 NewDecl->setAccess(AS);
6352
6353 if (Invalid)
6354 NewDecl->setInvalidDecl();
6355 else if (OldDecl)
6356 NewDecl->setPreviousDeclaration(OldDecl);
6357
6358 NewND = NewDecl;
6359 } else {
6360 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6361 NewND = NewTD;
6362 }
Richard Smithdda56e42011-04-15 14:24:37 +00006363
6364 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00006365 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00006366
Richard Smith3f1b5d02011-05-05 21:57:07 +00006367 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00006368}
6369
John McCall48871652010-08-21 09:40:31 +00006370Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006371 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006372 SourceLocation AliasLoc,
6373 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006374 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006375 SourceLocation IdentLoc,
6376 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00006377
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006378 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006379 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6380 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006381
Anders Carlssondca83c42009-03-28 06:23:46 +00006382 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00006383 NamedDecl *PrevDecl
6384 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6385 ForRedeclaration);
6386 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6387 PrevDecl = 0;
6388
6389 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006390 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00006391 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006392 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00006393 // FIXME: At some point, we'll want to create the (redundant)
6394 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00006395 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00006396 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00006397 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006398 }
Mike Stump11289f42009-09-09 15:08:12 +00006399
Anders Carlssondca83c42009-03-28 06:23:46 +00006400 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6401 diag::err_redefinition_different_kind;
6402 Diag(AliasLoc, DiagID) << Alias;
6403 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00006404 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00006405 }
6406
John McCall27b18f82009-11-17 02:14:36 +00006407 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006408 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006409
John McCall9f3059a2009-10-09 21:13:30 +00006410 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006411 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006412 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006413 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006414 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00006415 }
Mike Stump11289f42009-09-09 15:08:12 +00006416
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006417 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00006418 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00006419 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00006420 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006421
John McCalld8d0d432010-02-16 06:53:13 +00006422 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00006423 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00006424}
6425
Douglas Gregora57478e2010-05-01 15:04:51 +00006426namespace {
6427 /// \brief Scoped object used to handle the state changes required in Sema
6428 /// to implicitly define the body of a C++ member function;
6429 class ImplicitlyDefinedFunctionScope {
6430 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00006431 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00006432
6433 public:
6434 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00006435 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00006436 {
Douglas Gregora57478e2010-05-01 15:04:51 +00006437 S.PushFunctionScope();
6438 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6439 }
6440
6441 ~ImplicitlyDefinedFunctionScope() {
6442 S.PopExpressionEvaluationContext();
6443 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00006444 }
6445 };
6446}
6447
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006448Sema::ImplicitExceptionSpecification
6449Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00006450 // C++ [except.spec]p14:
6451 // An implicitly declared special member function (Clause 12) shall have an
6452 // exception-specification. [...]
6453 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006454 if (ClassDecl->isInvalidDecl())
6455 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00006456
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006457 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006458 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6459 BEnd = ClassDecl->bases_end();
6460 B != BEnd; ++B) {
6461 if (B->isVirtual()) // Handled below.
6462 continue;
6463
Douglas Gregor9672f922010-07-03 00:47:00 +00006464 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6465 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006466 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6467 // If this is a deleted function, add it anyway. This might be conformant
6468 // with the standard. This might not. I'm not sure. It might not matter.
6469 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006470 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006471 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006472 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006473
6474 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006475 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6476 BEnd = ClassDecl->vbases_end();
6477 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00006478 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6479 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006480 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6481 // If this is a deleted function, add it anyway. This might be conformant
6482 // with the standard. This might not. I'm not sure. It might not matter.
6483 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006484 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006485 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006486 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006487
6488 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006489 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6490 FEnd = ClassDecl->field_end();
6491 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00006492 if (F->hasInClassInitializer()) {
6493 if (Expr *E = F->getInClassInitializer())
6494 ExceptSpec.CalledExpr(E);
6495 else if (!F->isInvalidDecl())
6496 ExceptSpec.SetDelayed();
6497 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00006498 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00006499 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6500 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6501 // If this is a deleted function, add it anyway. This might be conformant
6502 // with the standard. This might not. I'm not sure. It might not matter.
6503 // In particular, the problem is that this function never gets called. It
6504 // might just be ill-formed because this function attempts to refer to
6505 // a deleted function here.
6506 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006507 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006508 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006509 }
John McCalldb40c7f2010-12-14 08:05:40 +00006510
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006511 return ExceptSpec;
6512}
6513
6514CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6515 CXXRecordDecl *ClassDecl) {
6516 // C++ [class.ctor]p5:
6517 // A default constructor for a class X is a constructor of class X
6518 // that can be called without an argument. If there is no
6519 // user-declared constructor for class X, a default constructor is
6520 // implicitly declared. An implicitly-declared default constructor
6521 // is an inline public member of its class.
6522 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6523 "Should not build implicit default constructor!");
6524
6525 ImplicitExceptionSpecification Spec =
6526 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6527 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00006528
Douglas Gregor6d880b12010-07-01 22:31:05 +00006529 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006530 CanQualType ClassType
6531 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006532 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006533 DeclarationName Name
6534 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006535 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006536 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00006537 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006538 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00006539 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006540 /*TInfo=*/0,
6541 /*isExplicit=*/false,
6542 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00006543 /*isImplicitlyDeclared=*/true,
6544 // FIXME: apply the rules for definitions here
6545 /*isConstexpr=*/false);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006546 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00006547 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006548 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00006549 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00006550
6551 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00006552 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6553
Douglas Gregor0be31a22010-07-02 17:43:08 +00006554 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00006555 PushOnScopeChains(DefaultCon, S, false);
6556 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00006557
6558 if (ShouldDeleteDefaultConstructor(DefaultCon))
6559 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00006560
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006561 return DefaultCon;
6562}
6563
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006564void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6565 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00006566 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006567 !Constructor->doesThisDeclarationHaveABody() &&
6568 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006569 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006570
Anders Carlsson423f5d82010-04-23 16:04:08 +00006571 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00006572 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00006573
Douglas Gregora57478e2010-05-01 15:04:51 +00006574 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006575 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00006576 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006577 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006578 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00006579 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00006580 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00006581 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00006582 }
Douglas Gregor73193272010-09-20 16:48:21 +00006583
6584 SourceLocation Loc = Constructor->getLocation();
6585 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6586
6587 Constructor->setUsed();
6588 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006589
6590 if (ASTMutationListener *L = getASTMutationListener()) {
6591 L->CompletedImplicitDefinition(Constructor);
6592 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006593}
6594
Richard Smith938f40b2011-06-11 17:19:42 +00006595/// Get any existing defaulted default constructor for the given class. Do not
6596/// implicitly define one if it does not exist.
6597static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6598 CXXRecordDecl *D) {
6599 ASTContext &Context = Self.Context;
6600 QualType ClassType = Context.getTypeDeclType(D);
6601 DeclarationName ConstructorName
6602 = Context.DeclarationNames.getCXXConstructorName(
6603 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6604
6605 DeclContext::lookup_const_iterator Con, ConEnd;
6606 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6607 Con != ConEnd; ++Con) {
6608 // A function template cannot be defaulted.
6609 if (isa<FunctionTemplateDecl>(*Con))
6610 continue;
6611
6612 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6613 if (Constructor->isDefaultConstructor())
6614 return Constructor->isDefaulted() ? Constructor : 0;
6615 }
6616 return 0;
6617}
6618
6619void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6620 if (!D) return;
6621 AdjustDeclIfTemplate(D);
6622
6623 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6624 CXXConstructorDecl *CtorDecl
6625 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6626
6627 if (!CtorDecl) return;
6628
6629 // Compute the exception specification for the default constructor.
6630 const FunctionProtoType *CtorTy =
6631 CtorDecl->getType()->castAs<FunctionProtoType>();
6632 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6633 ImplicitExceptionSpecification Spec =
6634 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6635 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6636 assert(EPI.ExceptionSpecType != EST_Delayed);
6637
6638 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6639 }
6640
6641 // If the default constructor is explicitly defaulted, checking the exception
6642 // specification is deferred until now.
6643 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6644 !ClassDecl->isDependentType())
6645 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6646}
6647
Sebastian Redl08905022011-02-05 19:23:19 +00006648void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6649 // We start with an initial pass over the base classes to collect those that
6650 // inherit constructors from. If there are none, we can forgo all further
6651 // processing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006652 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redl08905022011-02-05 19:23:19 +00006653 BasesVector BasesToInheritFrom;
6654 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6655 BaseE = ClassDecl->bases_end();
6656 BaseIt != BaseE; ++BaseIt) {
6657 if (BaseIt->getInheritConstructors()) {
6658 QualType Base = BaseIt->getType();
6659 if (Base->isDependentType()) {
6660 // If we inherit constructors from anything that is dependent, just
6661 // abort processing altogether. We'll get another chance for the
6662 // instantiations.
6663 return;
6664 }
6665 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6666 }
6667 }
6668 if (BasesToInheritFrom.empty())
6669 return;
6670
6671 // Now collect the constructors that we already have in the current class.
6672 // Those take precedence over inherited constructors.
6673 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6674 // unless there is a user-declared constructor with the same signature in
6675 // the class where the using-declaration appears.
6676 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6677 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6678 CtorE = ClassDecl->ctor_end();
6679 CtorIt != CtorE; ++CtorIt) {
6680 ExistingConstructors.insert(
6681 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6682 }
6683
6684 Scope *S = getScopeForContext(ClassDecl);
6685 DeclarationName CreatedCtorName =
6686 Context.DeclarationNames.getCXXConstructorName(
6687 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6688
6689 // Now comes the true work.
6690 // First, we keep a map from constructor types to the base that introduced
6691 // them. Needed for finding conflicting constructors. We also keep the
6692 // actually inserted declarations in there, for pretty diagnostics.
6693 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6694 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6695 ConstructorToSourceMap InheritedConstructors;
6696 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6697 BaseE = BasesToInheritFrom.end();
6698 BaseIt != BaseE; ++BaseIt) {
6699 const RecordType *Base = *BaseIt;
6700 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6701 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6702 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6703 CtorE = BaseDecl->ctor_end();
6704 CtorIt != CtorE; ++CtorIt) {
6705 // Find the using declaration for inheriting this base's constructors.
6706 DeclarationName Name =
6707 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6708 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6709 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6710 SourceLocation UsingLoc = UD ? UD->getLocation() :
6711 ClassDecl->getLocation();
6712
6713 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6714 // from the class X named in the using-declaration consists of actual
6715 // constructors and notional constructors that result from the
6716 // transformation of defaulted parameters as follows:
6717 // - all non-template default constructors of X, and
6718 // - for each non-template constructor of X that has at least one
6719 // parameter with a default argument, the set of constructors that
6720 // results from omitting any ellipsis parameter specification and
6721 // successively omitting parameters with a default argument from the
6722 // end of the parameter-type-list.
6723 CXXConstructorDecl *BaseCtor = *CtorIt;
6724 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6725 const FunctionProtoType *BaseCtorType =
6726 BaseCtor->getType()->getAs<FunctionProtoType>();
6727
6728 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6729 maxParams = BaseCtor->getNumParams();
6730 params <= maxParams; ++params) {
6731 // Skip default constructors. They're never inherited.
6732 if (params == 0)
6733 continue;
6734 // Skip copy and move constructors for the same reason.
6735 if (CanBeCopyOrMove && params == 1)
6736 continue;
6737
6738 // Build up a function type for this particular constructor.
6739 // FIXME: The working paper does not consider that the exception spec
6740 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00006741 // source. This code doesn't yet, either. When it does, this code will
6742 // need to be delayed until after exception specifications and in-class
6743 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00006744 const Type *NewCtorType;
6745 if (params == maxParams)
6746 NewCtorType = BaseCtorType;
6747 else {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006748 SmallVector<QualType, 16> Args;
Sebastian Redl08905022011-02-05 19:23:19 +00006749 for (unsigned i = 0; i < params; ++i) {
6750 Args.push_back(BaseCtorType->getArgType(i));
6751 }
6752 FunctionProtoType::ExtProtoInfo ExtInfo =
6753 BaseCtorType->getExtProtoInfo();
6754 ExtInfo.Variadic = false;
6755 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6756 Args.data(), params, ExtInfo)
6757 .getTypePtr();
6758 }
6759 const Type *CanonicalNewCtorType =
6760 Context.getCanonicalType(NewCtorType);
6761
6762 // Now that we have the type, first check if the class already has a
6763 // constructor with this signature.
6764 if (ExistingConstructors.count(CanonicalNewCtorType))
6765 continue;
6766
6767 // Then we check if we have already declared an inherited constructor
6768 // with this signature.
6769 std::pair<ConstructorToSourceMap::iterator, bool> result =
6770 InheritedConstructors.insert(std::make_pair(
6771 CanonicalNewCtorType,
6772 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6773 if (!result.second) {
6774 // Already in the map. If it came from a different class, that's an
6775 // error. Not if it's from the same.
6776 CanQualType PreviousBase = result.first->second.first;
6777 if (CanonicalBase != PreviousBase) {
6778 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6779 const CXXConstructorDecl *PrevBaseCtor =
6780 PrevCtor->getInheritedConstructor();
6781 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6782
6783 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6784 Diag(BaseCtor->getLocation(),
6785 diag::note_using_decl_constructor_conflict_current_ctor);
6786 Diag(PrevBaseCtor->getLocation(),
6787 diag::note_using_decl_constructor_conflict_previous_ctor);
6788 Diag(PrevCtor->getLocation(),
6789 diag::note_using_decl_constructor_conflict_previous_using);
6790 }
6791 continue;
6792 }
6793
6794 // OK, we're there, now add the constructor.
6795 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smitha77a0a62011-08-15 21:04:07 +00006796 // user-written inline constructor [...]
Sebastian Redl08905022011-02-05 19:23:19 +00006797 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6798 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00006799 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6800 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00006801 /*ImplicitlyDeclared=*/true,
6802 // FIXME: Due to a defect in the standard, we treat inherited
6803 // constructors as constexpr even if that makes them ill-formed.
6804 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redl08905022011-02-05 19:23:19 +00006805 NewCtor->setAccess(BaseCtor->getAccess());
6806
6807 // Build up the parameter decls and add them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006808 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redl08905022011-02-05 19:23:19 +00006809 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006810 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6811 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00006812 /*IdentifierInfo=*/0,
6813 BaseCtorType->getArgType(i),
6814 /*TInfo=*/0, SC_None,
6815 SC_None, /*DefaultArg=*/0));
6816 }
6817 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6818 NewCtor->setInheritedConstructor(BaseCtor);
6819
6820 PushOnScopeChains(NewCtor, S, false);
6821 ClassDecl->addDecl(NewCtor);
6822 result.first->second.second = NewCtor;
6823 }
6824 }
6825 }
6826}
6827
Alexis Huntf91729462011-05-12 22:46:25 +00006828Sema::ImplicitExceptionSpecification
6829Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00006830 // C++ [except.spec]p14:
6831 // An implicitly declared special member function (Clause 12) shall have
6832 // an exception-specification.
6833 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006834 if (ClassDecl->isInvalidDecl())
6835 return ExceptSpec;
6836
Douglas Gregorf1203042010-07-01 19:09:28 +00006837 // Direct base-class destructors.
6838 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6839 BEnd = ClassDecl->bases_end();
6840 B != BEnd; ++B) {
6841 if (B->isVirtual()) // Handled below.
6842 continue;
6843
6844 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6845 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006846 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006847 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006848
Douglas Gregorf1203042010-07-01 19:09:28 +00006849 // Virtual base-class destructors.
6850 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6851 BEnd = ClassDecl->vbases_end();
6852 B != BEnd; ++B) {
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 // Field destructors.
6859 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6860 FEnd = ClassDecl->field_end();
6861 F != FEnd; ++F) {
6862 if (const RecordType *RecordTy
6863 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6864 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006865 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006866 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006867
Alexis Huntf91729462011-05-12 22:46:25 +00006868 return ExceptSpec;
6869}
6870
6871CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6872 // C++ [class.dtor]p2:
6873 // If a class has no user-declared destructor, a destructor is
6874 // declared implicitly. An implicitly-declared destructor is an
6875 // inline public member of its class.
6876
6877 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00006878 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00006879 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6880
Douglas Gregor7454c562010-07-02 20:37:36 +00006881 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00006882 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006883
Douglas Gregorf1203042010-07-01 19:09:28 +00006884 CanQualType ClassType
6885 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006886 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00006887 DeclarationName Name
6888 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006889 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00006890 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006891 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6892 /*isInline=*/true,
6893 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00006894 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00006895 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00006896 Destructor->setImplicit();
6897 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00006898
6899 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00006900 ++ASTContext::NumImplicitDestructorsDeclared;
6901
6902 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006903 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00006904 PushOnScopeChains(Destructor, S, false);
6905 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00006906
6907 // This could be uniqued if it ever proves significant.
6908 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00006909
6910 if (ShouldDeleteDestructor(Destructor))
6911 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00006912
6913 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00006914
Douglas Gregorf1203042010-07-01 19:09:28 +00006915 return Destructor;
6916}
6917
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006918void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00006919 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006920 assert((Destructor->isDefaulted() &&
6921 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006922 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00006923 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006924 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006925
Douglas Gregor54818f02010-05-12 16:39:35 +00006926 if (Destructor->isInvalidDecl())
6927 return;
6928
Douglas Gregora57478e2010-05-01 15:04:51 +00006929 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006930
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006931 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00006932 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6933 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00006934
Douglas Gregor54818f02010-05-12 16:39:35 +00006935 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006936 Diag(CurrentLocation, diag::note_member_synthesized_at)
6937 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6938
6939 Destructor->setInvalidDecl();
6940 return;
6941 }
6942
Douglas Gregor73193272010-09-20 16:48:21 +00006943 SourceLocation Loc = Destructor->getLocation();
6944 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6945
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006946 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006947 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006948
6949 if (ASTMutationListener *L = getASTMutationListener()) {
6950 L->CompletedImplicitDefinition(Destructor);
6951 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006952}
6953
Sebastian Redl623ea822011-05-19 05:13:44 +00006954void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6955 CXXDestructorDecl *destructor) {
6956 // C++11 [class.dtor]p3:
6957 // A declaration of a destructor that does not have an exception-
6958 // specification is implicitly considered to have the same exception-
6959 // specification as an implicit declaration.
6960 const FunctionProtoType *dtorType = destructor->getType()->
6961 getAs<FunctionProtoType>();
6962 if (dtorType->hasExceptionSpec())
6963 return;
6964
6965 ImplicitExceptionSpecification exceptSpec =
6966 ComputeDefaultedDtorExceptionSpec(classDecl);
6967
6968 // Replace the destructor's type.
6969 FunctionProtoType::ExtProtoInfo epi;
6970 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6971 epi.NumExceptions = exceptSpec.size();
6972 epi.Exceptions = exceptSpec.data();
6973 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6974
6975 destructor->setType(ty);
6976
6977 // FIXME: If the destructor has a body that could throw, and the newly created
6978 // spec doesn't allow exceptions, we should emit a warning, because this
6979 // change in behavior can break conforming C++03 programs at runtime.
6980 // However, we don't have a body yet, so it needs to be done somewhere else.
6981}
6982
Sebastian Redl22653ba2011-08-30 19:58:05 +00006983/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00006984/// \c To.
6985///
Sebastian Redl22653ba2011-08-30 19:58:05 +00006986/// This routine is used to copy/move the members of a class with an
6987/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00006988/// copied are arrays, this routine builds for loops to copy them.
6989///
6990/// \param S The Sema object used for type-checking.
6991///
Sebastian Redl22653ba2011-08-30 19:58:05 +00006992/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00006993///
Sebastian Redl22653ba2011-08-30 19:58:05 +00006994/// \param T The type of the expressions being copied/moved. Both expressions
6995/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00006996///
Sebastian Redl22653ba2011-08-30 19:58:05 +00006997/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00006998///
Sebastian Redl22653ba2011-08-30 19:58:05 +00006999/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007000///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007001/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007002/// Otherwise, it's a non-static member subobject.
7003///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007004/// \param Copying Whether we're copying or moving.
7005///
Douglas Gregorb139cd52010-05-01 20:49:11 +00007006/// \param Depth Internal parameter recording the depth of the recursion.
7007///
7008/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00007009static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00007010BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00007011 Expr *To, Expr *From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007012 bool CopyingBaseSubobject, bool Copying,
7013 unsigned Depth = 0) {
7014 // C++0x [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00007015 // Each subobject is assigned in the manner appropriate to its type:
7016 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00007017 // - if the subobject is of class type, as if by a call to operator= with
7018 // the subobject as the object expression and the corresponding
7019 // subobject of x as a single function argument (as if by explicit
7020 // qualification; that is, ignoring any possible virtual overriding
7021 // functions in more derived classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007022 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7023 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7024
7025 // Look for operator=.
7026 DeclarationName Name
7027 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7028 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7029 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7030
Sebastian Redl22653ba2011-08-30 19:58:05 +00007031 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007032 LookupResult::Filter F = OpLookup.makeFilter();
7033 while (F.hasNext()) {
7034 NamedDecl *D = F.next();
7035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl22653ba2011-08-30 19:58:05 +00007036 if (Copying ? Method->isCopyAssignmentOperator() :
7037 Method->isMoveAssignmentOperator())
Douglas Gregorb139cd52010-05-01 20:49:11 +00007038 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00007039
Douglas Gregorb139cd52010-05-01 20:49:11 +00007040 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00007041 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007042 F.done();
7043
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007044 // Suppress the protected check (C++ [class.protected]) for each of the
7045 // assignment operators we found. This strange dance is required when
7046 // we're assigning via a base classes's copy-assignment operator. To
7047 // ensure that we're getting the right base class subobject (without
7048 // ambiguities), we need to cast "this" to that subobject type; to
7049 // ensure that we don't go through the virtual call mechanism, we need
7050 // to qualify the operator= name with the base class (see below). However,
7051 // this means that if the base class has a protected copy assignment
7052 // operator, the protected member access check will fail. So, we
7053 // rewrite "protected" access to "public" access in this case, since we
7054 // know by construction that we're calling from a derived class.
7055 if (CopyingBaseSubobject) {
7056 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7057 L != LEnd; ++L) {
7058 if (L.getAccess() == AS_protected)
7059 L.setAccess(AS_public);
7060 }
7061 }
7062
Douglas Gregorb139cd52010-05-01 20:49:11 +00007063 // Create the nested-name-specifier that will be used to qualify the
7064 // reference to operator=; this is required to suppress the virtual
7065 // call mechanism.
7066 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00007067 SS.MakeTrivial(S.Context,
7068 NestedNameSpecifier::Create(S.Context, 0, false,
7069 T.getTypePtr()),
7070 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007071
7072 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00007073 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00007074 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007075 /*FirstQualifierInScope=*/0, OpLookup,
7076 /*TemplateArgs=*/0,
7077 /*SuppressQualifierCheck=*/true);
7078 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007079 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007080
7081 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00007082
John McCalldadc5752010-08-24 06:29:42 +00007083 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007084 OpEqualRef.takeAs<Expr>(),
7085 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007086 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007087 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007088
7089 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007090 }
John McCallab8c2732010-03-16 06:11:48 +00007091
Douglas Gregorb139cd52010-05-01 20:49:11 +00007092 // - if the subobject is of scalar type, the built-in assignment
7093 // operator is used.
7094 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7095 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00007096 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007097 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007098 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007099
7100 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007101 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007102
7103 // - if the subobject is an array, each element is assigned, in the
7104 // manner appropriate to the element type;
7105
7106 // Construct a loop over the array bounds, e.g.,
7107 //
7108 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7109 //
7110 // that will copy each of the array elements.
7111 QualType SizeType = S.Context.getSizeType();
7112
7113 // Create the iteration variable.
7114 IdentifierInfo *IterationVarName = 0;
7115 {
7116 llvm::SmallString<8> Str;
7117 llvm::raw_svector_ostream OS(Str);
7118 OS << "__i" << Depth;
7119 IterationVarName = &S.Context.Idents.get(OS.str());
7120 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00007121 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007122 IterationVarName, SizeType,
7123 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007124 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007125
7126 // Initialize the iteration variable to zero.
7127 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007128 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00007129
7130 // Create a reference to the iteration variable; we'll use this several
7131 // times throughout.
7132 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00007133 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007134 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7135
7136 // Create the DeclStmt that holds the iteration variable.
7137 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7138
7139 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007140 llvm::APInt Upper
7141 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00007142 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00007143 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00007144 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7145 BO_NE, S.Context.BoolTy,
7146 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007147
7148 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007149 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00007150 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7151 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007152
7153 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007154 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7155 IterationVarRef, Loc));
7156 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7157 IterationVarRef, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00007158 if (!Copying) // Cast to rvalue
7159 From = CastForMoving(S, From);
7160
7161 // Build the copy/move for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00007162 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7163 To, From, CopyingBaseSubobject,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007164 Copying, Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00007165 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007166 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007167
7168 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00007169 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007170 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00007171 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00007172 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007173}
7174
Alexis Hunt119f3652011-05-14 05:23:20 +00007175std::pair<Sema::ImplicitExceptionSpecification, bool>
7176Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7177 CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007178 if (ClassDecl->isInvalidDecl())
7179 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7180
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007181 // C++ [class.copy]p10:
7182 // If the class definition does not explicitly declare a copy
7183 // assignment operator, one is declared implicitly.
7184 // The implicitly-defined copy assignment operator for a class X
7185 // will have the form
7186 //
7187 // X& X::operator=(const X&)
7188 //
7189 // if
7190 bool HasConstCopyAssignment = true;
7191
7192 // -- each direct base class B of X has a copy assignment operator
7193 // whose parameter is of type const B&, const volatile B& or B,
7194 // and
7195 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7196 BaseEnd = ClassDecl->bases_end();
7197 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007198 // We'll handle this below
7199 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7200 continue;
7201
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007202 assert(!Base->getType()->isDependentType() &&
7203 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00007204 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7205 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7206 &HasConstCopyAssignment);
7207 }
7208
7209 // In C++0x, the above citation has "or virtual added"
7210 if (LangOpts.CPlusPlus0x) {
7211 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7212 BaseEnd = ClassDecl->vbases_end();
7213 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7214 assert(!Base->getType()->isDependentType() &&
7215 "Cannot generate implicit members for class with dependent bases.");
7216 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7217 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7218 &HasConstCopyAssignment);
7219 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007220 }
7221
7222 // -- for all the nonstatic data members of X that are of a class
7223 // type M (or array thereof), each such class type has a copy
7224 // assignment operator whose parameter is of type const M&,
7225 // const volatile M& or M.
7226 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7227 FieldEnd = ClassDecl->field_end();
7228 HasConstCopyAssignment && Field != FieldEnd;
7229 ++Field) {
7230 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007231 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7232 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7233 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007234 }
7235 }
7236
7237 // Otherwise, the implicitly declared copy assignment operator will
7238 // have the form
7239 //
7240 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007241
Douglas Gregor68e11362010-07-01 17:48:08 +00007242 // C++ [except.spec]p14:
7243 // An implicitly declared special member function (Clause 12) shall have an
7244 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00007245
7246 // It is unspecified whether or not an implicit copy assignment operator
7247 // attempts to deduplicate calls to assignment operators of virtual bases are
7248 // made. As such, this exception specification is effectively unspecified.
7249 // Based on a similar decision made for constness in C++0x, we're erring on
7250 // the side of assuming such calls to be made regardless of whether they
7251 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00007252 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00007253 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00007254 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7255 BaseEnd = ClassDecl->bases_end();
7256 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007257 if (Base->isVirtual())
7258 continue;
7259
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007260 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00007261 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007262 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7263 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00007264 ExceptSpec.CalledDecl(CopyAssign);
7265 }
Alexis Hunt491ec602011-06-21 23:42:56 +00007266
7267 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7268 BaseEnd = ClassDecl->vbases_end();
7269 Base != BaseEnd; ++Base) {
7270 CXXRecordDecl *BaseClassDecl
7271 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7272 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7273 ArgQuals, false, 0))
7274 ExceptSpec.CalledDecl(CopyAssign);
7275 }
7276
Douglas Gregor68e11362010-07-01 17:48:08 +00007277 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7278 FieldEnd = ClassDecl->field_end();
7279 Field != FieldEnd;
7280 ++Field) {
7281 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007282 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7283 if (CXXMethodDecl *CopyAssign =
7284 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7285 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007286 }
Douglas Gregor68e11362010-07-01 17:48:08 +00007287 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007288
Alexis Hunt119f3652011-05-14 05:23:20 +00007289 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7290}
7291
7292CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7293 // Note: The following rules are largely analoguous to the copy
7294 // constructor rules. Note that virtual bases are not taken into account
7295 // for determining the argument type of the operator. Note also that
7296 // operators taking an object instead of a reference are allowed.
7297
7298 ImplicitExceptionSpecification Spec(Context);
7299 bool Const;
7300 llvm::tie(Spec, Const) =
7301 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7302
7303 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7304 QualType RetType = Context.getLValueReferenceType(ArgType);
7305 if (Const)
7306 ArgType = ArgType.withConst();
7307 ArgType = Context.getLValueReferenceType(ArgType);
7308
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007309 // An implicitly-declared copy assignment operator is an inline public
7310 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00007311 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007312 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007313 SourceLocation ClassLoc = ClassDecl->getLocation();
7314 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007315 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00007316 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00007317 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007318 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00007319 /*StorageClassAsWritten=*/SC_None,
Richard Smitha77a0a62011-08-15 21:04:07 +00007320 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf2f08062011-03-08 17:10:18 +00007321 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007322 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00007323 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007324 CopyAssignment->setImplicit();
7325 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007326
7327 // Add the parameter to the operator.
7328 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007329 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007330 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007331 SC_None,
7332 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007333 CopyAssignment->setParams(&FromParam, 1);
7334
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007335 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007336 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00007337
Douglas Gregor0be31a22010-07-02 17:43:08 +00007338 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007339 PushOnScopeChains(CopyAssignment, S, false);
7340 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007341
Alexis Huntd74c85f2011-06-22 01:05:13 +00007342 // C++0x [class.copy]p18:
7343 // ... If the class definition declares a move constructor or move
7344 // assignment operator, the implicitly declared copy assignment operator is
7345 // defined as deleted; ...
7346 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7347 ClassDecl->hasUserDeclaredMoveAssignment() ||
7348 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007349 CopyAssignment->setDeletedAsWritten();
7350
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007351 AddOverriddenMethods(ClassDecl, CopyAssignment);
7352 return CopyAssignment;
7353}
7354
Douglas Gregorb139cd52010-05-01 20:49:11 +00007355void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7356 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00007357 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007358 CopyAssignOperator->isOverloadedOperator() &&
7359 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007360 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007361 "DefineImplicitCopyAssignment called for wrong function");
7362
7363 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7364
7365 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7366 CopyAssignOperator->setInvalidDecl();
7367 return;
7368 }
7369
7370 CopyAssignOperator->setUsed();
7371
7372 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007373 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007374
7375 // C++0x [class.copy]p30:
7376 // The implicitly-defined or explicitly-defaulted copy assignment operator
7377 // for a non-union class X performs memberwise copy assignment of its
7378 // subobjects. The direct base classes of X are assigned first, in the
7379 // order of their declaration in the base-specifier-list, and then the
7380 // immediate non-static data members of X are assigned, in the order in
7381 // which they were declared in the class definition.
7382
7383 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00007384 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007385
7386 // The parameter for the "other" object, which we are copying from.
7387 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7388 Qualifiers OtherQuals = Other->getType().getQualifiers();
7389 QualType OtherRefType = Other->getType();
7390 if (const LValueReferenceType *OtherRef
7391 = OtherRefType->getAs<LValueReferenceType>()) {
7392 OtherRefType = OtherRef->getPointeeType();
7393 OtherQuals = OtherRefType.getQualifiers();
7394 }
7395
7396 // Our location for everything implicitly-generated.
7397 SourceLocation Loc = CopyAssignOperator->getLocation();
7398
7399 // Construct a reference to the "other" object. We'll be using this
7400 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00007401 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007402 assert(OtherRef && "Reference to parameter cannot fail!");
7403
7404 // Construct the "this" pointer. We'll be using this throughout the generated
7405 // ASTs.
7406 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7407 assert(This && "Reference to this cannot fail!");
7408
7409 // Assign base classes.
7410 bool Invalid = false;
7411 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7412 E = ClassDecl->bases_end(); Base != E; ++Base) {
7413 // Form the assignment:
7414 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7415 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00007416 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007417 Invalid = true;
7418 continue;
7419 }
7420
John McCallcf142162010-08-07 06:22:56 +00007421 CXXCastPath BasePath;
7422 BasePath.push_back(Base);
7423
Douglas Gregorb139cd52010-05-01 20:49:11 +00007424 // Construct the "from" expression, which is an implicit cast to the
7425 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00007426 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00007427 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7428 CK_UncheckedDerivedToBase,
7429 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007430
7431 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00007432 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007433
7434 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00007435 To = ImpCastExprToType(To.take(),
7436 Context.getCVRQualifiedType(BaseType,
7437 CopyAssignOperator->getTypeQualifiers()),
7438 CK_UncheckedDerivedToBase,
7439 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007440
7441 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00007442 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00007443 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007444 /*CopyingBaseSubobject=*/true,
7445 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007446 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007447 Diag(CurrentLocation, diag::note_member_synthesized_at)
7448 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7449 CopyAssignOperator->setInvalidDecl();
7450 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007451 }
7452
7453 // Success! Record the copy.
7454 Statements.push_back(Copy.takeAs<Expr>());
7455 }
7456
7457 // \brief Reference to the __builtin_memcpy function.
7458 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007459 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007460 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007461
7462 // Assign non-static members.
7463 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7464 FieldEnd = ClassDecl->field_end();
7465 Field != FieldEnd; ++Field) {
7466 // Check for members of reference type; we can't copy those.
7467 if (Field->getType()->isReferenceType()) {
7468 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7469 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7470 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007471 Diag(CurrentLocation, diag::note_member_synthesized_at)
7472 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007473 Invalid = true;
7474 continue;
7475 }
7476
7477 // Check for members of const-qualified, non-class type.
7478 QualType BaseType = Context.getBaseElementType(Field->getType());
7479 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7480 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7481 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7482 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007483 Diag(CurrentLocation, diag::note_member_synthesized_at)
7484 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007485 Invalid = true;
7486 continue;
7487 }
John McCall1b1a1db2011-06-17 00:18:42 +00007488
7489 // Suppress assigning zero-width bitfields.
7490 if (const Expr *Width = Field->getBitWidth())
7491 if (Width->EvaluateAsInt(Context) == 0)
7492 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007493
7494 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007495 if (FieldType->isIncompleteArrayType()) {
7496 assert(ClassDecl->hasFlexibleArrayMember() &&
7497 "Incomplete array type is not valid");
7498 continue;
7499 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007500
7501 // Build references to the field in the object we're copying from and to.
7502 CXXScopeSpec SS; // Intentionally empty
7503 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7504 LookupMemberName);
7505 MemberLookup.addDecl(*Field);
7506 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00007507 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00007508 Loc, /*IsArrow=*/false,
7509 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00007510 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00007511 Loc, /*IsArrow=*/true,
7512 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007513 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7514 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7515
7516 // If the field should be copied with __builtin_memcpy rather than via
7517 // explicit assignments, do so. This optimization only applies for arrays
7518 // of scalars and arrays of class type with trivial copy-assignment
7519 // operators.
Fariborz Jahanianc1a151b2011-08-09 00:26:11 +00007520 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl22653ba2011-08-30 19:58:05 +00007521 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007522 // Compute the size of the memory buffer to be copied.
7523 QualType SizeType = Context.getSizeType();
7524 llvm::APInt Size(Context.getTypeSize(SizeType),
7525 Context.getTypeSizeInChars(BaseType).getQuantity());
7526 for (const ConstantArrayType *Array
7527 = Context.getAsConstantArrayType(FieldType);
7528 Array;
7529 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00007530 llvm::APInt ArraySize
7531 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007532 Size *= ArraySize;
7533 }
7534
7535 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00007536 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7537 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007538
7539 bool NeedsCollectableMemCpy =
7540 (BaseType->isRecordType() &&
7541 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7542
7543 if (NeedsCollectableMemCpy) {
7544 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007545 // Create a reference to the __builtin_objc_memmove_collectable function.
7546 LookupResult R(*this,
7547 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007548 Loc, LookupOrdinaryName);
7549 LookupName(R, TUScope, true);
7550
7551 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7552 if (!CollectableMemCpy) {
7553 // Something went horribly wrong earlier, and we will have
7554 // complained about it.
7555 Invalid = true;
7556 continue;
7557 }
7558
7559 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7560 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007561 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007562 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7563 }
7564 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007565 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007566 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007567 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7568 LookupOrdinaryName);
7569 LookupName(R, TUScope, true);
7570
7571 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7572 if (!BuiltinMemCpy) {
7573 // Something went horribly wrong earlier, and we will have complained
7574 // about it.
7575 Invalid = true;
7576 continue;
7577 }
7578
7579 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7580 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007581 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007582 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7583 }
7584
John McCall37ad5512010-08-23 06:44:23 +00007585 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007586 CallArgs.push_back(To.takeAs<Expr>());
7587 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007588 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00007589 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007590 if (NeedsCollectableMemCpy)
7591 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007592 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007593 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007594 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007595 else
7596 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007597 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007598 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007599 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007600
Douglas Gregorb139cd52010-05-01 20:49:11 +00007601 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7602 Statements.push_back(Call.takeAs<Expr>());
7603 continue;
7604 }
7605
7606 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00007607 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007608 To.get(), From.get(),
7609 /*CopyingBaseSubobject=*/false,
7610 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007611 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007612 Diag(CurrentLocation, diag::note_member_synthesized_at)
7613 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7614 CopyAssignOperator->setInvalidDecl();
7615 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007616 }
7617
7618 // Success! Record the copy.
7619 Statements.push_back(Copy.takeAs<Stmt>());
7620 }
7621
7622 if (!Invalid) {
7623 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00007624 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007625
John McCalldadc5752010-08-24 06:29:42 +00007626 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007627 if (Return.isInvalid())
7628 Invalid = true;
7629 else {
7630 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00007631
7632 if (Trap.hasErrorOccurred()) {
7633 Diag(CurrentLocation, diag::note_member_synthesized_at)
7634 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7635 Invalid = true;
7636 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007637 }
7638 }
7639
7640 if (Invalid) {
7641 CopyAssignOperator->setInvalidDecl();
7642 return;
7643 }
7644
John McCalldadc5752010-08-24 06:29:42 +00007645 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00007646 /*isStmtExpr=*/false);
7647 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7648 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00007649
7650 if (ASTMutationListener *L = getASTMutationListener()) {
7651 L->CompletedImplicitDefinition(CopyAssignOperator);
7652 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007653}
7654
Sebastian Redl22653ba2011-08-30 19:58:05 +00007655Sema::ImplicitExceptionSpecification
7656Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7657 ImplicitExceptionSpecification ExceptSpec(Context);
7658
7659 if (ClassDecl->isInvalidDecl())
7660 return ExceptSpec;
7661
7662 // C++0x [except.spec]p14:
7663 // An implicitly declared special member function (Clause 12) shall have an
7664 // exception-specification. [...]
7665
7666 // It is unspecified whether or not an implicit move assignment operator
7667 // attempts to deduplicate calls to assignment operators of virtual bases are
7668 // made. As such, this exception specification is effectively unspecified.
7669 // Based on a similar decision made for constness in C++0x, we're erring on
7670 // the side of assuming such calls to be made regardless of whether they
7671 // actually happen.
7672 // Note that a move constructor is not implicitly declared when there are
7673 // virtual bases, but it can still be user-declared and explicitly defaulted.
7674 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7675 BaseEnd = ClassDecl->bases_end();
7676 Base != BaseEnd; ++Base) {
7677 if (Base->isVirtual())
7678 continue;
7679
7680 CXXRecordDecl *BaseClassDecl
7681 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7682 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7683 false, 0))
7684 ExceptSpec.CalledDecl(MoveAssign);
7685 }
7686
7687 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7688 BaseEnd = ClassDecl->vbases_end();
7689 Base != BaseEnd; ++Base) {
7690 CXXRecordDecl *BaseClassDecl
7691 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7692 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7693 false, 0))
7694 ExceptSpec.CalledDecl(MoveAssign);
7695 }
7696
7697 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7698 FieldEnd = ClassDecl->field_end();
7699 Field != FieldEnd;
7700 ++Field) {
7701 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7702 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7703 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7704 false, 0))
7705 ExceptSpec.CalledDecl(MoveAssign);
7706 }
7707 }
7708
7709 return ExceptSpec;
7710}
7711
7712CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7713 // Note: The following rules are largely analoguous to the move
7714 // constructor rules.
7715
7716 ImplicitExceptionSpecification Spec(
7717 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7718
7719 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7720 QualType RetType = Context.getLValueReferenceType(ArgType);
7721 ArgType = Context.getRValueReferenceType(ArgType);
7722
7723 // An implicitly-declared move assignment operator is an inline public
7724 // member of its class.
7725 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7726 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7727 SourceLocation ClassLoc = ClassDecl->getLocation();
7728 DeclarationNameInfo NameInfo(Name, ClassLoc);
7729 CXXMethodDecl *MoveAssignment
7730 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7731 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7732 /*TInfo=*/0, /*isStatic=*/false,
7733 /*StorageClassAsWritten=*/SC_None,
7734 /*isInline=*/true,
7735 /*isConstexpr=*/false,
7736 SourceLocation());
7737 MoveAssignment->setAccess(AS_public);
7738 MoveAssignment->setDefaulted();
7739 MoveAssignment->setImplicit();
7740 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7741
7742 // Add the parameter to the operator.
7743 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7744 ClassLoc, ClassLoc, /*Id=*/0,
7745 ArgType, /*TInfo=*/0,
7746 SC_None,
7747 SC_None, 0);
7748 MoveAssignment->setParams(&FromParam, 1);
7749
7750 // Note that we have added this copy-assignment operator.
7751 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7752
7753 // C++0x [class.copy]p9:
7754 // If the definition of a class X does not explicitly declare a move
7755 // assignment operator, one will be implicitly declared as defaulted if and
7756 // only if:
7757 // [...]
7758 // - the move assignment operator would not be implicitly defined as
7759 // deleted.
7760 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7761 // Cache this result so that we don't try to generate this over and over
7762 // on every lookup, leaking memory and wasting time.
7763 ClassDecl->setFailedImplicitMoveAssignment();
7764 return 0;
7765 }
7766
7767 if (Scope *S = getScopeForContext(ClassDecl))
7768 PushOnScopeChains(MoveAssignment, S, false);
7769 ClassDecl->addDecl(MoveAssignment);
7770
7771 AddOverriddenMethods(ClassDecl, MoveAssignment);
7772 return MoveAssignment;
7773}
7774
7775void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7776 CXXMethodDecl *MoveAssignOperator) {
7777 assert((MoveAssignOperator->isDefaulted() &&
7778 MoveAssignOperator->isOverloadedOperator() &&
7779 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7780 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7781 "DefineImplicitMoveAssignment called for wrong function");
7782
7783 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7784
7785 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7786 MoveAssignOperator->setInvalidDecl();
7787 return;
7788 }
7789
7790 MoveAssignOperator->setUsed();
7791
7792 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7793 DiagnosticErrorTrap Trap(Diags);
7794
7795 // C++0x [class.copy]p28:
7796 // The implicitly-defined or move assignment operator for a non-union class
7797 // X performs memberwise move assignment of its subobjects. The direct base
7798 // classes of X are assigned first, in the order of their declaration in the
7799 // base-specifier-list, and then the immediate non-static data members of X
7800 // are assigned, in the order in which they were declared in the class
7801 // definition.
7802
7803 // The statements that form the synthesized function body.
7804 ASTOwningVector<Stmt*> Statements(*this);
7805
7806 // The parameter for the "other" object, which we are move from.
7807 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7808 QualType OtherRefType = Other->getType()->
7809 getAs<RValueReferenceType>()->getPointeeType();
7810 assert(OtherRefType.getQualifiers() == 0 &&
7811 "Bad argument type of defaulted move assignment");
7812
7813 // Our location for everything implicitly-generated.
7814 SourceLocation Loc = MoveAssignOperator->getLocation();
7815
7816 // Construct a reference to the "other" object. We'll be using this
7817 // throughout the generated ASTs.
7818 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7819 assert(OtherRef && "Reference to parameter cannot fail!");
7820 // Cast to rvalue.
7821 OtherRef = CastForMoving(*this, OtherRef);
7822
7823 // Construct the "this" pointer. We'll be using this throughout the generated
7824 // ASTs.
7825 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7826 assert(This && "Reference to this cannot fail!");
7827
7828 // Assign base classes.
7829 bool Invalid = false;
7830 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7831 E = ClassDecl->bases_end(); Base != E; ++Base) {
7832 // Form the assignment:
7833 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7834 QualType BaseType = Base->getType().getUnqualifiedType();
7835 if (!BaseType->isRecordType()) {
7836 Invalid = true;
7837 continue;
7838 }
7839
7840 CXXCastPath BasePath;
7841 BasePath.push_back(Base);
7842
7843 // Construct the "from" expression, which is an implicit cast to the
7844 // appropriately-qualified base type.
7845 Expr *From = OtherRef;
7846 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00007847 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00007848
7849 // Dereference "this".
7850 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7851
7852 // Implicitly cast "this" to the appropriately-qualified base type.
7853 To = ImpCastExprToType(To.take(),
7854 Context.getCVRQualifiedType(BaseType,
7855 MoveAssignOperator->getTypeQualifiers()),
7856 CK_UncheckedDerivedToBase,
7857 VK_LValue, &BasePath);
7858
7859 // Build the move.
7860 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7861 To.get(), From,
7862 /*CopyingBaseSubobject=*/true,
7863 /*Copying=*/false);
7864 if (Move.isInvalid()) {
7865 Diag(CurrentLocation, diag::note_member_synthesized_at)
7866 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7867 MoveAssignOperator->setInvalidDecl();
7868 return;
7869 }
7870
7871 // Success! Record the move.
7872 Statements.push_back(Move.takeAs<Expr>());
7873 }
7874
7875 // \brief Reference to the __builtin_memcpy function.
7876 Expr *BuiltinMemCpyRef = 0;
7877 // \brief Reference to the __builtin_objc_memmove_collectable function.
7878 Expr *CollectableMemCpyRef = 0;
7879
7880 // Assign non-static members.
7881 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7882 FieldEnd = ClassDecl->field_end();
7883 Field != FieldEnd; ++Field) {
7884 // Check for members of reference type; we can't move those.
7885 if (Field->getType()->isReferenceType()) {
7886 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7887 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7888 Diag(Field->getLocation(), diag::note_declared_at);
7889 Diag(CurrentLocation, diag::note_member_synthesized_at)
7890 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7891 Invalid = true;
7892 continue;
7893 }
7894
7895 // Check for members of const-qualified, non-class type.
7896 QualType BaseType = Context.getBaseElementType(Field->getType());
7897 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7898 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7899 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7900 Diag(Field->getLocation(), diag::note_declared_at);
7901 Diag(CurrentLocation, diag::note_member_synthesized_at)
7902 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7903 Invalid = true;
7904 continue;
7905 }
7906
7907 // Suppress assigning zero-width bitfields.
7908 if (const Expr *Width = Field->getBitWidth())
7909 if (Width->EvaluateAsInt(Context) == 0)
7910 continue;
7911
7912 QualType FieldType = Field->getType().getNonReferenceType();
7913 if (FieldType->isIncompleteArrayType()) {
7914 assert(ClassDecl->hasFlexibleArrayMember() &&
7915 "Incomplete array type is not valid");
7916 continue;
7917 }
7918
7919 // Build references to the field in the object we're copying from and to.
7920 CXXScopeSpec SS; // Intentionally empty
7921 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7922 LookupMemberName);
7923 MemberLookup.addDecl(*Field);
7924 MemberLookup.resolveKind();
7925 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7926 Loc, /*IsArrow=*/false,
7927 SS, 0, MemberLookup, 0);
7928 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7929 Loc, /*IsArrow=*/true,
7930 SS, 0, MemberLookup, 0);
7931 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7932 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7933
7934 assert(!From.get()->isLValue() && // could be xvalue or prvalue
7935 "Member reference with rvalue base must be rvalue except for reference "
7936 "members, which aren't allowed for move assignment.");
7937
7938 // If the field should be copied with __builtin_memcpy rather than via
7939 // explicit assignments, do so. This optimization only applies for arrays
7940 // of scalars and arrays of class type with trivial move-assignment
7941 // operators.
7942 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7943 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7944 // Compute the size of the memory buffer to be copied.
7945 QualType SizeType = Context.getSizeType();
7946 llvm::APInt Size(Context.getTypeSize(SizeType),
7947 Context.getTypeSizeInChars(BaseType).getQuantity());
7948 for (const ConstantArrayType *Array
7949 = Context.getAsConstantArrayType(FieldType);
7950 Array;
7951 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7952 llvm::APInt ArraySize
7953 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7954 Size *= ArraySize;
7955 }
7956
Douglas Gregor528499b2011-09-01 02:09:07 +00007957 // Take the address of the field references for "from" and "to". We
7958 // directly construct UnaryOperators here because semantic analysis
7959 // does not permit us to take the address of an xvalue.
7960 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
7961 Context.getPointerType(From.get()->getType()),
7962 VK_RValue, OK_Ordinary, Loc);
7963 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
7964 Context.getPointerType(To.get()->getType()),
7965 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00007966
7967 bool NeedsCollectableMemCpy =
7968 (BaseType->isRecordType() &&
7969 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7970
7971 if (NeedsCollectableMemCpy) {
7972 if (!CollectableMemCpyRef) {
7973 // Create a reference to the __builtin_objc_memmove_collectable function.
7974 LookupResult R(*this,
7975 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7976 Loc, LookupOrdinaryName);
7977 LookupName(R, TUScope, true);
7978
7979 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7980 if (!CollectableMemCpy) {
7981 // Something went horribly wrong earlier, and we will have
7982 // complained about it.
7983 Invalid = true;
7984 continue;
7985 }
7986
7987 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7988 CollectableMemCpy->getType(),
7989 VK_LValue, Loc, 0).take();
7990 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7991 }
7992 }
7993 // Create a reference to the __builtin_memcpy builtin function.
7994 else if (!BuiltinMemCpyRef) {
7995 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7996 LookupOrdinaryName);
7997 LookupName(R, TUScope, true);
7998
7999 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8000 if (!BuiltinMemCpy) {
8001 // Something went horribly wrong earlier, and we will have complained
8002 // about it.
8003 Invalid = true;
8004 continue;
8005 }
8006
8007 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8008 BuiltinMemCpy->getType(),
8009 VK_LValue, Loc, 0).take();
8010 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8011 }
8012
8013 ASTOwningVector<Expr*> CallArgs(*this);
8014 CallArgs.push_back(To.takeAs<Expr>());
8015 CallArgs.push_back(From.takeAs<Expr>());
8016 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8017 ExprResult Call = ExprError();
8018 if (NeedsCollectableMemCpy)
8019 Call = ActOnCallExpr(/*Scope=*/0,
8020 CollectableMemCpyRef,
8021 Loc, move_arg(CallArgs),
8022 Loc);
8023 else
8024 Call = ActOnCallExpr(/*Scope=*/0,
8025 BuiltinMemCpyRef,
8026 Loc, move_arg(CallArgs),
8027 Loc);
8028
8029 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8030 Statements.push_back(Call.takeAs<Expr>());
8031 continue;
8032 }
8033
8034 // Build the move of this field.
8035 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8036 To.get(), From.get(),
8037 /*CopyingBaseSubobject=*/false,
8038 /*Copying=*/false);
8039 if (Move.isInvalid()) {
8040 Diag(CurrentLocation, diag::note_member_synthesized_at)
8041 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8042 MoveAssignOperator->setInvalidDecl();
8043 return;
8044 }
8045
8046 // Success! Record the copy.
8047 Statements.push_back(Move.takeAs<Stmt>());
8048 }
8049
8050 if (!Invalid) {
8051 // Add a "return *this;"
8052 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8053
8054 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8055 if (Return.isInvalid())
8056 Invalid = true;
8057 else {
8058 Statements.push_back(Return.takeAs<Stmt>());
8059
8060 if (Trap.hasErrorOccurred()) {
8061 Diag(CurrentLocation, diag::note_member_synthesized_at)
8062 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8063 Invalid = true;
8064 }
8065 }
8066 }
8067
8068 if (Invalid) {
8069 MoveAssignOperator->setInvalidDecl();
8070 return;
8071 }
8072
8073 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8074 /*isStmtExpr=*/false);
8075 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8076 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8077
8078 if (ASTMutationListener *L = getASTMutationListener()) {
8079 L->CompletedImplicitDefinition(MoveAssignOperator);
8080 }
8081}
8082
Alexis Hunt913820d2011-05-13 06:10:58 +00008083std::pair<Sema::ImplicitExceptionSpecification, bool>
8084Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008085 if (ClassDecl->isInvalidDecl())
8086 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8087
Douglas Gregor54be3392010-07-01 17:57:27 +00008088 // C++ [class.copy]p5:
8089 // The implicitly-declared copy constructor for a class X will
8090 // have the form
8091 //
8092 // X::X(const X&)
8093 //
8094 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00008095 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00008096 bool HasConstCopyConstructor = true;
8097
8098 // -- each direct or virtual base class B of X has a copy
8099 // constructor whose first parameter is of type const B& or
8100 // const volatile B&, and
8101 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8102 BaseEnd = ClassDecl->bases_end();
8103 HasConstCopyConstructor && Base != BaseEnd;
8104 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008105 // Virtual bases are handled below.
8106 if (Base->isVirtual())
8107 continue;
8108
Douglas Gregora6d69502010-07-02 23:41:54 +00008109 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00008110 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008111 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8112 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00008113 }
8114
8115 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8116 BaseEnd = ClassDecl->vbases_end();
8117 HasConstCopyConstructor && Base != BaseEnd;
8118 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008119 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00008120 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008121 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8122 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008123 }
8124
8125 // -- for all the nonstatic data members of X that are of a
8126 // class type M (or array thereof), each such class type
8127 // has a copy constructor whose first parameter is of type
8128 // const M& or const volatile M&.
8129 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8130 FieldEnd = ClassDecl->field_end();
8131 HasConstCopyConstructor && Field != FieldEnd;
8132 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008133 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008134 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008135 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8136 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008137 }
8138 }
Douglas Gregor54be3392010-07-01 17:57:27 +00008139 // Otherwise, the implicitly declared copy constructor will have
8140 // the form
8141 //
8142 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00008143
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008144 // C++ [except.spec]p14:
8145 // An implicitly declared special member function (Clause 12) shall have an
8146 // exception-specification. [...]
8147 ImplicitExceptionSpecification ExceptSpec(Context);
8148 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8149 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8150 BaseEnd = ClassDecl->bases_end();
8151 Base != BaseEnd;
8152 ++Base) {
8153 // Virtual bases are handled below.
8154 if (Base->isVirtual())
8155 continue;
8156
Douglas Gregora6d69502010-07-02 23:41:54 +00008157 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008158 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008159 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008160 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008161 ExceptSpec.CalledDecl(CopyConstructor);
8162 }
8163 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8164 BaseEnd = ClassDecl->vbases_end();
8165 Base != BaseEnd;
8166 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008167 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008168 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008169 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008170 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008171 ExceptSpec.CalledDecl(CopyConstructor);
8172 }
8173 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8174 FieldEnd = ClassDecl->field_end();
8175 Field != FieldEnd;
8176 ++Field) {
8177 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008178 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8179 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008180 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00008181 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008182 }
8183 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008184
Alexis Hunt913820d2011-05-13 06:10:58 +00008185 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8186}
8187
8188CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8189 CXXRecordDecl *ClassDecl) {
8190 // C++ [class.copy]p4:
8191 // If the class definition does not explicitly declare a copy
8192 // constructor, one is declared implicitly.
8193
8194 ImplicitExceptionSpecification Spec(Context);
8195 bool Const;
8196 llvm::tie(Spec, Const) =
8197 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8198
8199 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8200 QualType ArgType = ClassType;
8201 if (Const)
8202 ArgType = ArgType.withConst();
8203 ArgType = Context.getLValueReferenceType(ArgType);
8204
8205 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8206
Douglas Gregor54be3392010-07-01 17:57:27 +00008207 DeclarationName Name
8208 = Context.DeclarationNames.getCXXConstructorName(
8209 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008210 SourceLocation ClassLoc = ClassDecl->getLocation();
8211 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00008212
8213 // An implicitly-declared copy constructor is an inline public
8214 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00008215 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00008216 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00008217 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00008218 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00008219 /*TInfo=*/0,
8220 /*isExplicit=*/false,
8221 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00008222 /*isImplicitlyDeclared=*/true,
8223 // FIXME: apply the rules for definitions here
8224 /*isConstexpr=*/false);
Douglas Gregor54be3392010-07-01 17:57:27 +00008225 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00008226 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00008227 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8228
Douglas Gregora6d69502010-07-02 23:41:54 +00008229 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00008230 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8231
Douglas Gregor54be3392010-07-01 17:57:27 +00008232 // Add the parameter to the constructor.
8233 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008234 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00008235 /*IdentifierInfo=*/0,
8236 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008237 SC_None,
8238 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00008239 CopyConstructor->setParams(&FromParam, 1);
Alexis Hunt913820d2011-05-13 06:10:58 +00008240
Douglas Gregor0be31a22010-07-02 17:43:08 +00008241 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00008242 PushOnScopeChains(CopyConstructor, S, false);
8243 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008244
Alexis Huntd74c85f2011-06-22 01:05:13 +00008245 // C++0x [class.copy]p7:
8246 // ... If the class definition declares a move constructor or move
8247 // assignment operator, the implicitly declared constructor is defined as
8248 // deleted; ...
8249 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8250 ClassDecl->hasUserDeclaredMoveAssignment() ||
8251 ShouldDeleteCopyConstructor(CopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00008252 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00008253
8254 return CopyConstructor;
8255}
8256
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008257void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00008258 CXXConstructorDecl *CopyConstructor) {
8259 assert((CopyConstructor->isDefaulted() &&
8260 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008261 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008262 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008263
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00008264 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008265 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008266
Douglas Gregora57478e2010-05-01 15:04:51 +00008267 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008268 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008269
Alexis Hunt1d792652011-01-08 20:30:50 +00008270 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008271 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00008272 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00008273 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00008274 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00008275 } else {
8276 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8277 CopyConstructor->getLocation(),
8278 MultiStmtArg(*this, 0, 0),
8279 /*isStmtExpr=*/false)
8280 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00008281 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00008282
8283 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00008284
8285 if (ASTMutationListener *L = getASTMutationListener()) {
8286 L->CompletedImplicitDefinition(CopyConstructor);
8287 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008288}
8289
Sebastian Redl22653ba2011-08-30 19:58:05 +00008290Sema::ImplicitExceptionSpecification
8291Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8292 // C++ [except.spec]p14:
8293 // An implicitly declared special member function (Clause 12) shall have an
8294 // exception-specification. [...]
8295 ImplicitExceptionSpecification ExceptSpec(Context);
8296 if (ClassDecl->isInvalidDecl())
8297 return ExceptSpec;
8298
8299 // Direct base-class constructors.
8300 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8301 BEnd = ClassDecl->bases_end();
8302 B != BEnd; ++B) {
8303 if (B->isVirtual()) // Handled below.
8304 continue;
8305
8306 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8307 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8308 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8309 // If this is a deleted function, add it anyway. This might be conformant
8310 // with the standard. This might not. I'm not sure. It might not matter.
8311 if (Constructor)
8312 ExceptSpec.CalledDecl(Constructor);
8313 }
8314 }
8315
8316 // Virtual base-class constructors.
8317 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8318 BEnd = ClassDecl->vbases_end();
8319 B != BEnd; ++B) {
8320 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8321 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8322 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8323 // If this is a deleted function, add it anyway. This might be conformant
8324 // with the standard. This might not. I'm not sure. It might not matter.
8325 if (Constructor)
8326 ExceptSpec.CalledDecl(Constructor);
8327 }
8328 }
8329
8330 // Field constructors.
8331 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8332 FEnd = ClassDecl->field_end();
8333 F != FEnd; ++F) {
8334 if (F->hasInClassInitializer()) {
8335 if (Expr *E = F->getInClassInitializer())
8336 ExceptSpec.CalledExpr(E);
8337 else if (!F->isInvalidDecl())
8338 ExceptSpec.SetDelayed();
8339 } else if (const RecordType *RecordTy
8340 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8341 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8342 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8343 // If this is a deleted function, add it anyway. This might be conformant
8344 // with the standard. This might not. I'm not sure. It might not matter.
8345 // In particular, the problem is that this function never gets called. It
8346 // might just be ill-formed because this function attempts to refer to
8347 // a deleted function here.
8348 if (Constructor)
8349 ExceptSpec.CalledDecl(Constructor);
8350 }
8351 }
8352
8353 return ExceptSpec;
8354}
8355
8356CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8357 CXXRecordDecl *ClassDecl) {
8358 ImplicitExceptionSpecification Spec(
8359 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8360
8361 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8362 QualType ArgType = Context.getRValueReferenceType(ClassType);
8363
8364 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8365
8366 DeclarationName Name
8367 = Context.DeclarationNames.getCXXConstructorName(
8368 Context.getCanonicalType(ClassType));
8369 SourceLocation ClassLoc = ClassDecl->getLocation();
8370 DeclarationNameInfo NameInfo(Name, ClassLoc);
8371
8372 // C++0x [class.copy]p11:
8373 // An implicitly-declared copy/move constructor is an inline public
8374 // member of its class.
8375 CXXConstructorDecl *MoveConstructor
8376 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8377 Context.getFunctionType(Context.VoidTy,
8378 &ArgType, 1, EPI),
8379 /*TInfo=*/0,
8380 /*isExplicit=*/false,
8381 /*isInline=*/true,
8382 /*isImplicitlyDeclared=*/true,
8383 // FIXME: apply the rules for definitions here
8384 /*isConstexpr=*/false);
8385 MoveConstructor->setAccess(AS_public);
8386 MoveConstructor->setDefaulted();
8387 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8388
8389 // Add the parameter to the constructor.
8390 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8391 ClassLoc, ClassLoc,
8392 /*IdentifierInfo=*/0,
8393 ArgType, /*TInfo=*/0,
8394 SC_None,
8395 SC_None, 0);
8396 MoveConstructor->setParams(&FromParam, 1);
8397
8398 // C++0x [class.copy]p9:
8399 // If the definition of a class X does not explicitly declare a move
8400 // constructor, one will be implicitly declared as defaulted if and only if:
8401 // [...]
8402 // - the move constructor would not be implicitly defined as deleted.
8403 if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8404 // Cache this result so that we don't try to generate this over and over
8405 // on every lookup, leaking memory and wasting time.
8406 ClassDecl->setFailedImplicitMoveConstructor();
8407 return 0;
8408 }
8409
8410 // Note that we have declared this constructor.
8411 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8412
8413 if (Scope *S = getScopeForContext(ClassDecl))
8414 PushOnScopeChains(MoveConstructor, S, false);
8415 ClassDecl->addDecl(MoveConstructor);
8416
8417 return MoveConstructor;
8418}
8419
8420void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8421 CXXConstructorDecl *MoveConstructor) {
8422 assert((MoveConstructor->isDefaulted() &&
8423 MoveConstructor->isMoveConstructor() &&
8424 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8425 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8426
8427 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8428 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8429
8430 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8431 DiagnosticErrorTrap Trap(Diags);
8432
8433 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8434 Trap.hasErrorOccurred()) {
8435 Diag(CurrentLocation, diag::note_member_synthesized_at)
8436 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8437 MoveConstructor->setInvalidDecl();
8438 } else {
8439 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8440 MoveConstructor->getLocation(),
8441 MultiStmtArg(*this, 0, 0),
8442 /*isStmtExpr=*/false)
8443 .takeAs<Stmt>());
8444 }
8445
8446 MoveConstructor->setUsed();
8447
8448 if (ASTMutationListener *L = getASTMutationListener()) {
8449 L->CompletedImplicitDefinition(MoveConstructor);
8450 }
8451}
8452
John McCalldadc5752010-08-24 06:29:42 +00008453ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008454Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00008455 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008456 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008457 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008458 unsigned ConstructKind,
8459 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00008460 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00008461
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008462 // C++0x [class.copy]p34:
8463 // When certain criteria are met, an implementation is allowed to
8464 // omit the copy/move construction of a class object, even if the
8465 // copy/move constructor and/or destructor for the object have
8466 // side effects. [...]
8467 // - when a temporary class object that has not been bound to a
8468 // reference (12.2) would be copied/moved to a class object
8469 // with the same cv-unqualified type, the copy/move operation
8470 // can be omitted by constructing the temporary object
8471 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00008472 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00008473 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008474 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00008475 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00008476 }
Mike Stump11289f42009-09-09 15:08:12 +00008477
8478 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008479 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008480 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00008481}
8482
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008483/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8484/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00008485ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008486Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8487 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008488 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008489 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008490 unsigned ConstructKind,
8491 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00008492 unsigned NumExprs = ExprArgs.size();
8493 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00008494
Nick Lewyckyd4693212011-03-25 01:44:32 +00008495 for (specific_attr_iterator<NonNullAttr>
8496 i = Constructor->specific_attr_begin<NonNullAttr>(),
8497 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8498 const NonNullAttr *NonNull = *i;
8499 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8500 }
8501
Douglas Gregor27381f32009-11-23 12:27:39 +00008502 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00008503 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008504 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00008505 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008506 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8507 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008508}
8509
Mike Stump11289f42009-09-09 15:08:12 +00008510bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008511 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00008512 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00008513 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00008514 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00008515 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00008516 move(Exprs), false, CXXConstructExpr::CK_Complete,
8517 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008518 if (TempResult.isInvalid())
8519 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008520
Anders Carlsson6eb55572009-08-25 05:12:04 +00008521 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00008522 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00008523 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00008524 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00008525 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00008526
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008527 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00008528}
8529
John McCall03c48482010-02-02 09:10:11 +00008530void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00008531 if (VD->isInvalidDecl()) return;
8532
John McCall03c48482010-02-02 09:10:11 +00008533 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00008534 if (ClassDecl->isInvalidDecl()) return;
8535 if (ClassDecl->hasTrivialDestructor()) return;
8536 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00008537
Chandler Carruth86d17d32011-03-27 21:26:48 +00008538 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8539 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8540 CheckDestructorAccess(VD->getLocation(), Destructor,
8541 PDiag(diag::err_access_dtor_var)
8542 << VD->getDeclName()
8543 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00008544
Chandler Carruth86d17d32011-03-27 21:26:48 +00008545 if (!VD->hasGlobalStorage()) return;
8546
8547 // Emit warning for non-trivial dtor in global scope (a real global,
8548 // class-static, function-static).
8549 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8550
8551 // TODO: this should be re-enabled for static locals by !CXAAtExit
8552 if (!VD->isStaticLocal())
8553 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008554}
8555
Mike Stump11289f42009-09-09 15:08:12 +00008556/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008557/// ActOnDeclarator, when a C++ direct initializer is present.
8558/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00008559void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00008560 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008561 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00008562 SourceLocation RParenLoc,
8563 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00008564 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008565
8566 // If there is no declaration, there was an error parsing it. Just ignore
8567 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00008568 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008569 return;
Mike Stump11289f42009-09-09 15:08:12 +00008570
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008571 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8572 if (!VDecl) {
8573 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8574 RealDecl->setInvalidDecl();
8575 return;
8576 }
8577
Richard Smith30482bc2011-02-20 03:19:35 +00008578 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8579 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008580 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8581 if (Exprs.size() > 1) {
8582 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8583 diag::err_auto_var_init_multiple_expressions)
8584 << VDecl->getDeclName() << VDecl->getType()
8585 << VDecl->getSourceRange();
8586 RealDecl->setInvalidDecl();
8587 return;
8588 }
8589
8590 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00008591 TypeSourceInfo *DeducedType = 0;
8592 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00008593 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8594 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8595 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00008596 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00008597 RealDecl->setInvalidDecl();
8598 return;
8599 }
Richard Smith9647d3c2011-03-17 16:11:59 +00008600 VDecl->setTypeSourceInfo(DeducedType);
8601 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00008602
John McCall31168b02011-06-15 23:02:42 +00008603 // In ARC, infer lifetime.
8604 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8605 VDecl->setInvalidDecl();
8606
Richard Smith30482bc2011-02-20 03:19:35 +00008607 // If this is a redeclaration, check that the type we just deduced matches
8608 // the previously declared type.
8609 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8610 MergeVarDeclTypes(VDecl, Old);
8611 }
8612
Douglas Gregor402250f2009-08-26 21:14:46 +00008613 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00008614 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008615 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8616 //
8617 // Clients that want to distinguish between the two forms, can check for
8618 // direct initializer using VarDecl::hasCXXDirectInitializer().
8619 // A major benefit is that clients that don't particularly care about which
8620 // exactly form was it (like the CodeGen) can handle both cases without
8621 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00008622
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008623 // C++ 8.5p11:
8624 // The form of initialization (using parentheses or '=') is generally
8625 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00008626 // class type.
8627
Douglas Gregor50dc2192010-02-11 22:55:30 +00008628 if (!VDecl->getType()->isDependentType() &&
8629 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00008630 diag::err_typecheck_decl_incomplete_type)) {
8631 VDecl->setInvalidDecl();
8632 return;
8633 }
8634
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008635 // The variable can not have an abstract class type.
8636 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8637 diag::err_abstract_type_in_decl,
8638 AbstractVariableType))
8639 VDecl->setInvalidDecl();
8640
Sebastian Redl5ca79842010-02-01 20:16:42 +00008641 const VarDecl *Def;
8642 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008643 Diag(VDecl->getLocation(), diag::err_redefinition)
8644 << VDecl->getDeclName();
8645 Diag(Def->getLocation(), diag::note_previous_definition);
8646 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00008647 return;
8648 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00008649
Douglas Gregorf0f83692010-08-24 05:27:49 +00008650 // C++ [class.static.data]p4
8651 // If a static data member is of const integral or const
8652 // enumeration type, its declaration in the class definition can
8653 // specify a constant-initializer which shall be an integral
8654 // constant expression (5.19). In that case, the member can appear
8655 // in integral constant expressions. The member shall still be
8656 // defined in a namespace scope if it is used in the program and the
8657 // namespace scope definition shall not contain an initializer.
8658 //
8659 // We already performed a redefinition check above, but for static
8660 // data members we also need to check whether there was an in-class
8661 // declaration with an initializer.
8662 const VarDecl* PrevInit = 0;
8663 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8664 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8665 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8666 return;
8667 }
8668
Douglas Gregor71f39c92010-12-16 01:31:22 +00008669 bool IsDependent = false;
8670 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8671 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8672 VDecl->setInvalidDecl();
8673 return;
8674 }
8675
8676 if (Exprs.get()[I]->isTypeDependent())
8677 IsDependent = true;
8678 }
8679
Douglas Gregor50dc2192010-02-11 22:55:30 +00008680 // If either the declaration has a dependent type or if any of the
8681 // expressions is type-dependent, we represent the initialization
8682 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00008683 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00008684 // Let clients know that initialization was done with a direct initializer.
8685 VDecl->setCXXDirectInitializer(true);
8686
8687 // Store the initialization expressions as a ParenListExpr.
8688 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00008689 VDecl->setInit(new (Context) ParenListExpr(
8690 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8691 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00008692 return;
8693 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008694
8695 // Capture the variable that is being initialized and the style of
8696 // initialization.
8697 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8698
8699 // FIXME: Poor source location information.
8700 InitializationKind Kind
8701 = InitializationKind::CreateDirect(VDecl->getLocation(),
8702 LParenLoc, RParenLoc);
8703
8704 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00008705 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00008706 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008707 if (Result.isInvalid()) {
8708 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008709 return;
8710 }
John McCallacf0ee52010-10-08 02:01:28 +00008711
8712 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008713
Douglas Gregora40433a2010-12-07 00:41:46 +00008714 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00008715 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008716 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00008717
John McCall8b7fd8f12011-01-19 11:48:09 +00008718 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008719}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008720
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008721/// \brief Given a constructor and the set of arguments provided for the
8722/// constructor, convert the arguments and add any required default arguments
8723/// to form a proper call to this constructor.
8724///
8725/// \returns true if an error occurred, false otherwise.
8726bool
8727Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8728 MultiExprArg ArgsPtr,
8729 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00008730 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008731 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8732 unsigned NumArgs = ArgsPtr.size();
8733 Expr **Args = (Expr **)ArgsPtr.get();
8734
8735 const FunctionProtoType *Proto
8736 = Constructor->getType()->getAs<FunctionProtoType>();
8737 assert(Proto && "Constructor without a prototype?");
8738 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008739
8740 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008741 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008742 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008743 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008744 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008745
8746 VariadicCallType CallType =
8747 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008748 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008749 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8750 Proto, 0, Args, NumArgs, AllArgs,
8751 CallType);
8752 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8753 ConvertedArgs.push_back(AllArgs[i]);
8754 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00008755}
8756
Anders Carlssone363c8e2009-12-12 00:32:00 +00008757static inline bool
8758CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8759 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008760 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00008761 if (isa<NamespaceDecl>(DC)) {
8762 return SemaRef.Diag(FnDecl->getLocation(),
8763 diag::err_operator_new_delete_declared_in_namespace)
8764 << FnDecl->getDeclName();
8765 }
8766
8767 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00008768 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00008769 return SemaRef.Diag(FnDecl->getLocation(),
8770 diag::err_operator_new_delete_declared_static)
8771 << FnDecl->getDeclName();
8772 }
8773
Anders Carlsson60659a82009-12-12 02:43:16 +00008774 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00008775}
8776
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008777static inline bool
8778CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8779 CanQualType ExpectedResultType,
8780 CanQualType ExpectedFirstParamType,
8781 unsigned DependentParamTypeDiag,
8782 unsigned InvalidParamTypeDiag) {
8783 QualType ResultType =
8784 FnDecl->getType()->getAs<FunctionType>()->getResultType();
8785
8786 // Check that the result type is not dependent.
8787 if (ResultType->isDependentType())
8788 return SemaRef.Diag(FnDecl->getLocation(),
8789 diag::err_operator_new_delete_dependent_result_type)
8790 << FnDecl->getDeclName() << ExpectedResultType;
8791
8792 // Check that the result type is what we expect.
8793 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8794 return SemaRef.Diag(FnDecl->getLocation(),
8795 diag::err_operator_new_delete_invalid_result_type)
8796 << FnDecl->getDeclName() << ExpectedResultType;
8797
8798 // A function template must have at least 2 parameters.
8799 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8800 return SemaRef.Diag(FnDecl->getLocation(),
8801 diag::err_operator_new_delete_template_too_few_parameters)
8802 << FnDecl->getDeclName();
8803
8804 // The function decl must have at least 1 parameter.
8805 if (FnDecl->getNumParams() == 0)
8806 return SemaRef.Diag(FnDecl->getLocation(),
8807 diag::err_operator_new_delete_too_few_parameters)
8808 << FnDecl->getDeclName();
8809
8810 // Check the the first parameter type is not dependent.
8811 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8812 if (FirstParamType->isDependentType())
8813 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8814 << FnDecl->getDeclName() << ExpectedFirstParamType;
8815
8816 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00008817 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008818 ExpectedFirstParamType)
8819 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8820 << FnDecl->getDeclName() << ExpectedFirstParamType;
8821
8822 return false;
8823}
8824
Anders Carlsson12308f42009-12-11 23:23:22 +00008825static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008826CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00008827 // C++ [basic.stc.dynamic.allocation]p1:
8828 // A program is ill-formed if an allocation function is declared in a
8829 // namespace scope other than global scope or declared static in global
8830 // scope.
8831 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8832 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008833
8834 CanQualType SizeTy =
8835 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8836
8837 // C++ [basic.stc.dynamic.allocation]p1:
8838 // The return type shall be void*. The first parameter shall have type
8839 // std::size_t.
8840 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8841 SizeTy,
8842 diag::err_operator_new_dependent_param_type,
8843 diag::err_operator_new_param_type))
8844 return true;
8845
8846 // C++ [basic.stc.dynamic.allocation]p1:
8847 // The first parameter shall not have an associated default argument.
8848 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00008849 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008850 diag::err_operator_new_default_arg)
8851 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8852
8853 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00008854}
8855
8856static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00008857CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8858 // C++ [basic.stc.dynamic.deallocation]p1:
8859 // A program is ill-formed if deallocation functions are declared in a
8860 // namespace scope other than global scope or declared static in global
8861 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00008862 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8863 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00008864
8865 // C++ [basic.stc.dynamic.deallocation]p2:
8866 // Each deallocation function shall return void and its first parameter
8867 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008868 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8869 SemaRef.Context.VoidPtrTy,
8870 diag::err_operator_delete_dependent_param_type,
8871 diag::err_operator_delete_param_type))
8872 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00008873
Anders Carlsson12308f42009-12-11 23:23:22 +00008874 return false;
8875}
8876
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008877/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8878/// of this overloaded operator is well-formed. If so, returns false;
8879/// otherwise, emits appropriate diagnostics and returns true.
8880bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00008881 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008882 "Expected an overloaded operator declaration");
8883
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008884 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8885
Mike Stump11289f42009-09-09 15:08:12 +00008886 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008887 // The allocation and deallocation functions, operator new,
8888 // operator new[], operator delete and operator delete[], are
8889 // described completely in 3.7.3. The attributes and restrictions
8890 // found in the rest of this subclause do not apply to them unless
8891 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00008892 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00008893 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00008894
Anders Carlsson22f443f2009-12-12 00:26:23 +00008895 if (Op == OO_New || Op == OO_Array_New)
8896 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008897
8898 // C++ [over.oper]p6:
8899 // An operator function shall either be a non-static member
8900 // function or be a non-member function and have at least one
8901 // parameter whose type is a class, a reference to a class, an
8902 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00008903 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8904 if (MethodDecl->isStatic())
8905 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008906 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008907 } else {
8908 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00008909 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8910 ParamEnd = FnDecl->param_end();
8911 Param != ParamEnd; ++Param) {
8912 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00008913 if (ParamType->isDependentType() || ParamType->isRecordType() ||
8914 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008915 ClassOrEnumParam = true;
8916 break;
8917 }
8918 }
8919
Douglas Gregord69246b2008-11-17 16:14:12 +00008920 if (!ClassOrEnumParam)
8921 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00008922 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008923 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008924 }
8925
8926 // C++ [over.oper]p8:
8927 // An operator function cannot have default arguments (8.3.6),
8928 // except where explicitly stated below.
8929 //
Mike Stump11289f42009-09-09 15:08:12 +00008930 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008931 // (C++ [over.call]p1).
8932 if (Op != OO_Call) {
8933 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8934 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008935 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00008936 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00008937 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00008938 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008939 }
8940 }
8941
Douglas Gregor6cf08062008-11-10 13:38:07 +00008942 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8943 { false, false, false }
8944#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8945 , { Unary, Binary, MemberOnly }
8946#include "clang/Basic/OperatorKinds.def"
8947 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008948
Douglas Gregor6cf08062008-11-10 13:38:07 +00008949 bool CanBeUnaryOperator = OperatorUses[Op][0];
8950 bool CanBeBinaryOperator = OperatorUses[Op][1];
8951 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008952
8953 // C++ [over.oper]p8:
8954 // [...] Operator functions cannot have more or fewer parameters
8955 // than the number required for the corresponding operator, as
8956 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00008957 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00008958 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008959 if (Op != OO_Call &&
8960 ((NumParams == 1 && !CanBeUnaryOperator) ||
8961 (NumParams == 2 && !CanBeBinaryOperator) ||
8962 (NumParams < 1) || (NumParams > 2))) {
8963 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008964 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00008965 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008966 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00008967 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008968 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00008969 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00008970 assert(CanBeBinaryOperator &&
8971 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008972 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00008973 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008974
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00008975 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008976 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008977 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00008978
Douglas Gregord69246b2008-11-17 16:14:12 +00008979 // Overloaded operators other than operator() cannot be variadic.
8980 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00008981 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00008982 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008983 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008984 }
8985
8986 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00008987 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
8988 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00008989 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008990 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00008991 }
8992
8993 // C++ [over.inc]p1:
8994 // The user-defined function called operator++ implements the
8995 // prefix and postfix ++ operator. If this function is a member
8996 // function with no parameters, or a non-member function with one
8997 // parameter of class or enumeration type, it defines the prefix
8998 // increment operator ++ for objects of that type. If the function
8999 // is a member function with one parameter (which shall be of type
9000 // int) or a non-member function with two parameters (the second
9001 // of which shall be of type int), it defines the postfix
9002 // increment operator ++ for objects of that type.
9003 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9004 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9005 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00009006 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009007 ParamIsInt = BT->getKind() == BuiltinType::Int;
9008
Chris Lattner2b786902008-11-21 07:50:02 +00009009 if (!ParamIsInt)
9010 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00009011 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009012 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009013 }
9014
Douglas Gregord69246b2008-11-17 16:14:12 +00009015 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009016}
Chris Lattner3b024a32008-12-17 07:09:26 +00009017
Alexis Huntc88db062010-01-13 09:01:02 +00009018/// CheckLiteralOperatorDeclaration - Check whether the declaration
9019/// of this literal operator function is well-formed. If so, returns
9020/// false; otherwise, emits appropriate diagnostics and returns true.
9021bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9022 DeclContext *DC = FnDecl->getDeclContext();
9023 Decl::Kind Kind = DC->getDeclKind();
9024 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9025 Kind != Decl::LinkageSpec) {
9026 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9027 << FnDecl->getDeclName();
9028 return true;
9029 }
9030
9031 bool Valid = false;
9032
Alexis Hunt7dd26172010-04-07 23:11:06 +00009033 // template <char...> type operator "" name() is the only valid template
9034 // signature, and the only valid signature with no parameters.
9035 if (FnDecl->param_size() == 0) {
9036 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9037 // Must have only one template parameter
9038 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9039 if (Params->size() == 1) {
9040 NonTypeTemplateParmDecl *PmDecl =
9041 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00009042
Alexis Hunt7dd26172010-04-07 23:11:06 +00009043 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00009044 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9045 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9046 Valid = true;
9047 }
9048 }
9049 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00009050 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00009051 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9052
Alexis Huntc88db062010-01-13 09:01:02 +00009053 QualType T = (*Param)->getType();
9054
Alexis Hunt079a6f72010-04-07 22:57:35 +00009055 // unsigned long long int, long double, and any character type are allowed
9056 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00009057 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9058 Context.hasSameType(T, Context.LongDoubleTy) ||
9059 Context.hasSameType(T, Context.CharTy) ||
9060 Context.hasSameType(T, Context.WCharTy) ||
9061 Context.hasSameType(T, Context.Char16Ty) ||
9062 Context.hasSameType(T, Context.Char32Ty)) {
9063 if (++Param == FnDecl->param_end())
9064 Valid = true;
9065 goto FinishedParams;
9066 }
9067
Alexis Hunt079a6f72010-04-07 22:57:35 +00009068 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00009069 const PointerType *PT = T->getAs<PointerType>();
9070 if (!PT)
9071 goto FinishedParams;
9072 T = PT->getPointeeType();
9073 if (!T.isConstQualified())
9074 goto FinishedParams;
9075 T = T.getUnqualifiedType();
9076
9077 // Move on to the second parameter;
9078 ++Param;
9079
9080 // If there is no second parameter, the first must be a const char *
9081 if (Param == FnDecl->param_end()) {
9082 if (Context.hasSameType(T, Context.CharTy))
9083 Valid = true;
9084 goto FinishedParams;
9085 }
9086
9087 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9088 // are allowed as the first parameter to a two-parameter function
9089 if (!(Context.hasSameType(T, Context.CharTy) ||
9090 Context.hasSameType(T, Context.WCharTy) ||
9091 Context.hasSameType(T, Context.Char16Ty) ||
9092 Context.hasSameType(T, Context.Char32Ty)))
9093 goto FinishedParams;
9094
9095 // The second and final parameter must be an std::size_t
9096 T = (*Param)->getType().getUnqualifiedType();
9097 if (Context.hasSameType(T, Context.getSizeType()) &&
9098 ++Param == FnDecl->param_end())
9099 Valid = true;
9100 }
9101
9102 // FIXME: This diagnostic is absolutely terrible.
9103FinishedParams:
9104 if (!Valid) {
9105 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9106 << FnDecl->getDeclName();
9107 return true;
9108 }
9109
Douglas Gregor86325ad2011-08-30 22:40:35 +00009110 StringRef LiteralName
9111 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9112 if (LiteralName[0] != '_') {
9113 // C++0x [usrlit.suffix]p1:
9114 // Literal suffix identifiers that do not start with an underscore are
9115 // reserved for future standardization.
9116 bool IsHexFloat = true;
9117 if (LiteralName.size() > 1 &&
9118 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9119 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9120 if (!isdigit(LiteralName[I])) {
9121 IsHexFloat = false;
9122 break;
9123 }
9124 }
9125 }
9126
9127 if (IsHexFloat)
9128 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9129 << LiteralName;
9130 else
9131 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9132 }
9133
Alexis Huntc88db062010-01-13 09:01:02 +00009134 return false;
9135}
9136
Douglas Gregor07665a62009-01-05 19:45:36 +00009137/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9138/// linkage specification, including the language and (if present)
9139/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9140/// the location of the language string literal, which is provided
9141/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9142/// the '{' brace. Otherwise, this linkage specification does not
9143/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00009144Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9145 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009146 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +00009147 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00009148 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009149 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009150 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009151 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009152 Language = LinkageSpecDecl::lang_cxx;
9153 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00009154 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00009155 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00009156 }
Mike Stump11289f42009-09-09 15:08:12 +00009157
Chris Lattner438e5012008-12-17 07:13:27 +00009158 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00009159
Douglas Gregor07665a62009-01-05 19:45:36 +00009160 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009161 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009162 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00009163 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00009164 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00009165}
9166
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00009167/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00009168/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9169/// valid, it's the position of the closing '}' brace in a linkage
9170/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00009171Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009172 Decl *LinkageSpec,
9173 SourceLocation RBraceLoc) {
9174 if (LinkageSpec) {
9175 if (RBraceLoc.isValid()) {
9176 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9177 LSDecl->setRBraceLoc(RBraceLoc);
9178 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009179 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009180 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009181 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00009182}
9183
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009184/// \brief Perform semantic analysis for the variable declaration that
9185/// occurs within a C++ catch clause, returning the newly-created
9186/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009187VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00009188 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009189 SourceLocation StartLoc,
9190 SourceLocation Loc,
9191 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009192 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009193 QualType ExDeclType = TInfo->getType();
9194
Sebastian Redl54c04d42008-12-22 19:15:10 +00009195 // Arrays and functions decay.
9196 if (ExDeclType->isArrayType())
9197 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9198 else if (ExDeclType->isFunctionType())
9199 ExDeclType = Context.getPointerType(ExDeclType);
9200
9201 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9202 // The exception-declaration shall not denote a pointer or reference to an
9203 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00009204 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00009205 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009206 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00009207 Invalid = true;
9208 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009209
Douglas Gregor104ee002010-03-08 01:47:36 +00009210 // GCC allows catching pointers and references to incomplete types
9211 // as an extension; so do we, but we warn by default.
9212
Sebastian Redl54c04d42008-12-22 19:15:10 +00009213 QualType BaseType = ExDeclType;
9214 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00009215 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00009216 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009217 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009218 BaseType = Ptr->getPointeeType();
9219 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00009220 DK = diag::ext_catch_incomplete_ptr;
9221 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00009222 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00009223 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009224 BaseType = Ref->getPointeeType();
9225 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00009226 DK = diag::ext_catch_incomplete_ref;
9227 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009228 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00009229 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00009230 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9231 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00009232 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009233
Mike Stump11289f42009-09-09 15:08:12 +00009234 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009235 RequireNonAbstractType(Loc, ExDeclType,
9236 diag::err_abstract_type_in_decl,
9237 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00009238 Invalid = true;
9239
John McCall2ca705e2010-07-24 00:37:23 +00009240 // Only the non-fragile NeXT runtime currently supports C++ catches
9241 // of ObjC types, and no runtime supports catching ObjC types by value.
9242 if (!Invalid && getLangOptions().ObjC1) {
9243 QualType T = ExDeclType;
9244 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9245 T = RT->getPointeeType();
9246
9247 if (T->isObjCObjectType()) {
9248 Diag(Loc, diag::err_objc_object_catch);
9249 Invalid = true;
9250 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00009251 if (!getLangOptions().ObjCNonFragileABI)
9252 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00009253 }
9254 }
9255
Abramo Bagnaradff19302011-03-08 08:55:46 +00009256 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9257 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00009258 ExDecl->setExceptionVariable(true);
9259
Douglas Gregor750734c2011-07-06 18:14:43 +00009260 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +00009261 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00009262 // C++ [except.handle]p16:
9263 // The object declared in an exception-declaration or, if the
9264 // exception-declaration does not specify a name, a temporary (12.2) is
9265 // copy-initialized (8.5) from the exception object. [...]
9266 // The object is destroyed when the handler exits, after the destruction
9267 // of any automatic objects initialized within the handler.
9268 //
9269 // We just pretend to initialize the object with itself, then make sure
9270 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00009271 QualType initType = ExDeclType;
9272
9273 InitializedEntity entity =
9274 InitializedEntity::InitializeVariable(ExDecl);
9275 InitializationKind initKind =
9276 InitializationKind::CreateCopy(Loc, SourceLocation());
9277
9278 Expr *opaqueValue =
9279 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9280 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9281 ExprResult result = sequence.Perform(*this, entity, initKind,
9282 MultiExprArg(&opaqueValue, 1));
9283 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00009284 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00009285 else {
9286 // If the constructor used was non-trivial, set this as the
9287 // "initializer".
9288 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9289 if (!construct->getConstructor()->isTrivial()) {
9290 Expr *init = MaybeCreateExprWithCleanups(construct);
9291 ExDecl->setInit(init);
9292 }
9293
9294 // And make sure it's destructable.
9295 FinalizeVarWithDestructor(ExDecl, recordType);
9296 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00009297 }
9298 }
9299
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009300 if (Invalid)
9301 ExDecl->setInvalidDecl();
9302
9303 return ExDecl;
9304}
9305
9306/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9307/// handler.
John McCall48871652010-08-21 09:40:31 +00009308Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00009309 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00009310 bool Invalid = D.isInvalidType();
9311
9312 // Check for unexpanded parameter packs.
9313 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9314 UPPC_ExceptionType)) {
9315 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9316 D.getIdentifierLoc());
9317 Invalid = true;
9318 }
9319
Sebastian Redl54c04d42008-12-22 19:15:10 +00009320 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009321 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00009322 LookupOrdinaryName,
9323 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009324 // The scope should be freshly made just for us. There is just no way
9325 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00009326 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00009327 if (PrevDecl->isTemplateParameter()) {
9328 // Maybe we will complain about the shadowed template parameter.
9329 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009330 }
9331 }
9332
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009333 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009334 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9335 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009336 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009337 }
9338
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009339 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009340 D.getSourceRange().getBegin(),
9341 D.getIdentifierLoc(),
9342 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009343 if (Invalid)
9344 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009345
Sebastian Redl54c04d42008-12-22 19:15:10 +00009346 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009347 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009348 PushOnScopeChains(ExDecl, S);
9349 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009350 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009351
Douglas Gregor758a8692009-06-17 21:51:59 +00009352 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00009353 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009354}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009355
Abramo Bagnaraea947882011-03-08 16:41:52 +00009356Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00009357 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009358 Expr *AssertMessageExpr_,
9359 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00009360 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009361
Anders Carlsson54b26982009-03-14 00:33:21 +00009362 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9363 llvm::APSInt Value(32);
9364 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009365 Diag(StaticAssertLoc,
9366 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00009367 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00009368 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00009369 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009370
Anders Carlsson54b26982009-03-14 00:33:21 +00009371 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009372 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00009373 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00009374 }
9375 }
Mike Stump11289f42009-09-09 15:08:12 +00009376
Douglas Gregoref68fee2010-12-15 23:55:21 +00009377 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9378 return 0;
9379
Abramo Bagnaraea947882011-03-08 16:41:52 +00009380 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9381 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00009382
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009383 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00009384 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009385}
Sebastian Redlf769df52009-03-24 22:27:57 +00009386
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009387/// \brief Perform semantic analysis of the given friend type declaration.
9388///
9389/// \returns A friend declaration that.
9390FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9391 TypeSourceInfo *TSInfo) {
9392 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9393
9394 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009395 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009396
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009397 if (!getLangOptions().CPlusPlus0x) {
9398 // C++03 [class.friend]p2:
9399 // An elaborated-type-specifier shall be used in a friend declaration
9400 // for a class.*
9401 //
9402 // * The class-key of the elaborated-type-specifier is required.
9403 if (!ActiveTemplateInstantiations.empty()) {
9404 // Do not complain about the form of friend template types during
9405 // template instantiation; we will already have complained when the
9406 // template was declared.
9407 } else if (!T->isElaboratedTypeSpecifier()) {
9408 // If we evaluated the type to a record type, suggest putting
9409 // a tag in front.
9410 if (const RecordType *RT = T->getAs<RecordType>()) {
9411 RecordDecl *RD = RT->getDecl();
9412
9413 std::string InsertionText = std::string(" ") + RD->getKindName();
9414
9415 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9416 << (unsigned) RD->getTagKind()
9417 << T
9418 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9419 InsertionText);
9420 } else {
9421 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9422 << T
9423 << SourceRange(FriendLoc, TypeRange.getEnd());
9424 }
9425 } else if (T->getAs<EnumType>()) {
9426 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009427 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009428 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009429 }
9430 }
9431
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009432 // C++0x [class.friend]p3:
9433 // If the type specifier in a friend declaration designates a (possibly
9434 // cv-qualified) class type, that class is declared as a friend; otherwise,
9435 // the friend declaration is ignored.
9436
9437 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9438 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009439
9440 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9441}
9442
John McCallace48cd2010-10-19 01:40:49 +00009443/// Handle a friend tag declaration where the scope specifier was
9444/// templated.
9445Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9446 unsigned TagSpec, SourceLocation TagLoc,
9447 CXXScopeSpec &SS,
9448 IdentifierInfo *Name, SourceLocation NameLoc,
9449 AttributeList *Attr,
9450 MultiTemplateParamsArg TempParamLists) {
9451 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9452
9453 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00009454 bool Invalid = false;
9455
9456 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00009457 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00009458 TempParamLists.get(),
9459 TempParamLists.size(),
9460 /*friend*/ true,
9461 isExplicitSpecialization,
9462 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00009463 if (TemplateParams->size() > 0) {
9464 // This is a declaration of a class template.
9465 if (Invalid)
9466 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009467
Eric Christopher6f228b52011-07-21 05:34:24 +00009468 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9469 SS, Name, NameLoc, Attr,
9470 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +00009471 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +00009472 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009473 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00009474 } else {
9475 // The "template<>" header is extraneous.
9476 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9477 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9478 isExplicitSpecialization = true;
9479 }
9480 }
9481
9482 if (Invalid) return 0;
9483
9484 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9485
9486 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00009487 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00009488 if (TempParamLists.get()[I]->size()) {
9489 isAllExplicitSpecializations = false;
9490 break;
9491 }
9492 }
9493
9494 // FIXME: don't ignore attributes.
9495
9496 // If it's explicit specializations all the way down, just forget
9497 // about the template header and build an appropriate non-templated
9498 // friend. TODO: for source fidelity, remember the headers.
9499 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009500 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00009501 ElaboratedTypeKeyword Keyword
9502 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009503 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009504 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00009505 if (T.isNull())
9506 return 0;
9507
9508 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9509 if (isa<DependentNameType>(T)) {
9510 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9511 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009512 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009513 TL.setNameLoc(NameLoc);
9514 } else {
9515 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9516 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009517 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009518 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9519 }
9520
9521 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9522 TSI, FriendLoc);
9523 Friend->setAccess(AS_public);
9524 CurContext->addDecl(Friend);
9525 return Friend;
9526 }
9527
9528 // Handle the case of a templated-scope friend class. e.g.
9529 // template <class T> class A<T>::B;
9530 // FIXME: we don't support these right now.
9531 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9532 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9533 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9534 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9535 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009536 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00009537 TL.setNameLoc(NameLoc);
9538
9539 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9540 TSI, FriendLoc);
9541 Friend->setAccess(AS_public);
9542 Friend->setUnsupportedFriend(true);
9543 CurContext->addDecl(Friend);
9544 return Friend;
9545}
9546
9547
John McCall11083da2009-09-16 22:47:08 +00009548/// Handle a friend type declaration. This works in tandem with
9549/// ActOnTag.
9550///
9551/// Notes on friend class templates:
9552///
9553/// We generally treat friend class declarations as if they were
9554/// declaring a class. So, for example, the elaborated type specifier
9555/// in a friend declaration is required to obey the restrictions of a
9556/// class-head (i.e. no typedefs in the scope chain), template
9557/// parameters are required to match up with simple template-ids, &c.
9558/// However, unlike when declaring a template specialization, it's
9559/// okay to refer to a template specialization without an empty
9560/// template parameter declaration, e.g.
9561/// friend class A<T>::B<unsigned>;
9562/// We permit this as a special case; if there are any template
9563/// parameters present at all, require proper matching, i.e.
9564/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00009565Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00009566 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00009567 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00009568
9569 assert(DS.isFriendSpecified());
9570 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9571
John McCall11083da2009-09-16 22:47:08 +00009572 // Try to convert the decl specifier to a type. This works for
9573 // friend templates because ActOnTag never produces a ClassTemplateDecl
9574 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00009575 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00009576 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9577 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00009578 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00009579 return 0;
John McCall07e91c02009-08-06 02:15:43 +00009580
Douglas Gregor6c110f32010-12-16 01:14:37 +00009581 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9582 return 0;
9583
John McCall11083da2009-09-16 22:47:08 +00009584 // This is definitely an error in C++98. It's probably meant to
9585 // be forbidden in C++0x, too, but the specification is just
9586 // poorly written.
9587 //
9588 // The problem is with declarations like the following:
9589 // template <T> friend A<T>::foo;
9590 // where deciding whether a class C is a friend or not now hinges
9591 // on whether there exists an instantiation of A that causes
9592 // 'foo' to equal C. There are restrictions on class-heads
9593 // (which we declare (by fiat) elaborated friend declarations to
9594 // be) that makes this tractable.
9595 //
9596 // FIXME: handle "template <> friend class A<T>;", which
9597 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00009598 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00009599 Diag(Loc, diag::err_tagless_friend_type_template)
9600 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00009601 return 0;
John McCall11083da2009-09-16 22:47:08 +00009602 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009603
John McCallaa74a0c2009-08-28 07:59:38 +00009604 // C++98 [class.friend]p1: A friend of a class is a function
9605 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00009606 // This is fixed in DR77, which just barely didn't make the C++03
9607 // deadline. It's also a very silly restriction that seriously
9608 // affects inner classes and which nobody else seems to implement;
9609 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00009610 //
9611 // But note that we could warn about it: it's always useless to
9612 // friend one of your own members (it's not, however, worthless to
9613 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00009614
John McCall11083da2009-09-16 22:47:08 +00009615 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009616 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00009617 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009618 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00009619 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00009620 TSI,
John McCall11083da2009-09-16 22:47:08 +00009621 DS.getFriendSpecLoc());
9622 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009623 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9624
9625 if (!D)
John McCall48871652010-08-21 09:40:31 +00009626 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009627
John McCall11083da2009-09-16 22:47:08 +00009628 D->setAccess(AS_public);
9629 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00009630
John McCall48871652010-08-21 09:40:31 +00009631 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00009632}
9633
John McCallde3fd222010-10-12 23:13:28 +00009634Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9635 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00009636 const DeclSpec &DS = D.getDeclSpec();
9637
9638 assert(DS.isFriendSpecified());
9639 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9640
9641 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00009642 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9643 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00009644
9645 // C++ [class.friend]p1
9646 // A friend of a class is a function or class....
9647 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00009648 // It *doesn't* see through dependent types, which is correct
9649 // according to [temp.arg.type]p3:
9650 // If a declaration acquires a function type through a
9651 // type dependent on a template-parameter and this causes
9652 // a declaration that does not use the syntactic form of a
9653 // function declarator to have a function type, the program
9654 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00009655 if (!T->isFunctionType()) {
9656 Diag(Loc, diag::err_unexpected_friend);
9657
9658 // It might be worthwhile to try to recover by creating an
9659 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00009660 return 0;
John McCall07e91c02009-08-06 02:15:43 +00009661 }
9662
9663 // C++ [namespace.memdef]p3
9664 // - If a friend declaration in a non-local class first declares a
9665 // class or function, the friend class or function is a member
9666 // of the innermost enclosing namespace.
9667 // - The name of the friend is not found by simple name lookup
9668 // until a matching declaration is provided in that namespace
9669 // scope (either before or after the class declaration granting
9670 // friendship).
9671 // - If a friend function is called, its name may be found by the
9672 // name lookup that considers functions from namespaces and
9673 // classes associated with the types of the function arguments.
9674 // - When looking for a prior declaration of a class or a function
9675 // declared as a friend, scopes outside the innermost enclosing
9676 // namespace scope are not considered.
9677
John McCallde3fd222010-10-12 23:13:28 +00009678 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009679 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9680 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00009681 assert(Name);
9682
Douglas Gregor6c110f32010-12-16 01:14:37 +00009683 // Check for unexpanded parameter packs.
9684 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9685 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9686 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9687 return 0;
9688
John McCall07e91c02009-08-06 02:15:43 +00009689 // The context we found the declaration in, or in which we should
9690 // create the declaration.
9691 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00009692 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009693 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00009694 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00009695
John McCallde3fd222010-10-12 23:13:28 +00009696 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00009697
John McCallde3fd222010-10-12 23:13:28 +00009698 // There are four cases here.
9699 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00009700 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00009701 // there as appropriate.
9702 // Recover from invalid scope qualifiers as if they just weren't there.
9703 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00009704 // C++0x [namespace.memdef]p3:
9705 // If the name in a friend declaration is neither qualified nor
9706 // a template-id and the declaration is a function or an
9707 // elaborated-type-specifier, the lookup to determine whether
9708 // the entity has been previously declared shall not consider
9709 // any scopes outside the innermost enclosing namespace.
9710 // C++0x [class.friend]p11:
9711 // If a friend declaration appears in a local class and the name
9712 // specified is an unqualified name, a prior declaration is
9713 // looked up without considering scopes that are outside the
9714 // innermost enclosing non-class scope. For a friend function
9715 // declaration, if there is no prior declaration, the program is
9716 // ill-formed.
9717 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00009718 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00009719
John McCallf7cfb222010-10-13 05:45:15 +00009720 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00009721 DC = CurContext;
9722 while (true) {
9723 // Skip class contexts. If someone can cite chapter and verse
9724 // for this behavior, that would be nice --- it's what GCC and
9725 // EDG do, and it seems like a reasonable intent, but the spec
9726 // really only says that checks for unqualified existing
9727 // declarations should stop at the nearest enclosing namespace,
9728 // not that they should only consider the nearest enclosing
9729 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009730 while (DC->isRecord())
9731 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00009732
John McCall1f82f242009-11-18 22:49:29 +00009733 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00009734
9735 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00009736 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00009737 break;
John McCallf7cfb222010-10-13 05:45:15 +00009738
John McCallf4776592010-10-14 22:22:28 +00009739 if (isTemplateId) {
9740 if (isa<TranslationUnitDecl>(DC)) break;
9741 } else {
9742 if (DC->isFileContext()) break;
9743 }
John McCall07e91c02009-08-06 02:15:43 +00009744 DC = DC->getParent();
9745 }
9746
9747 // C++ [class.friend]p1: A friend of a class is a function or
9748 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00009749 // C++0x changes this for both friend types and functions.
9750 // Most C++ 98 compilers do seem to give an error here, so
9751 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00009752 if (!Previous.empty() && DC->Equals(CurContext)
9753 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00009754 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00009755
John McCallccbc0322010-10-13 06:22:15 +00009756 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00009757
John McCallde3fd222010-10-12 23:13:28 +00009758 // - There's a non-dependent scope specifier, in which case we
9759 // compute it and do a previous lookup there for a function
9760 // or function template.
9761 } else if (!SS.getScopeRep()->isDependent()) {
9762 DC = computeDeclContext(SS);
9763 if (!DC) return 0;
9764
9765 if (RequireCompleteDeclContext(SS, DC)) return 0;
9766
9767 LookupQualifiedName(Previous, DC);
9768
9769 // Ignore things found implicitly in the wrong scope.
9770 // TODO: better diagnostics for this case. Suggesting the right
9771 // qualified scope would be nice...
9772 LookupResult::Filter F = Previous.makeFilter();
9773 while (F.hasNext()) {
9774 NamedDecl *D = F.next();
9775 if (!DC->InEnclosingNamespaceSetOf(
9776 D->getDeclContext()->getRedeclContext()))
9777 F.erase();
9778 }
9779 F.done();
9780
9781 if (Previous.empty()) {
9782 D.setInvalidType();
9783 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9784 return 0;
9785 }
9786
9787 // C++ [class.friend]p1: A friend of a class is a function or
9788 // class that is not a member of the class . . .
9789 if (DC->Equals(CurContext))
9790 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9791
9792 // - There's a scope specifier that does not match any template
9793 // parameter lists, in which case we use some arbitrary context,
9794 // create a method or method template, and wait for instantiation.
9795 // - There's a scope specifier that does match some template
9796 // parameter lists, which we don't handle right now.
9797 } else {
9798 DC = CurContext;
9799 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00009800 }
9801
John McCallf7cfb222010-10-13 05:45:15 +00009802 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00009803 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00009804 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9805 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9806 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00009807 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00009808 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9809 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00009810 return 0;
John McCall07e91c02009-08-06 02:15:43 +00009811 }
John McCall07e91c02009-08-06 02:15:43 +00009812 }
9813
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009814 bool Redeclaration = false;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00009815 bool AddToScope = true;
John McCallccbc0322010-10-13 06:22:15 +00009816 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00009817 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00009818 IsDefinition,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00009819 Redeclaration, AddToScope);
John McCall48871652010-08-21 09:40:31 +00009820 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00009821
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009822 assert(ND->getDeclContext() == DC);
9823 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00009824
John McCall759e32b2009-08-31 22:39:49 +00009825 // Add the function declaration to the appropriate lookup tables,
9826 // adjusting the redeclarations list as necessary. We don't
9827 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00009828 //
John McCall759e32b2009-08-31 22:39:49 +00009829 // Also update the scope-based lookup if the target context's
9830 // lookup context is in lexical scope.
9831 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00009832 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009833 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00009834 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009835 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00009836 }
John McCallaa74a0c2009-08-28 07:59:38 +00009837
9838 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009839 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00009840 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00009841 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00009842 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00009843
John McCallde3fd222010-10-12 23:13:28 +00009844 if (ND->isInvalidDecl())
9845 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00009846 else {
9847 FunctionDecl *FD;
9848 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9849 FD = FTD->getTemplatedDecl();
9850 else
9851 FD = cast<FunctionDecl>(ND);
9852
9853 // Mark templated-scope function declarations as unsupported.
9854 if (FD->getNumTemplateParameterLists())
9855 FrD->setUnsupportedFriend(true);
9856 }
John McCallde3fd222010-10-12 23:13:28 +00009857
John McCall48871652010-08-21 09:40:31 +00009858 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00009859}
9860
John McCall48871652010-08-21 09:40:31 +00009861void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9862 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00009863
Sebastian Redlf769df52009-03-24 22:27:57 +00009864 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9865 if (!Fn) {
9866 Diag(DelLoc, diag::err_deleted_non_function);
9867 return;
9868 }
9869 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9870 Diag(DelLoc, diag::err_deleted_decl_not_first);
9871 Diag(Prev->getLocation(), diag::note_previous_declaration);
9872 // If the declaration wasn't the first, we delete the function anyway for
9873 // recovery.
9874 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009875 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00009876}
Sebastian Redl4c018662009-04-27 21:33:24 +00009877
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009878void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9879 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9880
9881 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +00009882 if (MD->getParent()->isDependentType()) {
9883 MD->setDefaulted();
9884 MD->setExplicitlyDefaulted();
9885 return;
9886 }
9887
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009888 CXXSpecialMember Member = getSpecialMember(MD);
9889 if (Member == CXXInvalid) {
9890 Diag(DefaultLoc, diag::err_default_special_members);
9891 return;
9892 }
9893
9894 MD->setDefaulted();
9895 MD->setExplicitlyDefaulted();
9896
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009897 // If this definition appears within the record, do the checking when
9898 // the record is complete.
9899 const FunctionDecl *Primary = MD;
9900 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9901 // Find the uninstantiated declaration that actually had the '= default'
9902 // on it.
9903 MD->getTemplateInstantiationPattern()->isDefined(Primary);
9904
9905 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009906 return;
9907
9908 switch (Member) {
9909 case CXXDefaultConstructor: {
9910 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9911 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +00009912 if (!CD->isInvalidDecl())
9913 DefineImplicitDefaultConstructor(DefaultLoc, CD);
9914 break;
9915 }
9916
9917 case CXXCopyConstructor: {
9918 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9919 CheckExplicitlyDefaultedCopyConstructor(CD);
9920 if (!CD->isInvalidDecl())
9921 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009922 break;
9923 }
Alexis Huntf91729462011-05-12 22:46:25 +00009924
Alexis Huntc9a55732011-05-14 05:23:28 +00009925 case CXXCopyAssignment: {
9926 CheckExplicitlyDefaultedCopyAssignment(MD);
9927 if (!MD->isInvalidDecl())
9928 DefineImplicitCopyAssignment(DefaultLoc, MD);
9929 break;
9930 }
9931
Alexis Huntf91729462011-05-12 22:46:25 +00009932 case CXXDestructor: {
9933 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9934 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +00009935 if (!DD->isInvalidDecl())
9936 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +00009937 break;
9938 }
9939
Sebastian Redl22653ba2011-08-30 19:58:05 +00009940 case CXXMoveConstructor: {
9941 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9942 CheckExplicitlyDefaultedMoveConstructor(CD);
9943 if (!CD->isInvalidDecl())
9944 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +00009945 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009946 }
Alexis Hunt119c10e2011-05-25 23:16:36 +00009947
Sebastian Redl22653ba2011-08-30 19:58:05 +00009948 case CXXMoveAssignment: {
9949 CheckExplicitlyDefaultedMoveAssignment(MD);
9950 if (!MD->isInvalidDecl())
9951 DefineImplicitMoveAssignment(DefaultLoc, MD);
9952 break;
9953 }
9954
9955 case CXXInvalid:
9956 assert(false && "Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +00009957 break;
9958 }
9959 } else {
9960 Diag(DefaultLoc, diag::err_default_special_members);
9961 }
9962}
9963
Sebastian Redl4c018662009-04-27 21:33:24 +00009964static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00009965 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00009966 Stmt *SubStmt = *CI;
9967 if (!SubStmt)
9968 continue;
9969 if (isa<ReturnStmt>(SubStmt))
9970 Self.Diag(SubStmt->getSourceRange().getBegin(),
9971 diag::err_return_in_constructor_handler);
9972 if (!isa<Expr>(SubStmt))
9973 SearchForReturnInStmt(Self, SubStmt);
9974 }
9975}
9976
9977void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
9978 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
9979 CXXCatchStmt *Handler = TryBlock->getHandler(I);
9980 SearchForReturnInStmt(*this, Handler);
9981 }
9982}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00009983
Mike Stump11289f42009-09-09 15:08:12 +00009984bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00009985 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00009986 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
9987 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00009988
Chandler Carruth284bb2e2010-02-15 11:53:20 +00009989 if (Context.hasSameType(NewTy, OldTy) ||
9990 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00009991 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009992
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00009993 // Check if the return types are covariant
9994 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00009995
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00009996 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00009997 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
9998 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00009999 NewClassTy = NewPT->getPointeeType();
10000 OldClassTy = OldPT->getPointeeType();
10001 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010002 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10003 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10004 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10005 NewClassTy = NewRT->getPointeeType();
10006 OldClassTy = OldRT->getPointeeType();
10007 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010008 }
10009 }
Mike Stump11289f42009-09-09 15:08:12 +000010010
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010011 // The return types aren't either both pointers or references to a class type.
10012 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000010013 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010014 diag::err_different_return_type_for_overriding_virtual_function)
10015 << New->getDeclName() << NewTy << OldTy;
10016 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000010017
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010018 return true;
10019 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010020
Anders Carlssone60365b2009-12-31 18:34:24 +000010021 // C++ [class.virtual]p6:
10022 // If the return type of D::f differs from the return type of B::f, the
10023 // class type in the return type of D::f shall be complete at the point of
10024 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010025 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10026 if (!RT->isBeingDefined() &&
10027 RequireCompleteType(New->getLocation(), NewClassTy,
10028 PDiag(diag::err_covariant_return_incomplete)
10029 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000010030 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010031 }
Anders Carlssone60365b2009-12-31 18:34:24 +000010032
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000010033 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010034 // Check if the new class derives from the old class.
10035 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10036 Diag(New->getLocation(),
10037 diag::err_covariant_return_not_derived)
10038 << New->getDeclName() << NewTy << OldTy;
10039 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10040 return true;
10041 }
Mike Stump11289f42009-09-09 15:08:12 +000010042
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010043 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000010044 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000010045 diag::err_covariant_return_inaccessible_base,
10046 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10047 // FIXME: Should this point to the return type?
10048 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000010049 // FIXME: this note won't trigger for delayed access control
10050 // diagnostics, and it's impossible to get an undelayed error
10051 // here from access control during the original parse because
10052 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010053 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10054 return true;
10055 }
10056 }
Mike Stump11289f42009-09-09 15:08:12 +000010057
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010058 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010059 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010060 Diag(New->getLocation(),
10061 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010062 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010063 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10064 return true;
10065 };
Mike Stump11289f42009-09-09 15:08:12 +000010066
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010067
10068 // The new class type must have the same or less qualifiers as the old type.
10069 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10070 Diag(New->getLocation(),
10071 diag::err_covariant_return_type_class_type_more_qualified)
10072 << New->getDeclName() << NewTy << OldTy;
10073 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10074 return true;
10075 };
Mike Stump11289f42009-09-09 15:08:12 +000010076
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010077 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010078}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010079
Douglas Gregor21920e372009-12-01 17:24:26 +000010080/// \brief Mark the given method pure.
10081///
10082/// \param Method the method to be marked pure.
10083///
10084/// \param InitRange the source range that covers the "0" initializer.
10085bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010086 SourceLocation EndLoc = InitRange.getEnd();
10087 if (EndLoc.isValid())
10088 Method->setRangeEnd(EndLoc);
10089
Douglas Gregor21920e372009-12-01 17:24:26 +000010090 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10091 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000010092 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010093 }
Douglas Gregor21920e372009-12-01 17:24:26 +000010094
10095 if (!Method->isInvalidDecl())
10096 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10097 << Method->getDeclName() << InitRange;
10098 return true;
10099}
10100
John McCall1f4ee7b2009-12-19 09:28:58 +000010101/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10102/// an initializer for the out-of-line declaration 'Dcl'. The scope
10103/// is a fresh scope pushed for just this purpose.
10104///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010105/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10106/// static data member of class X, names should be looked up in the scope of
10107/// class X.
John McCall48871652010-08-21 09:40:31 +000010108void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010109 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010110 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010111
John McCall1f4ee7b2009-12-19 09:28:58 +000010112 // We should only get called for declarations with scope specifiers, like:
10113 // int foo::bar;
10114 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010115 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010116}
10117
10118/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000010119/// initializer for the out-of-line declaration 'D'.
10120void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010121 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010122 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010123
John McCall1f4ee7b2009-12-19 09:28:58 +000010124 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010125 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010126}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010127
10128/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10129/// C++ if/switch/while/for statement.
10130/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000010131DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010132 // C++ 6.4p2:
10133 // The declarator shall not specify a function or an array.
10134 // The type-specifier-seq shall not contain typedef and shall not declare a
10135 // new class or enumeration.
10136 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10137 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010138
10139 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010140 if (!Dcl)
10141 return true;
10142
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010143 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10144 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010145 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010146 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010147 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010148
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010149 return Dcl;
10150}
Anders Carlssonf98849e2009-12-02 17:15:43 +000010151
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010152void Sema::LoadExternalVTableUses() {
10153 if (!ExternalSource)
10154 return;
10155
10156 SmallVector<ExternalVTableUse, 4> VTables;
10157 ExternalSource->ReadUsedVTables(VTables);
10158 SmallVector<VTableUse, 4> NewUses;
10159 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10160 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10161 = VTablesUsed.find(VTables[I].Record);
10162 // Even if a definition wasn't required before, it may be required now.
10163 if (Pos != VTablesUsed.end()) {
10164 if (!Pos->second && VTables[I].DefinitionRequired)
10165 Pos->second = true;
10166 continue;
10167 }
10168
10169 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10170 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10171 }
10172
10173 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10174}
10175
Douglas Gregor88d292c2010-05-13 16:44:06 +000010176void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10177 bool DefinitionRequired) {
10178 // Ignore any vtable uses in unevaluated operands or for classes that do
10179 // not have a vtable.
10180 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10181 CurContext->isDependentContext() ||
10182 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +000010183 return;
10184
Douglas Gregor88d292c2010-05-13 16:44:06 +000010185 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010186 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010187 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10188 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10189 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10190 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000010191 // If we already had an entry, check to see if we are promoting this vtable
10192 // to required a definition. If so, we need to reappend to the VTableUses
10193 // list, since we may have already processed the first entry.
10194 if (DefinitionRequired && !Pos.first->second) {
10195 Pos.first->second = true;
10196 } else {
10197 // Otherwise, we can early exit.
10198 return;
10199 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010200 }
10201
10202 // Local classes need to have their virtual members marked
10203 // immediately. For all other classes, we mark their virtual members
10204 // at the end of the translation unit.
10205 if (Class->isLocalClass())
10206 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000010207 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000010208 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000010209}
10210
Douglas Gregor88d292c2010-05-13 16:44:06 +000010211bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010212 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010213 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000010214 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000010215
Douglas Gregor88d292c2010-05-13 16:44:06 +000010216 // Note: The VTableUses vector could grow as a result of marking
10217 // the members of a class as "used", so we check the size each
10218 // time through the loop and prefer indices (with are stable) to
10219 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000010220 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010221 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000010222 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010223 if (!Class)
10224 continue;
10225
10226 SourceLocation Loc = VTableUses[I].second;
10227
10228 // If this class has a key function, but that key function is
10229 // defined in another translation unit, we don't need to emit the
10230 // vtable even though we're using it.
10231 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010232 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000010233 switch (KeyFunction->getTemplateSpecializationKind()) {
10234 case TSK_Undeclared:
10235 case TSK_ExplicitSpecialization:
10236 case TSK_ExplicitInstantiationDeclaration:
10237 // The key function is in another translation unit.
10238 continue;
10239
10240 case TSK_ExplicitInstantiationDefinition:
10241 case TSK_ImplicitInstantiation:
10242 // We will be instantiating the key function.
10243 break;
10244 }
10245 } else if (!KeyFunction) {
10246 // If we have a class with no key function that is the subject
10247 // of an explicit instantiation declaration, suppress the
10248 // vtable; it will live with the explicit instantiation
10249 // definition.
10250 bool IsExplicitInstantiationDeclaration
10251 = Class->getTemplateSpecializationKind()
10252 == TSK_ExplicitInstantiationDeclaration;
10253 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10254 REnd = Class->redecls_end();
10255 R != REnd; ++R) {
10256 TemplateSpecializationKind TSK
10257 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10258 if (TSK == TSK_ExplicitInstantiationDeclaration)
10259 IsExplicitInstantiationDeclaration = true;
10260 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10261 IsExplicitInstantiationDeclaration = false;
10262 break;
10263 }
10264 }
10265
10266 if (IsExplicitInstantiationDeclaration)
10267 continue;
10268 }
10269
10270 // Mark all of the virtual members of this class as referenced, so
10271 // that we can build a vtable. Then, tell the AST consumer that a
10272 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000010273 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010274 MarkVirtualMembersReferenced(Loc, Class);
10275 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10276 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10277
10278 // Optionally warn if we're emitting a weak vtable.
10279 if (Class->getLinkage() == ExternalLinkage &&
10280 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010281 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +000010282 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10283 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000010284 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010285 VTableUses.clear();
10286
Douglas Gregor97509692011-04-22 22:25:37 +000010287 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000010288}
Anders Carlsson82fccd02009-12-07 08:24:59 +000010289
Rafael Espindola5b334082010-03-26 00:36:59 +000010290void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10291 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +000010292 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10293 e = RD->method_end(); i != e; ++i) {
10294 CXXMethodDecl *MD = *i;
10295
10296 // C++ [basic.def.odr]p2:
10297 // [...] A virtual member function is used if it is not pure. [...]
10298 if (MD->isVirtual() && !MD->isPure())
10299 MarkDeclarationReferenced(Loc, MD);
10300 }
Rafael Espindola5b334082010-03-26 00:36:59 +000010301
10302 // Only classes that have virtual bases need a VTT.
10303 if (RD->getNumVBases() == 0)
10304 return;
10305
10306 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10307 e = RD->bases_end(); i != e; ++i) {
10308 const CXXRecordDecl *Base =
10309 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000010310 if (Base->getNumVBases() == 0)
10311 continue;
10312 MarkVirtualMembersReferenced(Loc, Base);
10313 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000010314}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010315
10316/// SetIvarInitializers - This routine builds initialization ASTs for the
10317/// Objective-C implementation whose ivars need be initialized.
10318void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10319 if (!getLangOptions().CPlusPlus)
10320 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000010321 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010322 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010323 CollectIvarsToConstructOrDestruct(OID, ivars);
10324 if (ivars.empty())
10325 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010326 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010327 for (unsigned i = 0; i < ivars.size(); i++) {
10328 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000010329 if (Field->isInvalidDecl())
10330 continue;
10331
Alexis Hunt1d792652011-01-08 20:30:50 +000010332 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010333 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10334 InitializationKind InitKind =
10335 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10336
10337 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +000010338 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +000010339 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +000010340 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010341 // Note, MemberInit could actually come back empty if no initialization
10342 // is required (e.g., because it would call a trivial default constructor)
10343 if (!MemberInit.get() || MemberInit.isInvalid())
10344 continue;
John McCallacf0ee52010-10-08 02:01:28 +000010345
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010346 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000010347 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10348 SourceLocation(),
10349 MemberInit.takeAs<Expr>(),
10350 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010351 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000010352
10353 // Be sure that the destructor is accessible and is marked as referenced.
10354 if (const RecordType *RecordTy
10355 = Context.getBaseElementType(Field->getType())
10356 ->getAs<RecordType>()) {
10357 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000010358 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +000010359 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10360 CheckDestructorAccess(Field->getLocation(), Destructor,
10361 PDiag(diag::err_access_dtor_ivar)
10362 << Context.getBaseElementType(Field->getType()));
10363 }
10364 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010365 }
10366 ObjCImplementation->setIvarInitializers(Context,
10367 AllToInit.data(), AllToInit.size());
10368 }
10369}
Alexis Hunt6118d662011-05-04 05:57:24 +000010370
Alexis Hunt27a761d2011-05-04 23:29:54 +000010371static
10372void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10373 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10374 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10375 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10376 Sema &S) {
10377 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10378 CE = Current.end();
10379 if (Ctor->isInvalidDecl())
10380 return;
10381
10382 const FunctionDecl *FNTarget = 0;
10383 CXXConstructorDecl *Target;
10384
10385 // We ignore the result here since if we don't have a body, Target will be
10386 // null below.
10387 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10388 Target
10389= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10390
10391 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10392 // Avoid dereferencing a null pointer here.
10393 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10394
10395 if (!Current.insert(Canonical))
10396 return;
10397
10398 // We know that beyond here, we aren't chaining into a cycle.
10399 if (!Target || !Target->isDelegatingConstructor() ||
10400 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10401 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10402 Valid.insert(*CI);
10403 Current.clear();
10404 // We've hit a cycle.
10405 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10406 Current.count(TCanonical)) {
10407 // If we haven't diagnosed this cycle yet, do so now.
10408 if (!Invalid.count(TCanonical)) {
10409 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000010410 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000010411 << Ctor;
10412
10413 // Don't add a note for a function delegating directo to itself.
10414 if (TCanonical != Canonical)
10415 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10416
10417 CXXConstructorDecl *C = Target;
10418 while (C->getCanonicalDecl() != Canonical) {
10419 (void)C->getTargetConstructor()->hasBody(FNTarget);
10420 assert(FNTarget && "Ctor cycle through bodiless function");
10421
10422 C
10423 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10424 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10425 }
10426 }
10427
10428 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10429 Invalid.insert(*CI);
10430 Current.clear();
10431 } else {
10432 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10433 }
10434}
10435
10436
Alexis Hunt6118d662011-05-04 05:57:24 +000010437void Sema::CheckDelegatingCtorCycles() {
10438 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10439
Alexis Hunt27a761d2011-05-04 23:29:54 +000010440 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10441 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000010442
Douglas Gregorbae31202011-07-27 21:57:17 +000010443 for (DelegatingCtorDeclsType::iterator
10444 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000010445 E = DelegatingCtorDecls.end();
10446 I != E; ++I) {
10447 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +000010448 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000010449
10450 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10451 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000010452}