blob: 38bce96360c27e42949a29c95139c9649e21259a [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
Richard Smitheb3c10c2011-10-01 02:31:28 +0000505 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
506 // template has a constexpr specifier then all its declarations shall
507 // contain the constexpr specifier. [Note: An explicit specialization can
508 // differ from the template declaration with respect to the constexpr
509 // specifier. -- end note]
510 //
511 // FIXME: Don't reject changes in constexpr in explicit specializations.
512 if (New->isConstexpr() != Old->isConstexpr()) {
513 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
514 << New << New->isConstexpr();
515 Diag(Old->getLocation(), diag::note_previous_declaration);
516 Invalid = true;
517 }
518
Douglas Gregorf40863c2010-02-12 07:32:17 +0000519 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000520 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000521
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000522 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000523}
524
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000525/// \brief Merge the exception specifications of two variable declarations.
526///
527/// This is called when there's a redeclaration of a VarDecl. The function
528/// checks if the redeclaration might have an exception specification and
529/// validates compatibility and merges the specs if necessary.
530void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
531 // Shortcut if exceptions are disabled.
532 if (!getLangOptions().CXXExceptions)
533 return;
534
535 assert(Context.hasSameType(New->getType(), Old->getType()) &&
536 "Should only be called if types are otherwise the same.");
537
538 QualType NewType = New->getType();
539 QualType OldType = Old->getType();
540
541 // We're only interested in pointers and references to functions, as well
542 // as pointers to member functions.
543 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
544 NewType = R->getPointeeType();
545 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
546 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
547 NewType = P->getPointeeType();
548 OldType = OldType->getAs<PointerType>()->getPointeeType();
549 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
550 NewType = M->getPointeeType();
551 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
552 }
553
554 if (!NewType->isFunctionProtoType())
555 return;
556
557 // There's lots of special cases for functions. For function pointers, system
558 // libraries are hopefully not as broken so that we don't need these
559 // workarounds.
560 if (CheckEquivalentExceptionSpec(
561 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
562 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
563 New->setInvalidDecl();
564 }
565}
566
Chris Lattner199abbc2008-04-08 05:04:30 +0000567/// CheckCXXDefaultArguments - Verify that the default arguments for a
568/// function declaration are well-formed according to C++
569/// [dcl.fct.default].
570void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
571 unsigned NumParams = FD->getNumParams();
572 unsigned p;
573
574 // Find first parameter with a default argument
575 for (p = 0; p < NumParams; ++p) {
576 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000577 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000578 break;
579 }
580
581 // C++ [dcl.fct.default]p4:
582 // In a given function declaration, all parameters
583 // subsequent to a parameter with a default argument shall
584 // have default arguments supplied in this or previous
585 // declarations. A default argument shall not be redefined
586 // by a later declaration (not even to the same value).
587 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000588 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000589 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000590 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000591 if (Param->isInvalidDecl())
592 /* We already complained about this parameter. */;
593 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000594 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000595 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000596 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000597 else
Mike Stump11289f42009-09-09 15:08:12 +0000598 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000599 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000600
Chris Lattner199abbc2008-04-08 05:04:30 +0000601 LastMissingDefaultArg = p;
602 }
603 }
604
605 if (LastMissingDefaultArg > 0) {
606 // Some default arguments were missing. Clear out all of the
607 // default arguments up to (and including) the last missing
608 // default argument, so that we leave the function parameters
609 // in a semantically valid state.
610 for (p = 0; p <= LastMissingDefaultArg; ++p) {
611 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000612 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000613 Param->setDefaultArg(0);
614 }
615 }
616 }
617}
Douglas Gregor556877c2008-04-13 21:30:24 +0000618
Richard Smitheb3c10c2011-10-01 02:31:28 +0000619// CheckConstexprParameterTypes - Check whether a function's parameter types
620// are all literal types. If so, return true. If not, produce a suitable
621// diagnostic depending on @p CCK and return false.
622static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
623 Sema::CheckConstexprKind CCK) {
624 unsigned ArgIndex = 0;
625 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
626 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
627 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
628 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
629 SourceLocation ParamLoc = PD->getLocation();
630 if (!(*i)->isDependentType() &&
631 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
632 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
633 << ArgIndex+1 << PD->getSourceRange()
634 << isa<CXXConstructorDecl>(FD) :
635 SemaRef.PDiag(),
636 /*AllowIncompleteType*/ true)) {
637 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
638 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
639 << ArgIndex+1 << PD->getSourceRange()
640 << isa<CXXConstructorDecl>(FD) << *i;
641 return false;
642 }
643 }
644 return true;
645}
646
647// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
648// the requirements of a constexpr function declaration or a constexpr
649// constructor declaration. Return true if it does, false if not.
650//
651// This implements C++0x [dcl.constexpr]p3,4, as amended by N3308.
652//
653// \param CCK Specifies whether to produce diagnostics if the function does not
654// satisfy the requirements.
655bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
656 CheckConstexprKind CCK) {
657 assert((CCK != CCK_NoteNonConstexprInstantiation ||
658 (NewFD->getTemplateInstantiationPattern() &&
659 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
660 "only constexpr templates can be instantiated non-constexpr");
661
662 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(NewFD)) {
663 // C++0x [dcl.constexpr]p4:
664 // In the definition of a constexpr constructor, each of the parameter
665 // types shall be a literal type.
666 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
667 return false;
668
669 // In addition, either its function-body shall be = delete or = default or
670 // it shall satisfy the following constraints:
671 // - the class shall not have any virtual base classes;
672 const CXXRecordDecl *RD = CD->getParent();
673 if (RD->getNumVBases()) {
674 // Note, this is still illegal if the body is = default, since the
675 // implicit body does not satisfy the requirements of a constexpr
676 // constructor. We also reject cases where the body is = delete, as
677 // required by N3308.
678 if (CCK != CCK_Instantiation) {
679 Diag(NewFD->getLocation(),
680 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
681 : diag::note_constexpr_tmpl_virtual_base)
682 << RD->isStruct() << RD->getNumVBases();
683 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
684 E = RD->vbases_end(); I != E; ++I)
685 Diag(I->getSourceRange().getBegin(),
686 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
687 }
688 return false;
689 }
690 } else {
691 // C++0x [dcl.constexpr]p3:
692 // The definition of a constexpr function shall satisfy the following
693 // constraints:
694 // - it shall not be virtual;
695 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
696 if (Method && Method->isVirtual()) {
697 if (CCK != CCK_Instantiation) {
698 Diag(NewFD->getLocation(),
699 CCK == CCK_Declaration ? diag::err_constexpr_virtual
700 : diag::note_constexpr_tmpl_virtual);
701
702 // If it's not obvious why this function is virtual, find an overridden
703 // function which uses the 'virtual' keyword.
704 const CXXMethodDecl *WrittenVirtual = Method;
705 while (!WrittenVirtual->isVirtualAsWritten())
706 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
707 if (WrittenVirtual != Method)
708 Diag(WrittenVirtual->getLocation(),
709 diag::note_overridden_virtual_function);
710 }
711 return false;
712 }
713
714 // - its return type shall be a literal type;
715 QualType RT = NewFD->getResultType();
716 if (!RT->isDependentType() &&
717 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
718 PDiag(diag::err_constexpr_non_literal_return) :
719 PDiag(),
720 /*AllowIncompleteType*/ true)) {
721 if (CCK == CCK_NoteNonConstexprInstantiation)
722 Diag(NewFD->getLocation(),
723 diag::note_constexpr_tmpl_non_literal_return) << RT;
724 return false;
725 }
726
727 // - each of its parameter types shall be a literal type;
728 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
729 return false;
730 }
731
732 return true;
733}
734
735/// Check the given declaration statement is legal within a constexpr function
736/// body. C++0x [dcl.constexpr]p3,p4.
737///
738/// \return true if the body is OK, false if we have diagnosed a problem.
739static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
740 DeclStmt *DS) {
741 // C++0x [dcl.constexpr]p3 and p4:
742 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
743 // contain only
744 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
745 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
746 switch ((*DclIt)->getKind()) {
747 case Decl::StaticAssert:
748 case Decl::Using:
749 case Decl::UsingShadow:
750 case Decl::UsingDirective:
751 case Decl::UnresolvedUsingTypename:
752 // - static_assert-declarations
753 // - using-declarations,
754 // - using-directives,
755 continue;
756
757 case Decl::Typedef:
758 case Decl::TypeAlias: {
759 // - typedef declarations and alias-declarations that do not define
760 // classes or enumerations,
761 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
762 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
763 // Don't allow variably-modified types in constexpr functions.
764 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
765 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
766 << TL.getSourceRange() << TL.getType()
767 << isa<CXXConstructorDecl>(Dcl);
768 return false;
769 }
770 continue;
771 }
772
773 case Decl::Enum:
774 case Decl::CXXRecord:
775 // As an extension, we allow the declaration (but not the definition) of
776 // classes and enumerations in all declarations, not just in typedef and
777 // alias declarations.
778 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
779 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
780 << isa<CXXConstructorDecl>(Dcl);
781 return false;
782 }
783 continue;
784
785 case Decl::Var:
786 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
787 << isa<CXXConstructorDecl>(Dcl);
788 return false;
789
790 default:
791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794 }
795 }
796
797 return true;
798}
799
800/// Check that the given field is initialized within a constexpr constructor.
801///
802/// \param Dcl The constexpr constructor being checked.
803/// \param Field The field being checked. This may be a member of an anonymous
804/// struct or union nested within the class being checked.
805/// \param Inits All declarations, including anonymous struct/union members and
806/// indirect members, for which any initialization was provided.
807/// \param Diagnosed Set to true if an error is produced.
808static void CheckConstexprCtorInitializer(Sema &SemaRef,
809 const FunctionDecl *Dcl,
810 FieldDecl *Field,
811 llvm::SmallSet<Decl*, 16> &Inits,
812 bool &Diagnosed) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000813 if (Field->isUnnamedBitfield())
814 return;
815
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816 if (!Inits.count(Field)) {
817 if (!Diagnosed) {
818 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
819 Diagnosed = true;
820 }
821 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
822 } else if (Field->isAnonymousStructOrUnion()) {
823 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
824 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
825 I != E; ++I)
826 // If an anonymous union contains an anonymous struct of which any member
827 // is initialized, all members must be initialized.
828 if (!RD->isUnion() || Inits.count(*I))
829 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
830 }
831}
832
833/// Check the body for the given constexpr function declaration only contains
834/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
835///
836/// \return true if the body is OK, false if we have diagnosed a problem.
837bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
838 if (isa<CXXTryStmt>(Body)) {
839 // C++0x [dcl.constexpr]p3:
840 // The definition of a constexpr function shall satisfy the following
841 // constraints: [...]
842 // - its function-body shall be = delete, = default, or a
843 // compound-statement
844 //
845 // C++0x [dcl.constexpr]p4:
846 // In the definition of a constexpr constructor, [...]
847 // - its function-body shall not be a function-try-block;
848 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
849 << isa<CXXConstructorDecl>(Dcl);
850 return false;
851 }
852
853 // - its function-body shall be [...] a compound-statement that contains only
854 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
855
856 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
857 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
858 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
859 switch ((*BodyIt)->getStmtClass()) {
860 case Stmt::NullStmtClass:
861 // - null statements,
862 continue;
863
864 case Stmt::DeclStmtClass:
865 // - static_assert-declarations
866 // - using-declarations,
867 // - using-directives,
868 // - typedef declarations and alias-declarations that do not define
869 // classes or enumerations,
870 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
871 return false;
872 continue;
873
874 case Stmt::ReturnStmtClass:
875 // - and exactly one return statement;
876 if (isa<CXXConstructorDecl>(Dcl))
877 break;
878
879 ReturnStmts.push_back((*BodyIt)->getLocStart());
880 // FIXME
881 // - every constructor call and implicit conversion used in initializing
882 // the return value shall be one of those allowed in a constant
883 // expression.
884 // Deal with this as part of a general check that the function can produce
885 // a constant expression (for [dcl.constexpr]p5).
886 continue;
887
888 default:
889 break;
890 }
891
892 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
893 << isa<CXXConstructorDecl>(Dcl);
894 return false;
895 }
896
897 if (const CXXConstructorDecl *Constructor
898 = dyn_cast<CXXConstructorDecl>(Dcl)) {
899 const CXXRecordDecl *RD = Constructor->getParent();
900 // - every non-static data member and base class sub-object shall be
901 // initialized;
902 if (RD->isUnion()) {
903 // DR1359: Exactly one member of a union shall be initialized.
904 if (Constructor->getNumCtorInitializers() == 0) {
905 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
906 return false;
907 }
Richard Smithf368fb42011-10-10 16:38:04 +0000908 } else if (!Constructor->isDependentContext() &&
909 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000910 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
911
912 // Skip detailed checking if we have enough initializers, and we would
913 // allow at most one initializer per member.
914 bool AnyAnonStructUnionMembers = false;
915 unsigned Fields = 0;
916 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
917 E = RD->field_end(); I != E; ++I, ++Fields) {
918 if ((*I)->isAnonymousStructOrUnion()) {
919 AnyAnonStructUnionMembers = true;
920 break;
921 }
922 }
923 if (AnyAnonStructUnionMembers ||
924 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
925 // Check initialization of non-static data members. Base classes are
926 // always initialized so do not need to be checked. Dependent bases
927 // might not have initializers in the member initializer list.
928 llvm::SmallSet<Decl*, 16> Inits;
929 for (CXXConstructorDecl::init_const_iterator
930 I = Constructor->init_begin(), E = Constructor->init_end();
931 I != E; ++I) {
932 if (FieldDecl *FD = (*I)->getMember())
933 Inits.insert(FD);
934 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
935 Inits.insert(ID->chain_begin(), ID->chain_end());
936 }
937
938 bool Diagnosed = false;
939 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
940 E = RD->field_end(); I != E; ++I)
941 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
942 if (Diagnosed)
943 return false;
944 }
945 }
946
947 // FIXME
948 // - every constructor involved in initializing non-static data members
949 // and base class sub-objects shall be a constexpr constructor;
950 // - every assignment-expression that is an initializer-clause appearing
951 // directly or indirectly within a brace-or-equal-initializer for
952 // a non-static data member that is not named by a mem-initializer-id
953 // shall be a constant expression; and
954 // - every implicit conversion used in converting a constructor argument
955 // to the corresponding parameter type and converting
956 // a full-expression to the corresponding member type shall be one of
957 // those allowed in a constant expression.
958 // Deal with these as part of a general check that the function can produce
959 // a constant expression (for [dcl.constexpr]p5).
960 } else {
961 if (ReturnStmts.empty()) {
962 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
963 return false;
964 }
965 if (ReturnStmts.size() > 1) {
966 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
967 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
968 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
969 return false;
970 }
971 }
972
973 return true;
974}
975
Douglas Gregor61956c42008-10-31 09:07:45 +0000976/// isCurrentClassName - Determine whether the identifier II is the
977/// name of the class type currently being defined. In the case of
978/// nested classes, this will only return true if II is the name of
979/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000980bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
981 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000982 assert(getLangOptions().CPlusPlus && "No class names in C!");
983
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000984 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000985 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000986 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000987 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
988 } else
989 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
990
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000991 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000992 return &II == CurDecl->getIdentifier();
993 else
994 return false;
995}
996
Mike Stump11289f42009-09-09 15:08:12 +0000997/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000998///
999/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1000/// and returns NULL otherwise.
1001CXXBaseSpecifier *
1002Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1003 SourceRange SpecifierRange,
1004 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001005 TypeSourceInfo *TInfo,
1006 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001007 QualType BaseType = TInfo->getType();
1008
Douglas Gregor463421d2009-03-03 04:44:36 +00001009 // C++ [class.union]p1:
1010 // A union shall not have base classes.
1011 if (Class->isUnion()) {
1012 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1013 << SpecifierRange;
1014 return 0;
1015 }
1016
Douglas Gregor752a5952011-01-03 22:36:02 +00001017 if (EllipsisLoc.isValid() &&
1018 !TInfo->getType()->containsUnexpandedParameterPack()) {
1019 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1020 << TInfo->getTypeLoc().getSourceRange();
1021 EllipsisLoc = SourceLocation();
1022 }
1023
Douglas Gregor463421d2009-03-03 04:44:36 +00001024 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +00001025 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001026 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001027 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001028
1029 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +00001030
1031 // Base specifiers must be record types.
1032 if (!BaseType->isRecordType()) {
1033 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1034 return 0;
1035 }
1036
1037 // C++ [class.union]p1:
1038 // A union shall not be used as a base class.
1039 if (BaseType->isUnionType()) {
1040 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1041 return 0;
1042 }
1043
1044 // C++ [class.derived]p2:
1045 // The class-name in a base-specifier shall not be an incompletely
1046 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001047 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00001048 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +00001049 << SpecifierRange)) {
1050 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001051 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001052 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001053
Eli Friedmanc96d4962009-08-15 21:55:26 +00001054 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001055 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001056 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001057 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001058 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +00001059 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1060 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001061
Anders Carlsson65c76d32011-03-25 14:55:14 +00001062 // C++ [class]p3:
1063 // If a class is marked final and it appears as a base-type-specifier in
1064 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +00001065 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001066 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1067 << CXXBaseDecl->getDeclName();
1068 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1069 << CXXBaseDecl->getDeclName();
1070 return 0;
1071 }
1072
John McCall3696dcb2010-08-17 07:23:57 +00001073 if (BaseDecl->isInvalidDecl())
1074 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001075
1076 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001077 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001078 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001079 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001080}
1081
Douglas Gregor556877c2008-04-13 21:30:24 +00001082/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1083/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001084/// example:
1085/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001086/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001087BaseResult
John McCall48871652010-08-21 09:40:31 +00001088Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +00001089 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001090 ParsedType basetype, SourceLocation BaseLoc,
1091 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001092 if (!classdecl)
1093 return true;
1094
Douglas Gregorc40290e2009-03-09 23:48:35 +00001095 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001096 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001097 if (!Class)
1098 return true;
1099
Nick Lewycky19b9f952010-07-26 16:56:01 +00001100 TypeSourceInfo *TInfo = 0;
1101 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001102
Douglas Gregor752a5952011-01-03 22:36:02 +00001103 if (EllipsisLoc.isInvalid() &&
1104 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001105 UPPC_BaseType))
1106 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001107
Douglas Gregor463421d2009-03-03 04:44:36 +00001108 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001109 Virtual, Access, TInfo,
1110 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001111 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +00001112
Douglas Gregor463421d2009-03-03 04:44:36 +00001113 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001114}
Douglas Gregor556877c2008-04-13 21:30:24 +00001115
Douglas Gregor463421d2009-03-03 04:44:36 +00001116/// \brief Performs the actual work of attaching the given base class
1117/// specifiers to a C++ class.
1118bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1119 unsigned NumBases) {
1120 if (NumBases == 0)
1121 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001122
1123 // Used to keep track of which base types we have already seen, so
1124 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001125 // that the key is always the unqualified canonical type of the base
1126 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001127 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1128
1129 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001130 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001131 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001132 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001133 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001134 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001135 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor29a92472008-10-22 17:49:05 +00001136 if (KnownBaseTypes[NewBaseType]) {
1137 // C++ [class.mi]p3:
1138 // A class shall not be specified as a direct base class of a
1139 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +00001140 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001141 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001142 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001143 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001144
1145 // Delete the duplicate base class specifier; we're going to
1146 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001147 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001148
1149 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001150 } else {
1151 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +00001152 KnownBaseTypes[NewBaseType] = Bases[idx];
1153 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +00001154 }
1155 }
1156
1157 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001158 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001159
1160 // Delete the remaining (good) base class specifiers, since their
1161 // data has been copied into the CXXRecordDecl.
1162 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001163 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001164
1165 return Invalid;
1166}
1167
1168/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1169/// class, after checking whether there are any duplicate base
1170/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001171void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001172 unsigned NumBases) {
1173 if (!ClassDecl || !Bases || !NumBases)
1174 return;
1175
1176 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +00001177 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +00001178 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001179}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001180
John McCalle78aac42010-03-10 03:28:59 +00001181static CXXRecordDecl *GetClassForType(QualType T) {
1182 if (const RecordType *RT = T->getAs<RecordType>())
1183 return cast<CXXRecordDecl>(RT->getDecl());
1184 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1185 return ICT->getDecl();
1186 else
1187 return 0;
1188}
1189
Douglas Gregor36d1b142009-10-06 17:59:45 +00001190/// \brief Determine whether the type \p Derived is a C++ class that is
1191/// derived from the type \p Base.
1192bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1193 if (!getLangOptions().CPlusPlus)
1194 return false;
John McCalle78aac42010-03-10 03:28:59 +00001195
1196 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1197 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001198 return false;
1199
John McCalle78aac42010-03-10 03:28:59 +00001200 CXXRecordDecl *BaseRD = GetClassForType(Base);
1201 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001202 return false;
1203
John McCall67da35c2010-02-04 22:26:26 +00001204 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1205 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001206}
1207
1208/// \brief Determine whether the type \p Derived is a C++ class that is
1209/// derived from the type \p Base.
1210bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1211 if (!getLangOptions().CPlusPlus)
1212 return false;
1213
John McCalle78aac42010-03-10 03:28:59 +00001214 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1215 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001216 return false;
1217
John McCalle78aac42010-03-10 03:28:59 +00001218 CXXRecordDecl *BaseRD = GetClassForType(Base);
1219 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001220 return false;
1221
Douglas Gregor36d1b142009-10-06 17:59:45 +00001222 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1223}
1224
Anders Carlssona70cff62010-04-24 19:06:50 +00001225void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001226 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001227 assert(BasePathArray.empty() && "Base path array must be empty!");
1228 assert(Paths.isRecordingPaths() && "Must record paths!");
1229
1230 const CXXBasePath &Path = Paths.front();
1231
1232 // We first go backward and check if we have a virtual base.
1233 // FIXME: It would be better if CXXBasePath had the base specifier for
1234 // the nearest virtual base.
1235 unsigned Start = 0;
1236 for (unsigned I = Path.size(); I != 0; --I) {
1237 if (Path[I - 1].Base->isVirtual()) {
1238 Start = I - 1;
1239 break;
1240 }
1241 }
1242
1243 // Now add all bases.
1244 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001245 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001246}
1247
Douglas Gregor88d292c2010-05-13 16:44:06 +00001248/// \brief Determine whether the given base path includes a virtual
1249/// base class.
John McCallcf142162010-08-07 06:22:56 +00001250bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1251 for (CXXCastPath::const_iterator B = BasePath.begin(),
1252 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001253 B != BEnd; ++B)
1254 if ((*B)->isVirtual())
1255 return true;
1256
1257 return false;
1258}
1259
Douglas Gregor36d1b142009-10-06 17:59:45 +00001260/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1261/// conversion (where Derived and Base are class types) is
1262/// well-formed, meaning that the conversion is unambiguous (and
1263/// that all of the base classes are accessible). Returns true
1264/// and emits a diagnostic if the code is ill-formed, returns false
1265/// otherwise. Loc is the location where this routine should point to
1266/// if there is an error, and Range is the source range to highlight
1267/// if there is an error.
1268bool
1269Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001270 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001271 unsigned AmbigiousBaseConvID,
1272 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001273 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001274 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001275 // First, determine whether the path from Derived to Base is
1276 // ambiguous. This is slightly more expensive than checking whether
1277 // the Derived to Base conversion exists, because here we need to
1278 // explore multiple paths to determine if there is an ambiguity.
1279 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1280 /*DetectVirtual=*/false);
1281 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1282 assert(DerivationOkay &&
1283 "Can only be used with a derived-to-base conversion");
1284 (void)DerivationOkay;
1285
1286 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001287 if (InaccessibleBaseID) {
1288 // Check that the base class can be accessed.
1289 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1290 InaccessibleBaseID)) {
1291 case AR_inaccessible:
1292 return true;
1293 case AR_accessible:
1294 case AR_dependent:
1295 case AR_delayed:
1296 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001297 }
John McCall5b0829a2010-02-10 09:31:12 +00001298 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001299
1300 // Build a base path if necessary.
1301 if (BasePath)
1302 BuildBasePathArray(Paths, *BasePath);
1303 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001304 }
1305
1306 // We know that the derived-to-base conversion is ambiguous, and
1307 // we're going to produce a diagnostic. Perform the derived-to-base
1308 // search just one more time to compute all of the possible paths so
1309 // that we can print them out. This is more expensive than any of
1310 // the previous derived-to-base checks we've done, but at this point
1311 // performance isn't as much of an issue.
1312 Paths.clear();
1313 Paths.setRecordingPaths(true);
1314 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1315 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1316 (void)StillOkay;
1317
1318 // Build up a textual representation of the ambiguous paths, e.g.,
1319 // D -> B -> A, that will be used to illustrate the ambiguous
1320 // conversions in the diagnostic. We only print one of the paths
1321 // to each base class subobject.
1322 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1323
1324 Diag(Loc, AmbigiousBaseConvID)
1325 << Derived << Base << PathDisplayStr << Range << Name;
1326 return true;
1327}
1328
1329bool
1330Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001331 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001332 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001333 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001334 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001335 IgnoreAccess ? 0
1336 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001337 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001338 Loc, Range, DeclarationName(),
1339 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001340}
1341
1342
1343/// @brief Builds a string representing ambiguous paths from a
1344/// specific derived class to different subobjects of the same base
1345/// class.
1346///
1347/// This function builds a string that can be used in error messages
1348/// to show the different paths that one can take through the
1349/// inheritance hierarchy to go from the derived class to different
1350/// subobjects of a base class. The result looks something like this:
1351/// @code
1352/// struct D -> struct B -> struct A
1353/// struct D -> struct C -> struct A
1354/// @endcode
1355std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1356 std::string PathDisplayStr;
1357 std::set<unsigned> DisplayedPaths;
1358 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1359 Path != Paths.end(); ++Path) {
1360 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1361 // We haven't displayed a path to this particular base
1362 // class subobject yet.
1363 PathDisplayStr += "\n ";
1364 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1365 for (CXXBasePath::const_iterator Element = Path->begin();
1366 Element != Path->end(); ++Element)
1367 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1368 }
1369 }
1370
1371 return PathDisplayStr;
1372}
1373
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001374//===----------------------------------------------------------------------===//
1375// C++ class member Handling
1376//===----------------------------------------------------------------------===//
1377
Abramo Bagnarad7340582010-06-05 05:09:32 +00001378/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001379bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1380 SourceLocation ASLoc,
1381 SourceLocation ColonLoc,
1382 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001383 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001384 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001385 ASLoc, ColonLoc);
1386 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001387 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001388}
1389
Anders Carlssonfd835532011-01-20 05:57:14 +00001390/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001391void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001392 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfd835532011-01-20 05:57:14 +00001393 if (!MD || !MD->isVirtual())
1394 return;
1395
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001396 if (MD->isDependentContext())
1397 return;
1398
Anders Carlssonfd835532011-01-20 05:57:14 +00001399 // C++0x [class.virtual]p3:
1400 // If a virtual function is marked with the virt-specifier override and does
1401 // not override a member function of a base class,
1402 // the program is ill-formed.
1403 bool HasOverriddenMethods =
1404 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001405 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001406 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001407 diag::err_function_marked_override_not_overriding)
1408 << MD->getDeclName();
1409 return;
1410 }
1411}
1412
Anders Carlsson3f610c72011-01-20 16:25:36 +00001413/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1414/// function overrides a virtual member function marked 'final', according to
1415/// C++0x [class.virtual]p3.
1416bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1417 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001418 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001419 return false;
1420
1421 Diag(New->getLocation(), diag::err_final_function_overridden)
1422 << New->getDeclName();
1423 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1424 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001425}
1426
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001427/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1428/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001429/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1430/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1431/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001432Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001433Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001434 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001435 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001436 bool HasDeferredInit) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001437 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001438 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1439 DeclarationName Name = NameInfo.getName();
1440 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001441
1442 // For anonymous bitfields, the location should point to the type.
1443 if (Loc.isInvalid())
1444 Loc = D.getSourceRange().getBegin();
1445
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001446 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001447
John McCallb1cd7da2010-06-04 08:34:12 +00001448 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001449 assert(!DS.isFriendSpecified());
1450
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001451 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001452
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001453 // C++ 9.2p6: A member shall not be declared to have automatic storage
1454 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001455 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1456 // data members and cannot be applied to names declared const or static,
1457 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001458 switch (DS.getStorageClassSpec()) {
1459 case DeclSpec::SCS_unspecified:
1460 case DeclSpec::SCS_typedef:
1461 case DeclSpec::SCS_static:
1462 // FALL THROUGH.
1463 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001464 case DeclSpec::SCS_mutable:
1465 if (isFunc) {
1466 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001467 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001468 else
Chris Lattner3b054132008-11-19 05:08:23 +00001469 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001470
Sebastian Redl8071edb2008-11-17 23:24:37 +00001471 // FIXME: It would be nicer if the keyword was ignored only for this
1472 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001473 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001474 }
1475 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001476 default:
1477 if (DS.getStorageClassSpecLoc().isValid())
1478 Diag(DS.getStorageClassSpecLoc(),
1479 diag::err_storageclass_invalid_for_member);
1480 else
1481 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1482 D.getMutableDeclSpec().ClearStorageClassSpecs();
1483 }
1484
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001485 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1486 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001487 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001488
1489 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001490 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001491 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001492
1493 // Data members must have identifiers for names.
1494 if (Name.getNameKind() != DeclarationName::Identifier) {
1495 Diag(Loc, diag::err_bad_variable_name)
1496 << Name;
1497 return 0;
1498 }
Douglas Gregora007d362010-10-13 22:19:53 +00001499
Douglas Gregor7c26c042011-09-21 14:40:46 +00001500 IdentifierInfo *II = Name.getAsIdentifierInfo();
1501
1502 // Member field could not be with "template" keyword.
1503 // So TemplateParameterLists should be empty in this case.
1504 if (TemplateParameterLists.size()) {
1505 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1506 if (TemplateParams->size()) {
1507 // There is no such thing as a member field template.
1508 Diag(D.getIdentifierLoc(), diag::err_template_member)
1509 << II
1510 << SourceRange(TemplateParams->getTemplateLoc(),
1511 TemplateParams->getRAngleLoc());
1512 } else {
1513 // There is an extraneous 'template<>' for this member.
1514 Diag(TemplateParams->getTemplateLoc(),
1515 diag::err_template_member_noparams)
1516 << II
1517 << SourceRange(TemplateParams->getTemplateLoc(),
1518 TemplateParams->getRAngleLoc());
1519 }
1520 return 0;
1521 }
1522
Douglas Gregora007d362010-10-13 22:19:53 +00001523 if (SS.isSet() && !SS.isInvalid()) {
1524 // The user provided a superfluous scope specifier inside a class
1525 // definition:
1526 //
1527 // class X {
1528 // int X::member;
1529 // };
1530 DeclContext *DC = 0;
1531 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1532 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1533 << Name << FixItHint::CreateRemoval(SS.getRange());
1534 else
1535 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1536 << Name << SS.getRange();
1537
1538 SS.clear();
1539 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001540
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001541 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001542 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001543 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001544 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001545 assert(!HasDeferredInit);
1546
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001547 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner97e277e2009-03-05 23:03:49 +00001548 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001549 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001550 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001551
1552 // Non-instance-fields can't have a bitfield.
1553 if (BitWidth) {
1554 if (Member->isInvalidDecl()) {
1555 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001556 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001557 // C++ 9.6p3: A bit-field shall not be a static member.
1558 // "static member 'A' cannot be a bit-field"
1559 Diag(Loc, diag::err_static_not_bitfield)
1560 << Name << BitWidth->getSourceRange();
1561 } else if (isa<TypedefDecl>(Member)) {
1562 // "typedef member 'x' cannot be a bit-field"
1563 Diag(Loc, diag::err_typedef_not_bitfield)
1564 << Name << BitWidth->getSourceRange();
1565 } else {
1566 // A function typedef ("typedef int f(); f a;").
1567 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1568 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001569 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001570 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001571 }
Mike Stump11289f42009-09-09 15:08:12 +00001572
Chris Lattnerd26760a2009-03-05 23:01:03 +00001573 BitWidth = 0;
1574 Member->setInvalidDecl();
1575 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001576
1577 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001578
Douglas Gregor3447e762009-08-20 22:52:58 +00001579 // If we have declared a member function template, set the access of the
1580 // templated declaration as well.
1581 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1582 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001583 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001584
Anders Carlsson13a69102011-01-20 04:34:22 +00001585 if (VS.isOverrideSpecified()) {
1586 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1587 if (!MD || !MD->isVirtual()) {
1588 Diag(Member->getLocStart(),
1589 diag::override_keyword_only_allowed_on_virtual_member_functions)
1590 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001591 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001592 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001593 }
1594 if (VS.isFinalSpecified()) {
1595 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1596 if (!MD || !MD->isVirtual()) {
1597 Diag(Member->getLocStart(),
1598 diag::override_keyword_only_allowed_on_virtual_member_functions)
1599 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001600 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001601 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001602 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001603
Douglas Gregorf2f08062011-03-08 17:10:18 +00001604 if (VS.getLastLocation().isValid()) {
1605 // Update the end location of a method that has a virt-specifiers.
1606 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1607 MD->setRangeEnd(VS.getLastLocation());
1608 }
1609
Anders Carlssonc87f8612011-01-20 06:29:02 +00001610 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001611
Douglas Gregor92751d42008-11-17 22:58:34 +00001612 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001613
John McCall25849ca2011-02-15 07:12:36 +00001614 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001615 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001616 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001617}
1618
Richard Smith938f40b2011-06-11 17:19:42 +00001619/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00001620/// in-class initializer for a non-static C++ class member, and after
1621/// instantiating an in-class initializer in a class template. Such actions
1622/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00001623void
1624Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1625 Expr *InitExpr) {
1626 FieldDecl *FD = cast<FieldDecl>(D);
1627
1628 if (!InitExpr) {
1629 FD->setInvalidDecl();
1630 FD->removeInClassInitializer();
1631 return;
1632 }
1633
1634 ExprResult Init = InitExpr;
1635 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1636 // FIXME: if there is no EqualLoc, this is list-initialization.
1637 Init = PerformCopyInitialization(
1638 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1639 if (Init.isInvalid()) {
1640 FD->setInvalidDecl();
1641 return;
1642 }
1643
1644 CheckImplicitConversions(Init.get(), EqualLoc);
1645 }
1646
1647 // C++0x [class.base.init]p7:
1648 // The initialization of each base and member constitutes a
1649 // full-expression.
1650 Init = MaybeCreateExprWithCleanups(Init);
1651 if (Init.isInvalid()) {
1652 FD->setInvalidDecl();
1653 return;
1654 }
1655
1656 InitExpr = Init.release();
1657
1658 FD->setInClassInitializer(InitExpr);
1659}
1660
Douglas Gregor15e77a22009-12-31 09:10:24 +00001661/// \brief Find the direct and/or virtual base specifiers that
1662/// correspond to the given base type, for use in base initialization
1663/// within a constructor.
1664static bool FindBaseInitializer(Sema &SemaRef,
1665 CXXRecordDecl *ClassDecl,
1666 QualType BaseType,
1667 const CXXBaseSpecifier *&DirectBaseSpec,
1668 const CXXBaseSpecifier *&VirtualBaseSpec) {
1669 // First, check for a direct base class.
1670 DirectBaseSpec = 0;
1671 for (CXXRecordDecl::base_class_const_iterator Base
1672 = ClassDecl->bases_begin();
1673 Base != ClassDecl->bases_end(); ++Base) {
1674 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1675 // We found a direct base of this type. That's what we're
1676 // initializing.
1677 DirectBaseSpec = &*Base;
1678 break;
1679 }
1680 }
1681
1682 // Check for a virtual base class.
1683 // FIXME: We might be able to short-circuit this if we know in advance that
1684 // there are no virtual bases.
1685 VirtualBaseSpec = 0;
1686 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1687 // We haven't found a base yet; search the class hierarchy for a
1688 // virtual base class.
1689 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1690 /*DetectVirtual=*/false);
1691 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1692 BaseType, Paths)) {
1693 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1694 Path != Paths.end(); ++Path) {
1695 if (Path->back().Base->isVirtual()) {
1696 VirtualBaseSpec = Path->back().Base;
1697 break;
1698 }
1699 }
1700 }
1701 }
1702
1703 return DirectBaseSpec || VirtualBaseSpec;
1704}
1705
Sebastian Redla74948d2011-09-24 17:48:25 +00001706/// \brief Handle a C++ member initializer using braced-init-list syntax.
1707MemInitResult
1708Sema::ActOnMemInitializer(Decl *ConstructorD,
1709 Scope *S,
1710 CXXScopeSpec &SS,
1711 IdentifierInfo *MemberOrBase,
1712 ParsedType TemplateTypeTy,
1713 SourceLocation IdLoc,
1714 Expr *InitList,
1715 SourceLocation EllipsisLoc) {
1716 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1717 IdLoc, MultiInitializer(InitList), EllipsisLoc);
1718}
1719
1720/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00001721MemInitResult
John McCall48871652010-08-21 09:40:31 +00001722Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001723 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001724 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001725 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001726 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001727 SourceLocation IdLoc,
1728 SourceLocation LParenLoc,
Richard Trieu2bd04012011-09-09 02:00:50 +00001729 Expr **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001730 SourceLocation RParenLoc,
1731 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00001732 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1733 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs,
1734 RParenLoc),
1735 EllipsisLoc);
1736}
1737
1738/// \brief Handle a C++ member initializer.
1739MemInitResult
1740Sema::BuildMemInitializer(Decl *ConstructorD,
1741 Scope *S,
1742 CXXScopeSpec &SS,
1743 IdentifierInfo *MemberOrBase,
1744 ParsedType TemplateTypeTy,
1745 SourceLocation IdLoc,
1746 const MultiInitializer &Args,
1747 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001748 if (!ConstructorD)
1749 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001750
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001751 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001752
1753 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001754 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001755 if (!Constructor) {
1756 // The user wrote a constructor initializer on a function that is
1757 // not a C++ constructor. Ignore the error for now, because we may
1758 // have more member initializers coming; we'll diagnose it just
1759 // once in ActOnMemInitializers.
1760 return true;
1761 }
1762
1763 CXXRecordDecl *ClassDecl = Constructor->getParent();
1764
1765 // C++ [class.base.init]p2:
1766 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001767 // constructor's class and, if not found in that scope, are looked
1768 // up in the scope containing the constructor's definition.
1769 // [Note: if the constructor's class contains a member with the
1770 // same name as a direct or virtual base class of the class, a
1771 // mem-initializer-id naming the member or base class and composed
1772 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001773 // mem-initializer-id for the hidden base class may be specified
1774 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001775 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001776 // Look for a member, first.
1777 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001778 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001779 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001780 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001781 Member = dyn_cast<FieldDecl>(*Result.first);
Sebastian Redla74948d2011-09-24 17:48:25 +00001782
Douglas Gregor44e7df62011-01-04 00:32:56 +00001783 if (Member) {
1784 if (EllipsisLoc.isValid())
1785 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001786 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1787
1788 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001789 }
Sebastian Redla74948d2011-09-24 17:48:25 +00001790
Francois Pichetd583da02010-12-04 09:14:42 +00001791 // Handle anonymous union case.
1792 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001793 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1794 if (EllipsisLoc.isValid())
1795 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001796 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor44e7df62011-01-04 00:32:56 +00001797
Sebastian Redla74948d2011-09-24 17:48:25 +00001798 return BuildMemberInitializer(IndirectField, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001799 }
Francois Pichetd583da02010-12-04 09:14:42 +00001800 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001801 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001802 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001803 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001804 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001805
1806 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001807 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001808 } else {
1809 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1810 LookupParsedName(R, S, &SS);
1811
1812 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1813 if (!TyD) {
1814 if (R.isAmbiguous()) return true;
1815
John McCallda6841b2010-04-09 19:01:14 +00001816 // We don't want access-control diagnostics here.
1817 R.suppressDiagnostics();
1818
Douglas Gregora3b624a2010-01-19 06:46:48 +00001819 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1820 bool NotUnknownSpecialization = false;
1821 DeclContext *DC = computeDeclContext(SS, false);
1822 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1823 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1824
1825 if (!NotUnknownSpecialization) {
1826 // When the scope specifier can refer to a member of an unknown
1827 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001828 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1829 SS.getWithLocInContext(Context),
1830 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001831 if (BaseType.isNull())
1832 return true;
1833
Douglas Gregora3b624a2010-01-19 06:46:48 +00001834 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001835 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001836 }
1837 }
1838
Douglas Gregor15e77a22009-12-31 09:10:24 +00001839 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001840 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00001841 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001842 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1843 ClassDecl, false, CTC_NoKeywords))) {
1844 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1845 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1846 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001847 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001848 // We have found a non-static data member with a similar
1849 // name to what was typed; complain and initialize that
1850 // member.
1851 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001852 << MemberOrBase << true << CorrectedQuotedStr
1853 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor6da83622010-01-07 00:17:44 +00001854 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001855 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001856
Sebastian Redla74948d2011-09-24 17:48:25 +00001857 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor15e77a22009-12-31 09:10:24 +00001858 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001859 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001860 const CXXBaseSpecifier *DirectBaseSpec;
1861 const CXXBaseSpecifier *VirtualBaseSpec;
1862 if (FindBaseInitializer(*this, ClassDecl,
1863 Context.getTypeDeclType(Type),
1864 DirectBaseSpec, VirtualBaseSpec)) {
1865 // We have found a direct or virtual base class with a
1866 // similar name to what was typed; complain and initialize
1867 // that base class.
1868 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001869 << MemberOrBase << false << CorrectedQuotedStr
1870 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001871
1872 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1873 : VirtualBaseSpec;
1874 Diag(BaseSpec->getSourceRange().getBegin(),
1875 diag::note_base_class_specified_here)
1876 << BaseSpec->getType()
1877 << BaseSpec->getSourceRange();
1878
Douglas Gregor15e77a22009-12-31 09:10:24 +00001879 TyD = Type;
1880 }
1881 }
1882 }
1883
Douglas Gregora3b624a2010-01-19 06:46:48 +00001884 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001885 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla74948d2011-09-24 17:48:25 +00001886 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor15e77a22009-12-31 09:10:24 +00001887 return true;
1888 }
John McCallb5a0d312009-12-21 10:41:20 +00001889 }
1890
Douglas Gregora3b624a2010-01-19 06:46:48 +00001891 if (BaseType.isNull()) {
1892 BaseType = Context.getTypeDeclType(TyD);
1893 if (SS.isSet()) {
1894 NestedNameSpecifier *Qualifier =
1895 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001896
Douglas Gregora3b624a2010-01-19 06:46:48 +00001897 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001898 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001899 }
John McCallb5a0d312009-12-21 10:41:20 +00001900 }
1901 }
Mike Stump11289f42009-09-09 15:08:12 +00001902
John McCallbcd03502009-12-07 02:54:59 +00001903 if (!TInfo)
1904 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001905
Sebastian Redla74948d2011-09-24 17:48:25 +00001906 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001907}
1908
Chandler Carruth599deef2011-09-03 01:14:15 +00001909/// Checks a member initializer expression for cases where reference (or
1910/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00001911static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1912 Expr *Init,
1913 SourceLocation IdLoc) {
1914 QualType MemberTy = Member->getType();
1915
1916 // We only handle pointers and references currently.
1917 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1918 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1919 return;
1920
1921 const bool IsPointer = MemberTy->isPointerType();
1922 if (IsPointer) {
1923 if (const UnaryOperator *Op
1924 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1925 // The only case we're worried about with pointers requires taking the
1926 // address.
1927 if (Op->getOpcode() != UO_AddrOf)
1928 return;
1929
1930 Init = Op->getSubExpr();
1931 } else {
1932 // We only handle address-of expression initializers for pointers.
1933 return;
1934 }
1935 }
1936
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001937 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1938 // Taking the address of a temporary will be diagnosed as a hard error.
1939 if (IsPointer)
1940 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001941
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001942 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1943 << Member << Init->getSourceRange();
1944 } else if (const DeclRefExpr *DRE
1945 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1946 // We only warn when referring to a non-reference parameter declaration.
1947 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1948 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00001949 return;
1950
1951 S.Diag(Init->getExprLoc(),
1952 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1953 : diag::warn_bind_ref_member_to_parameter)
1954 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001955 } else {
1956 // Other initializers are fine.
1957 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001958 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001959
1960 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1961 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00001962}
1963
John McCalle22a04a2009-11-04 23:02:40 +00001964/// Checks an initializer expression for use of uninitialized fields, such as
1965/// containing the field that is being initialized. Returns true if there is an
1966/// uninitialized field was used an updates the SourceLocation parameter; false
1967/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001968static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001969 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001970 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001971 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1972
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001973 if (isa<CallExpr>(S)) {
1974 // Do not descend into function calls or constructors, as the use
1975 // of an uninitialized field may be valid. One would have to inspect
1976 // the contents of the function/ctor to determine if it is safe or not.
1977 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1978 // may be safe, depending on what the function/ctor does.
1979 return false;
1980 }
1981 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1982 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001983
1984 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1985 // The member expression points to a static data member.
1986 assert(VD->isStaticDataMember() &&
1987 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001988 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001989 return false;
1990 }
1991
1992 if (isa<EnumConstantDecl>(RhsField)) {
1993 // The member expression points to an enum.
1994 return false;
1995 }
1996
John McCalle22a04a2009-11-04 23:02:40 +00001997 if (RhsField == LhsField) {
1998 // Initializing a field with itself. Throw a warning.
1999 // But wait; there are exceptions!
2000 // Exception #1: The field may not belong to this record.
2001 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002002 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00002003 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2004 // Even though the field matches, it does not belong to this record.
2005 return false;
2006 }
2007 // None of the exceptions triggered; return true to indicate an
2008 // uninitialized field was used.
2009 *L = ME->getMemberLoc();
2010 return true;
2011 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002012 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00002013 // sizeof/alignof doesn't reference contents, do not warn.
2014 return false;
2015 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2016 // address-of doesn't reference contents (the pointer may be dereferenced
2017 // in the same expression but it would be rare; and weird).
2018 if (UOE->getOpcode() == UO_AddrOf)
2019 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002020 }
John McCall8322c3a2011-02-13 04:07:26 +00002021 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002022 if (!*it) {
2023 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00002024 continue;
2025 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002026 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2027 return true;
John McCalle22a04a2009-11-04 23:02:40 +00002028 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002029 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002030}
2031
John McCallfaf5fb42010-08-26 23:41:50 +00002032MemInitResult
Sebastian Redla74948d2011-09-24 17:48:25 +00002033Sema::BuildMemberInitializer(ValueDecl *Member,
2034 const MultiInitializer &Args,
2035 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002036 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2037 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2038 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002039 "Member must be a FieldDecl or IndirectFieldDecl");
2040
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002041 if (Member->isInvalidDecl())
2042 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002043
John McCalle22a04a2009-11-04 23:02:40 +00002044 // Diagnose value-uses of fields to initialize themselves, e.g.
2045 // foo(foo)
2046 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00002047 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redla74948d2011-09-24 17:48:25 +00002048 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2049 I != E; ++I) {
John McCalle22a04a2009-11-04 23:02:40 +00002050 SourceLocation L;
Sebastian Redla74948d2011-09-24 17:48:25 +00002051 Expr *Arg = *I;
2052 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2053 Arg = DIE->getInit();
2054 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCalle22a04a2009-11-04 23:02:40 +00002055 // FIXME: Return true in the case when other fields are used before being
2056 // uninitialized. For example, let this field be the i'th field. When
2057 // initializing the i'th field, throw a warning if any of the >= i'th
2058 // fields are used, as they are not yet initialized.
2059 // Right now we are only handling the case where the i'th field uses
2060 // itself in its initializer.
2061 Diag(L, diag::warn_field_is_uninit);
2062 }
2063 }
2064
Sebastian Redla74948d2011-09-24 17:48:25 +00002065 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002066
Chandler Carruthd44c3102010-12-06 09:23:57 +00002067 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00002068 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002069 // Can't check initialization for a member of dependent type or when
2070 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002071 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002072
John McCall31168b02011-06-15 23:02:42 +00002073 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002074 } else {
2075 // Initialize the member.
2076 InitializedEntity MemberEntity =
2077 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2078 : InitializedEntity::InitializeMember(IndirectMember, 0);
2079 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002080 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2081 Args.getEndLoc());
John McCallacf0ee52010-10-08 02:01:28 +00002082
Sebastian Redla74948d2011-09-24 17:48:25 +00002083 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002084 if (MemberInit.isInvalid())
2085 return true;
2086
Sebastian Redla74948d2011-09-24 17:48:25 +00002087 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002088
2089 // C++0x [class.base.init]p7:
2090 // The initialization of each base and member constitutes a
2091 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002092 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002093 if (MemberInit.isInvalid())
2094 return true;
2095
2096 // If we are in a dependent context, template instantiation will
2097 // perform this type-checking again. Just save the arguments that we
2098 // received in a ParenListExpr.
2099 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2100 // of the information that we have about the member
2101 // initializer. However, deconstructing the ASTs is a dicey process,
2102 // and this approach is far more likely to get the corner cases right.
Chandler Carruth599deef2011-09-03 01:14:15 +00002103 if (CurContext->isDependentContext()) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002104 Init = Args.CreateInitExpr(Context,
2105 Member->getType().getNonReferenceType());
Chandler Carruth599deef2011-09-03 01:14:15 +00002106 } else {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002107 Init = MemberInit.get();
Chandler Carruth599deef2011-09-03 01:14:15 +00002108 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2109 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002110 }
2111
Chandler Carruthd44c3102010-12-06 09:23:57 +00002112 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002113 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002114 IdLoc, Args.getStartLoc(),
2115 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002116 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00002117 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002118 IdLoc, Args.getStartLoc(),
2119 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002120 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002121}
2122
John McCallfaf5fb42010-08-26 23:41:50 +00002123MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002124Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002125 const MultiInitializer &Args,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002126 SourceLocation NameLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002127 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002128 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2129 if (!LangOpts.CPlusPlus0x)
2130 return Diag(Loc, diag::err_delegation_0x_only)
2131 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002132
Alexis Huntc5575cc2011-02-26 19:13:13 +00002133 // Initialize the object.
2134 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2135 QualType(ClassDecl->getTypeForDecl(), 0));
2136 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002137 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2138 Args.getEndLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002139
Sebastian Redla74948d2011-09-24 17:48:25 +00002140 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002141 if (DelegationInit.isInvalid())
2142 return true;
2143
2144 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00002145 CXXConstructorDecl *Constructor
2146 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002147 assert(Constructor && "Delegating constructor with no target?");
2148
Sebastian Redla74948d2011-09-24 17:48:25 +00002149 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002150
2151 // C++0x [class.base.init]p7:
2152 // The initialization of each base and member constitutes a
2153 // full-expression.
2154 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2155 if (DelegationInit.isInvalid())
2156 return true;
2157
Manuel Klimekf2b4b692011-06-22 20:02:16 +00002158 assert(!CurContext->isDependentContext());
Sebastian Redla74948d2011-09-24 17:48:25 +00002159 return new (Context) CXXCtorInitializer(Context, Loc, Args.getStartLoc(),
2160 Constructor,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002161 DelegationInit.takeAs<Expr>(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002162 Args.getEndLoc());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002163}
2164
2165MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002166Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002167 const MultiInitializer &Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002168 CXXRecordDecl *ClassDecl,
2169 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002170 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002171
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002172 SourceLocation BaseLoc
2173 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002174
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002175 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2176 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2177 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2178
2179 // C++ [class.base.init]p2:
2180 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002181 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002182 // of that class, the mem-initializer is ill-formed. A
2183 // mem-initializer-list can initialize a base class using any
2184 // name that denotes that base class type.
2185 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2186
Douglas Gregor44e7df62011-01-04 00:32:56 +00002187 if (EllipsisLoc.isValid()) {
2188 // This is a pack expansion.
2189 if (!BaseType->containsUnexpandedParameterPack()) {
2190 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla74948d2011-09-24 17:48:25 +00002191 << SourceRange(BaseLoc, Args.getEndLoc());
2192
Douglas Gregor44e7df62011-01-04 00:32:56 +00002193 EllipsisLoc = SourceLocation();
2194 }
2195 } else {
2196 // Check for any unexpanded parameter packs.
2197 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2198 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002199
2200 if (Args.DiagnoseUnexpandedParameterPack(*this))
2201 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002202 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002203
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002204 // Check for direct and virtual base classes.
2205 const CXXBaseSpecifier *DirectBaseSpec = 0;
2206 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2207 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002208 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2209 BaseType))
Sebastian Redla74948d2011-09-24 17:48:25 +00002210 return BuildDelegatingInitializer(BaseTInfo, Args, BaseLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002211
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002212 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2213 VirtualBaseSpec);
2214
2215 // C++ [base.class.init]p2:
2216 // Unless the mem-initializer-id names a nonstatic data member of the
2217 // constructor's class or a direct or virtual base of that class, the
2218 // mem-initializer is ill-formed.
2219 if (!DirectBaseSpec && !VirtualBaseSpec) {
2220 // If the class has any dependent bases, then it's possible that
2221 // one of those types will resolve to the same type as
2222 // BaseType. Therefore, just treat this as a dependent base
2223 // class initialization. FIXME: Should we try to check the
2224 // initialization anyway? It seems odd.
2225 if (ClassDecl->hasAnyDependentBases())
2226 Dependent = true;
2227 else
2228 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2229 << BaseType << Context.getTypeDeclType(ClassDecl)
2230 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2231 }
2232 }
2233
2234 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002235 // Can't check initialization for a base of dependent type or when
2236 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002237 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002238
John McCall31168b02011-06-15 23:02:42 +00002239 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002240
Sebastian Redla74948d2011-09-24 17:48:25 +00002241 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2242 /*IsVirtual=*/false,
2243 Args.getStartLoc(), BaseInit,
2244 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002245 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002246
2247 // C++ [base.class.init]p2:
2248 // If a mem-initializer-id is ambiguous because it designates both
2249 // a direct non-virtual base class and an inherited virtual base
2250 // class, the mem-initializer is ill-formed.
2251 if (DirectBaseSpec && VirtualBaseSpec)
2252 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002253 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002254
2255 CXXBaseSpecifier *BaseSpec
2256 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2257 if (!BaseSpec)
2258 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2259
2260 // Initialize the base.
2261 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00002262 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002263 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002264 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2265 Args.getEndLoc());
2266
2267 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002268 if (BaseInit.isInvalid())
2269 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002270
Sebastian Redla74948d2011-09-24 17:48:25 +00002271 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2272
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002273 // C++0x [class.base.init]p7:
2274 // The initialization of each base and member constitutes a
2275 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002276 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002277 if (BaseInit.isInvalid())
2278 return true;
2279
2280 // If we are in a dependent context, template instantiation will
2281 // perform this type-checking again. Just save the arguments that we
2282 // received in a ParenListExpr.
2283 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2284 // of the information that we have about the base
2285 // initializer. However, deconstructing the ASTs is a dicey process,
2286 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002287 if (CurContext->isDependentContext())
2288 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002289
Alexis Hunt1d792652011-01-08 20:30:50 +00002290 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002291 BaseSpec->isVirtual(),
2292 Args.getStartLoc(),
2293 BaseInit.takeAs<Expr>(),
2294 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002295}
2296
Sebastian Redl22653ba2011-08-30 19:58:05 +00002297// Create a static_cast\<T&&>(expr).
2298static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2299 QualType ExprType = E->getType();
2300 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2301 SourceLocation ExprLoc = E->getLocStart();
2302 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2303 TargetType, ExprLoc);
2304
2305 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2306 SourceRange(ExprLoc, ExprLoc),
2307 E->getSourceRange()).take();
2308}
2309
Anders Carlsson1b00e242010-04-23 03:10:23 +00002310/// ImplicitInitializerKind - How an implicit base or member initializer should
2311/// initialize its base or member.
2312enum ImplicitInitializerKind {
2313 IIK_Default,
2314 IIK_Copy,
2315 IIK_Move
2316};
2317
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002318static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002319BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002320 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002321 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002322 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002323 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002324 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002325 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2326 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002327
John McCalldadc5752010-08-24 06:29:42 +00002328 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002329
2330 switch (ImplicitInitKind) {
2331 case IIK_Default: {
2332 InitializationKind InitKind
2333 = InitializationKind::CreateDefault(Constructor->getLocation());
2334 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2335 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002336 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002337 break;
2338 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002339
Sebastian Redl22653ba2011-08-30 19:58:05 +00002340 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00002341 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002342 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002343 ParmVarDecl *Param = Constructor->getParamDecl(0);
2344 QualType ParamType = Param->getType().getNonReferenceType();
2345
2346 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00002347 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002348 Constructor->getLocation(), ParamType,
2349 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002350
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002351 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00002352 QualType ArgTy =
2353 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2354 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00002355
Sebastian Redl22653ba2011-08-30 19:58:05 +00002356 if (Moving) {
2357 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2358 }
2359
John McCallcf142162010-08-07 06:22:56 +00002360 CXXCastPath BasePath;
2361 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00002362 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2363 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002364 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002365 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002366
Anders Carlsson1b00e242010-04-23 03:10:23 +00002367 InitializationKind InitKind
2368 = InitializationKind::CreateDirect(Constructor->getLocation(),
2369 SourceLocation(), SourceLocation());
2370 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2371 &CopyCtorArg, 1);
2372 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002373 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002374 break;
2375 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002376 }
John McCallb268a282010-08-23 23:25:46 +00002377
Douglas Gregora40433a2010-12-07 00:41:46 +00002378 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002379 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002380 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002381
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002382 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002383 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002384 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2385 SourceLocation()),
2386 BaseSpec->isVirtual(),
2387 SourceLocation(),
2388 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002389 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002390 SourceLocation());
2391
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002392 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002393}
2394
Sebastian Redl22653ba2011-08-30 19:58:05 +00002395static bool RefersToRValueRef(Expr *MemRef) {
2396 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2397 return Referenced->getType()->isRValueReferenceType();
2398}
2399
Anders Carlsson3c1db572010-04-23 02:15:47 +00002400static bool
2401BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002402 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002403 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002404 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002405 if (Field->isInvalidDecl())
2406 return true;
2407
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002408 SourceLocation Loc = Constructor->getLocation();
2409
Sebastian Redl22653ba2011-08-30 19:58:05 +00002410 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2411 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002412 ParmVarDecl *Param = Constructor->getParamDecl(0);
2413 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002414
2415 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00002416 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2417 return false;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002418
2419 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00002420 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002421 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002422
Sebastian Redl22653ba2011-08-30 19:58:05 +00002423 if (Moving) {
2424 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2425 }
2426
Douglas Gregor94f9a482010-05-05 05:51:00 +00002427 // Build a reference to this field within the parameter.
2428 CXXScopeSpec SS;
2429 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2430 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002431 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2432 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002433 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002434 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002435 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002436 ParamType, Loc,
2437 /*IsArrow=*/false,
2438 SS,
2439 /*FirstQualifierInScope=*/0,
2440 MemberLookup,
2441 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002442 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002443 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002444
2445 // C++11 [class.copy]p15:
2446 // - if a member m has rvalue reference type T&&, it is direct-initialized
2447 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002448 if (RefersToRValueRef(CtorArg.get())) {
2449 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002450 }
2451
Douglas Gregor94f9a482010-05-05 05:51:00 +00002452 // When the field we are copying is an array, create index variables for
2453 // each dimension of the array. We use these index variables to subscript
2454 // the source array, and other clients (e.g., CodeGen) will perform the
2455 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002456 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002457 QualType BaseType = Field->getType();
2458 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002459 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002460 while (const ConstantArrayType *Array
2461 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002462 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002463 // Create the iteration variable for this array index.
2464 IdentifierInfo *IterationVarName = 0;
2465 {
2466 llvm::SmallString<8> Str;
2467 llvm::raw_svector_ostream OS(Str);
2468 OS << "__i" << IndexVariables.size();
2469 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2470 }
2471 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002472 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002473 IterationVarName, SizeType,
2474 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002475 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002476 IndexVariables.push_back(IterationVar);
2477
2478 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002479 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00002480 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002481 assert(!IterationVarRef.isInvalid() &&
2482 "Reference to invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00002483
Douglas Gregor94f9a482010-05-05 05:51:00 +00002484 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00002485 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00002486 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00002487 Loc);
2488 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00002489 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002490
Douglas Gregor94f9a482010-05-05 05:51:00 +00002491 BaseType = Array->getElementType();
2492 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00002493
2494 // The array subscript expression is an lvalue, which is wrong for moving.
2495 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00002496 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002497
Douglas Gregor94f9a482010-05-05 05:51:00 +00002498 // Construct the entity that we will be initializing. For an array, this
2499 // will be first element in the array, which may require several levels
2500 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002501 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002502 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00002503 if (Indirect)
2504 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2505 else
2506 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00002507 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2508 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2509 0,
2510 Entities.back()));
2511
2512 // Direct-initialize to use the copy constructor.
2513 InitializationKind InitKind =
2514 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2515
Sebastian Redle9c4e842011-09-04 18:14:28 +00002516 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregor94f9a482010-05-05 05:51:00 +00002517 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002518 &CtorArgE, 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002519
John McCalldadc5752010-08-24 06:29:42 +00002520 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002521 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002522 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002523 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002524 if (MemberInit.isInvalid())
2525 return true;
2526
Douglas Gregor493627b2011-08-10 15:22:55 +00002527 if (Indirect) {
2528 assert(IndexVariables.size() == 0 &&
2529 "Indirect field improperly initialized");
2530 CXXMemberInit
2531 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2532 Loc, Loc,
2533 MemberInit.takeAs<Expr>(),
2534 Loc);
2535 } else
2536 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2537 Loc, MemberInit.takeAs<Expr>(),
2538 Loc,
2539 IndexVariables.data(),
2540 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002541 return false;
2542 }
2543
Anders Carlsson423f5d82010-04-23 16:04:08 +00002544 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2545
Anders Carlsson3c1db572010-04-23 02:15:47 +00002546 QualType FieldBaseElementType =
2547 SemaRef.Context.getBaseElementType(Field->getType());
2548
Anders Carlsson3c1db572010-04-23 02:15:47 +00002549 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002550 InitializedEntity InitEntity
2551 = Indirect? InitializedEntity::InitializeMember(Indirect)
2552 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002553 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002554 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002555
2556 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002557 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002558 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002559
Douglas Gregora40433a2010-12-07 00:41:46 +00002560 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002561 if (MemberInit.isInvalid())
2562 return true;
2563
Douglas Gregor493627b2011-08-10 15:22:55 +00002564 if (Indirect)
2565 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2566 Indirect, Loc,
2567 Loc,
2568 MemberInit.get(),
2569 Loc);
2570 else
2571 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2572 Field, Loc, Loc,
2573 MemberInit.get(),
2574 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002575 return false;
2576 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002577
Alexis Hunt8b455182011-05-17 00:19:05 +00002578 if (!Field->getParent()->isUnion()) {
2579 if (FieldBaseElementType->isReferenceType()) {
2580 SemaRef.Diag(Constructor->getLocation(),
2581 diag::err_uninitialized_member_in_ctor)
2582 << (int)Constructor->isImplicit()
2583 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2584 << 0 << Field->getDeclName();
2585 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2586 return true;
2587 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002588
Alexis Hunt8b455182011-05-17 00:19:05 +00002589 if (FieldBaseElementType.isConstQualified()) {
2590 SemaRef.Diag(Constructor->getLocation(),
2591 diag::err_uninitialized_member_in_ctor)
2592 << (int)Constructor->isImplicit()
2593 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2594 << 1 << Field->getDeclName();
2595 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2596 return true;
2597 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002598 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002599
John McCall31168b02011-06-15 23:02:42 +00002600 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2601 FieldBaseElementType->isObjCRetainableType() &&
2602 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2603 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2604 // Instant objects:
2605 // Default-initialize Objective-C pointers to NULL.
2606 CXXMemberInit
2607 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2608 Loc, Loc,
2609 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2610 Loc);
2611 return false;
2612 }
2613
Anders Carlsson3c1db572010-04-23 02:15:47 +00002614 // Nothing to initialize.
2615 CXXMemberInit = 0;
2616 return false;
2617}
John McCallbc83b3f2010-05-20 23:23:51 +00002618
2619namespace {
2620struct BaseAndFieldInfo {
2621 Sema &S;
2622 CXXConstructorDecl *Ctor;
2623 bool AnyErrorsInInits;
2624 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002625 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002626 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002627
2628 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2629 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002630 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2631 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00002632 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002633 else if (Generated && Ctor->isMoveConstructor())
2634 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00002635 else
2636 IIK = IIK_Default;
2637 }
2638};
2639}
2640
Richard Smithc94ec842011-09-19 13:34:43 +00002641/// \brief Determine whether the given indirect field declaration is somewhere
2642/// within an anonymous union.
2643static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2644 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2645 CEnd = F->chain_end();
2646 C != CEnd; ++C)
2647 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2648 if (Record->isUnion())
2649 return true;
2650
2651 return false;
2652}
2653
Richard Smith938f40b2011-06-11 17:19:42 +00002654static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00002655 FieldDecl *Field,
2656 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00002657
Chandler Carruth139e9622010-06-30 02:59:29 +00002658 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002659 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002660 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002661 return false;
2662 }
2663
Richard Smith938f40b2011-06-11 17:19:42 +00002664 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2665 // has a brace-or-equal-initializer, the entity is initialized as specified
2666 // in [dcl.init].
2667 if (Field->hasInClassInitializer()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002668 CXXCtorInitializer *Init;
2669 if (Indirect)
2670 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2671 SourceLocation(),
2672 SourceLocation(), 0,
2673 SourceLocation());
2674 else
2675 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2676 SourceLocation(),
2677 SourceLocation(), 0,
2678 SourceLocation());
2679 Info.AllToInit.push_back(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002680 return false;
2681 }
2682
Richard Smith12d5ed82011-09-18 11:14:50 +00002683 // Don't build an implicit initializer for union members if none was
2684 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00002685 if (Field->getParent()->isUnion() ||
2686 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00002687 return false;
2688
John McCallbc83b3f2010-05-20 23:23:51 +00002689 // Don't try to build an implicit initializer if there were semantic
2690 // errors in any of the initializers (and therefore we might be
2691 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002692 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002693 return false;
2694
Alexis Hunt1d792652011-01-08 20:30:50 +00002695 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00002696 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2697 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00002698 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002699
Francois Pichetd583da02010-12-04 09:14:42 +00002700 if (Init)
2701 Info.AllToInit.push_back(Init);
2702
John McCallbc83b3f2010-05-20 23:23:51 +00002703 return false;
2704}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002705
2706bool
2707Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2708 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002709 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002710 Constructor->setNumCtorInitializers(1);
2711 CXXCtorInitializer **initializer =
2712 new (Context) CXXCtorInitializer*[1];
2713 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2714 Constructor->setCtorInitializers(initializer);
2715
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002716 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2717 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2718 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2719 }
2720
Alexis Hunte2622992011-05-05 00:05:47 +00002721 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002722
Alexis Hunt61bc1732011-05-01 07:04:31 +00002723 return false;
2724}
Douglas Gregor493627b2011-08-10 15:22:55 +00002725
John McCall1b1a1db2011-06-17 00:18:42 +00002726bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2727 CXXCtorInitializer **Initializers,
2728 unsigned NumInitializers,
2729 bool AnyErrors) {
Douglas Gregor52235292011-09-22 23:04:35 +00002730 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002731 // Just store the initializers as written, they will be checked during
2732 // instantiation.
2733 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002734 Constructor->setNumCtorInitializers(NumInitializers);
2735 CXXCtorInitializer **baseOrMemberInitializers =
2736 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002737 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002738 NumInitializers * sizeof(CXXCtorInitializer*));
2739 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002740 }
2741
2742 return false;
2743 }
2744
John McCallbc83b3f2010-05-20 23:23:51 +00002745 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002746
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002747 // We need to build the initializer AST according to order of construction
2748 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002749 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002750 if (!ClassDecl)
2751 return true;
2752
Eli Friedman9cf6b592009-11-09 19:20:36 +00002753 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002754
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002755 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002756 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002757
2758 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002759 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002760 else
Francois Pichetd583da02010-12-04 09:14:42 +00002761 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002762 }
2763
Anders Carlsson43c64af2010-04-21 19:52:01 +00002764 // Keep track of the direct virtual bases.
2765 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2766 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2767 E = ClassDecl->bases_end(); I != E; ++I) {
2768 if (I->isVirtual())
2769 DirectVBases.insert(I);
2770 }
2771
Anders Carlssondb0a9652010-04-02 06:26:44 +00002772 // Push virtual bases before others.
2773 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2774 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2775
Alexis Hunt1d792652011-01-08 20:30:50 +00002776 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002777 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2778 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002779 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002780 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002781 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002782 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002783 VBase, IsInheritedVirtualBase,
2784 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002785 HadError = true;
2786 continue;
2787 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002788
John McCallbc83b3f2010-05-20 23:23:51 +00002789 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002790 }
2791 }
Mike Stump11289f42009-09-09 15:08:12 +00002792
John McCallbc83b3f2010-05-20 23:23:51 +00002793 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002794 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2795 E = ClassDecl->bases_end(); Base != E; ++Base) {
2796 // Virtuals are in the virtual base list and already constructed.
2797 if (Base->isVirtual())
2798 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002799
Alexis Hunt1d792652011-01-08 20:30:50 +00002800 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002801 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2802 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002803 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002804 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002805 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002806 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002807 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002808 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002809 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002810 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002811
John McCallbc83b3f2010-05-20 23:23:51 +00002812 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002813 }
2814 }
Mike Stump11289f42009-09-09 15:08:12 +00002815
John McCallbc83b3f2010-05-20 23:23:51 +00002816 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00002817 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2818 MemEnd = ClassDecl->decls_end();
2819 Mem != MemEnd; ++Mem) {
2820 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00002821 // C++ [class.bit]p2:
2822 // A declaration for a bit-field that omits the identifier declares an
2823 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2824 // initialized.
2825 if (F->isUnnamedBitfield())
2826 continue;
2827
Douglas Gregor493627b2011-08-10 15:22:55 +00002828 if (F->getType()->isIncompleteArrayType()) {
2829 assert(ClassDecl->hasFlexibleArrayMember() &&
2830 "Incomplete array type is not valid");
2831 continue;
2832 }
2833
Sebastian Redl22653ba2011-08-30 19:58:05 +00002834 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00002835 // handle anonymous struct/union fields based on their individual
2836 // indirect fields.
2837 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2838 continue;
2839
2840 if (CollectFieldInitializer(*this, Info, F))
2841 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002842 continue;
2843 }
Douglas Gregor493627b2011-08-10 15:22:55 +00002844
2845 // Beyond this point, we only consider default initialization.
2846 if (Info.IIK != IIK_Default)
2847 continue;
2848
2849 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2850 if (F->getType()->isIncompleteArrayType()) {
2851 assert(ClassDecl->hasFlexibleArrayMember() &&
2852 "Incomplete array type is not valid");
2853 continue;
2854 }
2855
Douglas Gregor493627b2011-08-10 15:22:55 +00002856 // Initialize each field of an anonymous struct individually.
2857 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2858 HadError = true;
2859
2860 continue;
2861 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002862 }
Mike Stump11289f42009-09-09 15:08:12 +00002863
John McCallbc83b3f2010-05-20 23:23:51 +00002864 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002865 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002866 Constructor->setNumCtorInitializers(NumInitializers);
2867 CXXCtorInitializer **baseOrMemberInitializers =
2868 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002869 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002870 NumInitializers * sizeof(CXXCtorInitializer*));
2871 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002872
John McCalla6309952010-03-16 21:39:52 +00002873 // Constructors implicitly reference the base and member
2874 // destructors.
2875 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2876 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002877 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002878
2879 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002880}
2881
Eli Friedman952c15d2009-07-21 19:28:10 +00002882static void *GetKeyForTopLevelField(FieldDecl *Field) {
2883 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002884 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002885 if (RT->getDecl()->isAnonymousStructOrUnion())
2886 return static_cast<void *>(RT->getDecl());
2887 }
2888 return static_cast<void *>(Field);
2889}
2890
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002891static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002892 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002893}
2894
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002895static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002896 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002897 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002898 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002899
Eli Friedman952c15d2009-07-21 19:28:10 +00002900 // For fields injected into the class via declaration of an anonymous union,
2901 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002902 FieldDecl *Field = Member->getAnyMember();
2903
John McCall23eebd92010-04-10 09:28:51 +00002904 // If the field is a member of an anonymous struct or union, our key
2905 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002906 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002907 if (RD->isAnonymousStructOrUnion()) {
2908 while (true) {
2909 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2910 if (Parent->isAnonymousStructOrUnion())
2911 RD = Parent;
2912 else
2913 break;
2914 }
2915
Anders Carlsson83ac3122010-03-30 16:19:37 +00002916 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002917 }
Mike Stump11289f42009-09-09 15:08:12 +00002918
Anders Carlssona942dcd2010-03-30 15:39:27 +00002919 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002920}
2921
Anders Carlssone857b292010-04-02 03:37:03 +00002922static void
2923DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002924 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002925 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002926 unsigned NumInits) {
2927 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002928 return;
Mike Stump11289f42009-09-09 15:08:12 +00002929
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002930 // Don't check initializers order unless the warning is enabled at the
2931 // location of at least one initializer.
2932 bool ShouldCheckOrder = false;
2933 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002934 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002935 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2936 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00002937 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002938 ShouldCheckOrder = true;
2939 break;
2940 }
2941 }
2942 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002943 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002944
John McCallbb7b6582010-04-10 07:37:23 +00002945 // Build the list of bases and members in the order that they'll
2946 // actually be initialized. The explicit initializers should be in
2947 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002948 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002949
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002950 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2951
John McCallbb7b6582010-04-10 07:37:23 +00002952 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002953 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002954 ClassDecl->vbases_begin(),
2955 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002956 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002957
John McCallbb7b6582010-04-10 07:37:23 +00002958 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002959 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002960 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002961 if (Base->isVirtual())
2962 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002963 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002964 }
Mike Stump11289f42009-09-09 15:08:12 +00002965
John McCallbb7b6582010-04-10 07:37:23 +00002966 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002967 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00002968 E = ClassDecl->field_end(); Field != E; ++Field) {
2969 if (Field->isUnnamedBitfield())
2970 continue;
2971
John McCallbb7b6582010-04-10 07:37:23 +00002972 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregor556e5862011-10-10 17:22:13 +00002973 }
2974
John McCallbb7b6582010-04-10 07:37:23 +00002975 unsigned NumIdealInits = IdealInitKeys.size();
2976 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002977
Alexis Hunt1d792652011-01-08 20:30:50 +00002978 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002979 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002980 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002981 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002982
2983 // Scan forward to try to find this initializer in the idealized
2984 // initializers list.
2985 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2986 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002987 break;
John McCallbb7b6582010-04-10 07:37:23 +00002988
2989 // If we didn't find this initializer, it must be because we
2990 // scanned past it on a previous iteration. That can only
2991 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002992 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002993 Sema::SemaDiagnosticBuilder D =
2994 SemaRef.Diag(PrevInit->getSourceLocation(),
2995 diag::warn_initializer_out_of_order);
2996
Francois Pichetd583da02010-12-04 09:14:42 +00002997 if (PrevInit->isAnyMemberInitializer())
2998 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002999 else
3000 D << 1 << PrevInit->getBaseClassInfo()->getType();
3001
Francois Pichetd583da02010-12-04 09:14:42 +00003002 if (Init->isAnyMemberInitializer())
3003 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003004 else
3005 D << 1 << Init->getBaseClassInfo()->getType();
3006
3007 // Move back to the initializer's location in the ideal list.
3008 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3009 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003010 break;
John McCallbb7b6582010-04-10 07:37:23 +00003011
3012 assert(IdealIndex != NumIdealInits &&
3013 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003014 }
John McCallbb7b6582010-04-10 07:37:23 +00003015
3016 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003017 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003018}
3019
John McCall23eebd92010-04-10 09:28:51 +00003020namespace {
3021bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003022 CXXCtorInitializer *Init,
3023 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003024 if (!PrevInit) {
3025 PrevInit = Init;
3026 return false;
3027 }
3028
3029 if (FieldDecl *Field = Init->getMember())
3030 S.Diag(Init->getSourceLocation(),
3031 diag::err_multiple_mem_initialization)
3032 << Field->getDeclName()
3033 << Init->getSourceRange();
3034 else {
John McCall424cec92011-01-19 06:33:43 +00003035 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003036 assert(BaseClass && "neither field nor base");
3037 S.Diag(Init->getSourceLocation(),
3038 diag::err_multiple_base_initialization)
3039 << QualType(BaseClass, 0)
3040 << Init->getSourceRange();
3041 }
3042 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3043 << 0 << PrevInit->getSourceRange();
3044
3045 return true;
3046}
3047
Alexis Hunt1d792652011-01-08 20:30:50 +00003048typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003049typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3050
3051bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003052 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003053 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003054 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003055 RecordDecl *Parent = Field->getParent();
3056 if (!Parent->isAnonymousStructOrUnion())
3057 return false;
3058
3059 NamedDecl *Child = Field;
3060 do {
3061 if (Parent->isUnion()) {
3062 UnionEntry &En = Unions[Parent];
3063 if (En.first && En.first != Child) {
3064 S.Diag(Init->getSourceLocation(),
3065 diag::err_multiple_mem_union_initialization)
3066 << Field->getDeclName()
3067 << Init->getSourceRange();
3068 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3069 << 0 << En.second->getSourceRange();
3070 return true;
3071 } else if (!En.first) {
3072 En.first = Child;
3073 En.second = Init;
3074 }
3075 }
3076
3077 Child = Parent;
3078 Parent = cast<RecordDecl>(Parent->getDeclContext());
3079 } while (Parent->isAnonymousStructOrUnion());
3080
3081 return false;
3082}
3083}
3084
Anders Carlssone857b292010-04-02 03:37:03 +00003085/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003086void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003087 SourceLocation ColonLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00003088 CXXCtorInitializer **meminits,
3089 unsigned NumMemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003090 bool AnyErrors) {
3091 if (!ConstructorDecl)
3092 return;
3093
3094 AdjustDeclIfTemplate(ConstructorDecl);
3095
3096 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003097 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003098
3099 if (!Constructor) {
3100 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3101 return;
3102 }
3103
Alexis Hunt1d792652011-01-08 20:30:50 +00003104 CXXCtorInitializer **MemInits =
3105 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00003106
3107 // Mapping for the duplicate initializers check.
3108 // For member initializers, this is keyed with a FieldDecl*.
3109 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00003110 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003111
3112 // Mapping for the inconsistent anonymous-union initializers check.
3113 RedundantUnionMap MemberUnions;
3114
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003115 bool HadError = false;
3116 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003117 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003118
Abramo Bagnara341d7832010-05-26 18:09:23 +00003119 // Set the source order index.
3120 Init->setSourceOrder(i);
3121
Francois Pichetd583da02010-12-04 09:14:42 +00003122 if (Init->isAnyMemberInitializer()) {
3123 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003124 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3125 CheckRedundantUnionInit(*this, Init, MemberUnions))
3126 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003127 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00003128 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3129 if (CheckRedundantInit(*this, Init, Members[Key]))
3130 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003131 } else {
3132 assert(Init->isDelegatingInitializer());
3133 // This must be the only initializer
3134 if (i != 0 || NumMemInits > 1) {
3135 Diag(MemInits[0]->getSourceLocation(),
3136 diag::err_delegating_initializer_alone)
3137 << MemInits[0]->getSourceRange();
3138 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00003139 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003140 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003141 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003142 // Return immediately as the initializer is set.
3143 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003144 }
Anders Carlssone857b292010-04-02 03:37:03 +00003145 }
3146
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003147 if (HadError)
3148 return;
3149
Anders Carlssone857b292010-04-02 03:37:03 +00003150 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003151
Alexis Hunt1d792652011-01-08 20:30:50 +00003152 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00003153}
3154
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003155void
John McCalla6309952010-03-16 21:39:52 +00003156Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3157 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003158 // Ignore dependent contexts. Also ignore unions, since their members never
3159 // have destructors implicitly called.
3160 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003161 return;
John McCall1064d7e2010-03-16 05:22:47 +00003162
3163 // FIXME: all the access-control diagnostics are positioned on the
3164 // field/base declaration. That's probably good; that said, the
3165 // user might reasonably want to know why the destructor is being
3166 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003167
Anders Carlssondee9a302009-11-17 04:44:12 +00003168 // Non-static data members.
3169 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3170 E = ClassDecl->field_end(); I != E; ++I) {
3171 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003172 if (Field->isInvalidDecl())
3173 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003174 QualType FieldType = Context.getBaseElementType(Field->getType());
3175
3176 const RecordType* RT = FieldType->getAs<RecordType>();
3177 if (!RT)
3178 continue;
3179
3180 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003181 if (FieldClassDecl->isInvalidDecl())
3182 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003183 if (FieldClassDecl->hasTrivialDestructor())
3184 continue;
3185
Douglas Gregore71edda2010-07-01 22:47:18 +00003186 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003187 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003188 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003189 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003190 << Field->getDeclName()
3191 << FieldType);
3192
John McCalla6309952010-03-16 21:39:52 +00003193 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003194 }
3195
John McCall1064d7e2010-03-16 05:22:47 +00003196 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3197
Anders Carlssondee9a302009-11-17 04:44:12 +00003198 // Bases.
3199 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3200 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003201 // Bases are always records in a well-formed non-dependent class.
3202 const RecordType *RT = Base->getType()->getAs<RecordType>();
3203
3204 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003205 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003206 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003207
John McCall1064d7e2010-03-16 05:22:47 +00003208 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003209 // If our base class is invalid, we probably can't get its dtor anyway.
3210 if (BaseClassDecl->isInvalidDecl())
3211 continue;
3212 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00003213 if (BaseClassDecl->hasTrivialDestructor())
3214 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003215
Douglas Gregore71edda2010-07-01 22:47:18 +00003216 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003217 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003218
3219 // FIXME: caret should be on the start of the class name
3220 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003221 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003222 << Base->getType()
3223 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00003224
John McCalla6309952010-03-16 21:39:52 +00003225 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003226 }
3227
3228 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003229 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3230 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003231
3232 // Bases are always records in a well-formed non-dependent class.
3233 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3234
3235 // Ignore direct virtual bases.
3236 if (DirectVirtualBases.count(RT))
3237 continue;
3238
John McCall1064d7e2010-03-16 05:22:47 +00003239 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003240 // If our base class is invalid, we probably can't get its dtor anyway.
3241 if (BaseClassDecl->isInvalidDecl())
3242 continue;
3243 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003244 if (BaseClassDecl->hasTrivialDestructor())
3245 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003246
Douglas Gregore71edda2010-07-01 22:47:18 +00003247 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003248 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003249 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003250 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00003251 << VBase->getType());
3252
John McCalla6309952010-03-16 21:39:52 +00003253 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003254 }
3255}
3256
John McCall48871652010-08-21 09:40:31 +00003257void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00003258 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003259 return;
Mike Stump11289f42009-09-09 15:08:12 +00003260
Mike Stump11289f42009-09-09 15:08:12 +00003261 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003262 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00003263 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003264}
3265
Mike Stump11289f42009-09-09 15:08:12 +00003266bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003267 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00003268 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00003269 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00003270 else
John McCall02db245d2010-08-18 09:41:07 +00003271 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00003272}
3273
Anders Carlssoneabf7702009-08-27 00:13:57 +00003274bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003275 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003276 if (!getLangOptions().CPlusPlus)
3277 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003278
Anders Carlssoneb0c5322009-03-23 19:10:31 +00003279 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00003280 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00003281
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003282 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003283 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003284 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003285 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00003286
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003287 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00003288 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003289 }
Mike Stump11289f42009-09-09 15:08:12 +00003290
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003291 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003292 if (!RT)
3293 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003294
John McCall67da35c2010-02-04 22:26:26 +00003295 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003296
John McCall02db245d2010-08-18 09:41:07 +00003297 // We can't answer whether something is abstract until it has a
3298 // definition. If it's currently being defined, we'll walk back
3299 // over all the declarations when we have a full definition.
3300 const CXXRecordDecl *Def = RD->getDefinition();
3301 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00003302 return false;
3303
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003304 if (!RD->isAbstract())
3305 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003306
Anders Carlssoneabf7702009-08-27 00:13:57 +00003307 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00003308 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00003309
John McCall02db245d2010-08-18 09:41:07 +00003310 return true;
3311}
3312
3313void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3314 // Check if we've already emitted the list of pure virtual functions
3315 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003316 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00003317 return;
Mike Stump11289f42009-09-09 15:08:12 +00003318
Douglas Gregor4165bd62010-03-23 23:47:56 +00003319 CXXFinalOverriderMap FinalOverriders;
3320 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00003321
Anders Carlssona2f74f32010-06-03 01:00:02 +00003322 // Keep a set of seen pure methods so we won't diagnose the same method
3323 // more than once.
3324 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3325
Douglas Gregor4165bd62010-03-23 23:47:56 +00003326 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3327 MEnd = FinalOverriders.end();
3328 M != MEnd;
3329 ++M) {
3330 for (OverridingMethods::iterator SO = M->second.begin(),
3331 SOEnd = M->second.end();
3332 SO != SOEnd; ++SO) {
3333 // C++ [class.abstract]p4:
3334 // A class is abstract if it contains or inherits at least one
3335 // pure virtual function for which the final overrider is pure
3336 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00003337
Douglas Gregor4165bd62010-03-23 23:47:56 +00003338 //
3339 if (SO->second.size() != 1)
3340 continue;
3341
3342 if (!SO->second.front().Method->isPure())
3343 continue;
3344
Anders Carlssona2f74f32010-06-03 01:00:02 +00003345 if (!SeenPureMethods.insert(SO->second.front().Method))
3346 continue;
3347
Douglas Gregor4165bd62010-03-23 23:47:56 +00003348 Diag(SO->second.front().Method->getLocation(),
3349 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00003350 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00003351 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003352 }
3353
3354 if (!PureVirtualClassDiagSet)
3355 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3356 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003357}
3358
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003359namespace {
John McCall02db245d2010-08-18 09:41:07 +00003360struct AbstractUsageInfo {
3361 Sema &S;
3362 CXXRecordDecl *Record;
3363 CanQualType AbstractType;
3364 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00003365
John McCall02db245d2010-08-18 09:41:07 +00003366 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3367 : S(S), Record(Record),
3368 AbstractType(S.Context.getCanonicalType(
3369 S.Context.getTypeDeclType(Record))),
3370 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003371
John McCall02db245d2010-08-18 09:41:07 +00003372 void DiagnoseAbstractType() {
3373 if (Invalid) return;
3374 S.DiagnoseAbstractType(Record);
3375 Invalid = true;
3376 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00003377
John McCall02db245d2010-08-18 09:41:07 +00003378 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3379};
3380
3381struct CheckAbstractUsage {
3382 AbstractUsageInfo &Info;
3383 const NamedDecl *Ctx;
3384
3385 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3386 : Info(Info), Ctx(Ctx) {}
3387
3388 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3389 switch (TL.getTypeLocClass()) {
3390#define ABSTRACT_TYPELOC(CLASS, PARENT)
3391#define TYPELOC(CLASS, PARENT) \
3392 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3393#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003394 }
John McCall02db245d2010-08-18 09:41:07 +00003395 }
Mike Stump11289f42009-09-09 15:08:12 +00003396
John McCall02db245d2010-08-18 09:41:07 +00003397 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3398 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3399 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003400 if (!TL.getArg(I))
3401 continue;
3402
John McCall02db245d2010-08-18 09:41:07 +00003403 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3404 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003405 }
John McCall02db245d2010-08-18 09:41:07 +00003406 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003407
John McCall02db245d2010-08-18 09:41:07 +00003408 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3409 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3410 }
Mike Stump11289f42009-09-09 15:08:12 +00003411
John McCall02db245d2010-08-18 09:41:07 +00003412 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3413 // Visit the type parameters from a permissive context.
3414 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3415 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3416 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3417 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3418 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3419 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003420 }
John McCall02db245d2010-08-18 09:41:07 +00003421 }
Mike Stump11289f42009-09-09 15:08:12 +00003422
John McCall02db245d2010-08-18 09:41:07 +00003423 // Visit pointee types from a permissive context.
3424#define CheckPolymorphic(Type) \
3425 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3426 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3427 }
3428 CheckPolymorphic(PointerTypeLoc)
3429 CheckPolymorphic(ReferenceTypeLoc)
3430 CheckPolymorphic(MemberPointerTypeLoc)
3431 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00003432 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00003433
John McCall02db245d2010-08-18 09:41:07 +00003434 /// Handle all the types we haven't given a more specific
3435 /// implementation for above.
3436 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3437 // Every other kind of type that we haven't called out already
3438 // that has an inner type is either (1) sugar or (2) contains that
3439 // inner type in some way as a subobject.
3440 if (TypeLoc Next = TL.getNextTypeLoc())
3441 return Visit(Next, Sel);
3442
3443 // If there's no inner type and we're in a permissive context,
3444 // don't diagnose.
3445 if (Sel == Sema::AbstractNone) return;
3446
3447 // Check whether the type matches the abstract type.
3448 QualType T = TL.getType();
3449 if (T->isArrayType()) {
3450 Sel = Sema::AbstractArrayType;
3451 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003452 }
John McCall02db245d2010-08-18 09:41:07 +00003453 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3454 if (CT != Info.AbstractType) return;
3455
3456 // It matched; do some magic.
3457 if (Sel == Sema::AbstractArrayType) {
3458 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3459 << T << TL.getSourceRange();
3460 } else {
3461 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3462 << Sel << T << TL.getSourceRange();
3463 }
3464 Info.DiagnoseAbstractType();
3465 }
3466};
3467
3468void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3469 Sema::AbstractDiagSelID Sel) {
3470 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3471}
3472
3473}
3474
3475/// Check for invalid uses of an abstract type in a method declaration.
3476static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3477 CXXMethodDecl *MD) {
3478 // No need to do the check on definitions, which require that
3479 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003480 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00003481 return;
3482
3483 // For safety's sake, just ignore it if we don't have type source
3484 // information. This should never happen for non-implicit methods,
3485 // but...
3486 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3487 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3488}
3489
3490/// Check for invalid uses of an abstract type within a class definition.
3491static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3492 CXXRecordDecl *RD) {
3493 for (CXXRecordDecl::decl_iterator
3494 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3495 Decl *D = *I;
3496 if (D->isImplicit()) continue;
3497
3498 // Methods and method templates.
3499 if (isa<CXXMethodDecl>(D)) {
3500 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3501 } else if (isa<FunctionTemplateDecl>(D)) {
3502 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3503 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3504
3505 // Fields and static variables.
3506 } else if (isa<FieldDecl>(D)) {
3507 FieldDecl *FD = cast<FieldDecl>(D);
3508 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3509 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3510 } else if (isa<VarDecl>(D)) {
3511 VarDecl *VD = cast<VarDecl>(D);
3512 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3513 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3514
3515 // Nested classes and class templates.
3516 } else if (isa<CXXRecordDecl>(D)) {
3517 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3518 } else if (isa<ClassTemplateDecl>(D)) {
3519 CheckAbstractClassUsage(Info,
3520 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3521 }
3522 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003523}
3524
Douglas Gregorc99f1552009-12-03 18:33:45 +00003525/// \brief Perform semantic checks on a class definition that has been
3526/// completing, introducing implicitly-declared members, checking for
3527/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003528void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003529 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003530 return;
3531
John McCall02db245d2010-08-18 09:41:07 +00003532 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3533 AbstractUsageInfo Info(*this, Record);
3534 CheckAbstractClassUsage(Info, Record);
3535 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003536
3537 // If this is not an aggregate type and has no user-declared constructor,
3538 // complain about any non-static data members of reference or const scalar
3539 // type, since they will never get initializers.
3540 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3541 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3542 bool Complained = false;
3543 for (RecordDecl::field_iterator F = Record->field_begin(),
3544 FEnd = Record->field_end();
3545 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003546 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00003547 continue;
3548
Douglas Gregor454a5b62010-04-15 00:00:53 +00003549 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003550 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003551 if (!Complained) {
3552 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3553 << Record->getTagKind() << Record;
3554 Complained = true;
3555 }
3556
3557 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3558 << F->getType()->isReferenceType()
3559 << F->getDeclName();
3560 }
3561 }
3562 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003563
Anders Carlssone771e762011-01-25 18:08:22 +00003564 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003565 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003566
3567 if (Record->getIdentifier()) {
3568 // C++ [class.mem]p13:
3569 // If T is the name of a class, then each of the following shall have a
3570 // name different from T:
3571 // - every member of every anonymous union that is a member of class T.
3572 //
3573 // C++ [class.mem]p14:
3574 // In addition, if class T has a user-declared constructor (12.1), every
3575 // non-static data member of class T shall have a name different from T.
3576 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003577 R.first != R.second; ++R.first) {
3578 NamedDecl *D = *R.first;
3579 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3580 isa<IndirectFieldDecl>(D)) {
3581 Diag(D->getLocation(), diag::err_member_name_of_class)
3582 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003583 break;
3584 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003585 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003586 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003587
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003588 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003589 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003590 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003591 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003592 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3593 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3594 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003595
3596 // See if a method overloads virtual methods in a base
3597 /// class without overriding any.
3598 if (!Record->isDependentType()) {
3599 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3600 MEnd = Record->method_end();
3601 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003602 if (!(*M)->isStatic())
3603 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003604 }
3605 }
Sebastian Redl08905022011-02-05 19:23:19 +00003606
Richard Smitheb3c10c2011-10-01 02:31:28 +00003607 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3608 // function that is not a constructor declares that member function to be
3609 // const. [...] The class of which that function is a member shall be
3610 // a literal type.
3611 //
3612 // It's fine to diagnose constructors here too: such constructors cannot
3613 // produce a constant expression, so are ill-formed (no diagnostic required).
3614 //
3615 // If the class has virtual bases, any constexpr members will already have
3616 // been diagnosed by the checks performed on the member declaration, so
3617 // suppress this (less useful) diagnostic.
3618 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3619 !Record->isLiteral() && !Record->getNumVBases()) {
3620 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3621 MEnd = Record->method_end();
3622 M != MEnd; ++M) {
3623 if ((*M)->isConstexpr()) {
3624 switch (Record->getTemplateSpecializationKind()) {
3625 case TSK_ImplicitInstantiation:
3626 case TSK_ExplicitInstantiationDeclaration:
3627 case TSK_ExplicitInstantiationDefinition:
3628 // If a template instantiates to a non-literal type, but its members
3629 // instantiate to constexpr functions, the template is technically
3630 // ill-formed, but we allow it for sanity. Such members are treated as
3631 // non-constexpr.
3632 (*M)->setConstexpr(false);
3633 continue;
3634
3635 case TSK_Undeclared:
3636 case TSK_ExplicitSpecialization:
3637 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3638 PDiag(diag::err_constexpr_method_non_literal));
3639 break;
3640 }
3641
3642 // Only produce one error per class.
3643 break;
3644 }
3645 }
3646 }
3647
Sebastian Redl08905022011-02-05 19:23:19 +00003648 // Declare inherited constructors. We do this eagerly here because:
3649 // - The standard requires an eager diagnostic for conflicting inherited
3650 // constructors from different classes.
3651 // - The lazy declaration of the other implicit constructors is so as to not
3652 // waste space and performance on classes that are not meant to be
3653 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3654 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003655 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003656
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003657 if (!Record->isDependentType())
3658 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003659}
3660
3661void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003662 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3663 ME = Record->method_end();
3664 MI != ME; ++MI) {
3665 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3666 switch (getSpecialMember(*MI)) {
3667 case CXXDefaultConstructor:
3668 CheckExplicitlyDefaultedDefaultConstructor(
3669 cast<CXXConstructorDecl>(*MI));
3670 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003671
Alexis Huntf91729462011-05-12 22:46:25 +00003672 case CXXDestructor:
3673 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3674 break;
3675
3676 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003677 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3678 break;
3679
Alexis Huntf91729462011-05-12 22:46:25 +00003680 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003681 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003682 break;
3683
Alexis Hunt119c10e2011-05-25 23:16:36 +00003684 case CXXMoveConstructor:
Sebastian Redl22653ba2011-08-30 19:58:05 +00003685 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Alexis Hunt119c10e2011-05-25 23:16:36 +00003686 break;
3687
Sebastian Redl22653ba2011-08-30 19:58:05 +00003688 case CXXMoveAssignment:
3689 CheckExplicitlyDefaultedMoveAssignment(*MI);
3690 break;
3691
3692 case CXXInvalid:
Alexis Huntf91729462011-05-12 22:46:25 +00003693 llvm_unreachable("non-special member explicitly defaulted!");
3694 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003695 }
3696 }
3697
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003698}
3699
3700void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3701 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3702
3703 // Whether this was the first-declared instance of the constructor.
3704 // This affects whether we implicitly add an exception spec (and, eventually,
3705 // constexpr). It is also ill-formed to explicitly default a constructor such
3706 // that it would be deleted. (C++0x [decl.fct.def.default])
3707 bool First = CD == CD->getCanonicalDecl();
3708
Alexis Hunt913820d2011-05-13 06:10:58 +00003709 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003710 if (CD->getNumParams() != 0) {
3711 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3712 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003713 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003714 }
3715
3716 ImplicitExceptionSpecification Spec
3717 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3718 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003719 if (EPI.ExceptionSpecType == EST_Delayed) {
3720 // Exception specification depends on some deferred part of the class. We'll
3721 // try again when the class's definition has been fully processed.
3722 return;
3723 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003724 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3725 *ExceptionType = Context.getFunctionType(
3726 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3727
3728 if (CtorType->hasExceptionSpec()) {
3729 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003730 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003731 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003732 PDiag(),
3733 ExceptionType, SourceLocation(),
3734 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003735 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003736 }
3737 } else if (First) {
3738 // We set the declaration to have the computed exception spec here.
3739 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003740 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003741 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3742 }
Alexis Huntb3153022011-05-12 03:51:48 +00003743
Alexis Hunt913820d2011-05-13 06:10:58 +00003744 if (HadError) {
3745 CD->setInvalidDecl();
3746 return;
3747 }
3748
Alexis Huntd6da8762011-10-10 06:18:57 +00003749 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003750 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003751 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003752 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003753 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003754 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003755 CD->setInvalidDecl();
3756 }
3757 }
3758}
3759
3760void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3761 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3762
3763 // Whether this was the first-declared instance of the constructor.
3764 bool First = CD == CD->getCanonicalDecl();
3765
3766 bool HadError = false;
3767 if (CD->getNumParams() != 1) {
3768 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3769 << CD->getSourceRange();
3770 HadError = true;
3771 }
3772
3773 ImplicitExceptionSpecification Spec(Context);
3774 bool Const;
3775 llvm::tie(Spec, Const) =
3776 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3777
3778 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3779 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3780 *ExceptionType = Context.getFunctionType(
3781 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3782
3783 // Check for parameter type matching.
3784 // This is a copy ctor so we know it's a cv-qualified reference to T.
3785 QualType ArgType = CtorType->getArgType(0);
3786 if (ArgType->getPointeeType().isVolatileQualified()) {
3787 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3788 HadError = true;
3789 }
3790 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3791 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3792 HadError = true;
3793 }
3794
3795 if (CtorType->hasExceptionSpec()) {
3796 if (CheckEquivalentExceptionSpec(
3797 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003798 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003799 PDiag(),
3800 ExceptionType, SourceLocation(),
3801 CtorType, CD->getLocation())) {
3802 HadError = true;
3803 }
3804 } else if (First) {
3805 // We set the declaration to have the computed exception spec here.
3806 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003807 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003808 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3809 }
3810
3811 if (HadError) {
3812 CD->setInvalidDecl();
3813 return;
3814 }
3815
Alexis Hunt1bc6f712011-10-11 04:55:36 +00003816 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003817 if (First) {
3818 CD->setDeletedAsWritten();
3819 } else {
3820 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003821 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003822 CD->setInvalidDecl();
3823 }
Alexis Huntb3153022011-05-12 03:51:48 +00003824 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003825}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003826
Alexis Huntc9a55732011-05-14 05:23:28 +00003827void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3828 assert(MD->isExplicitlyDefaulted());
3829
3830 // Whether this was the first-declared instance of the operator
3831 bool First = MD == MD->getCanonicalDecl();
3832
3833 bool HadError = false;
3834 if (MD->getNumParams() != 1) {
3835 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3836 << MD->getSourceRange();
3837 HadError = true;
3838 }
3839
3840 QualType ReturnType =
3841 MD->getType()->getAs<FunctionType>()->getResultType();
3842 if (!ReturnType->isLValueReferenceType() ||
3843 !Context.hasSameType(
3844 Context.getCanonicalType(ReturnType->getPointeeType()),
3845 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3846 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3847 HadError = true;
3848 }
3849
3850 ImplicitExceptionSpecification Spec(Context);
3851 bool Const;
3852 llvm::tie(Spec, Const) =
3853 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3854
3855 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3856 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3857 *ExceptionType = Context.getFunctionType(
3858 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3859
Alexis Huntc9a55732011-05-14 05:23:28 +00003860 QualType ArgType = OperType->getArgType(0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003861 if (!ArgType->isLValueReferenceType()) {
Alexis Hunt604aeb32011-05-17 20:44:43 +00003862 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003863 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003864 } else {
3865 if (ArgType->getPointeeType().isVolatileQualified()) {
3866 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3867 HadError = true;
3868 }
3869 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3870 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3871 HadError = true;
3872 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003873 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003874
Alexis Huntc9a55732011-05-14 05:23:28 +00003875 if (OperType->getTypeQuals()) {
3876 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3877 HadError = true;
3878 }
3879
3880 if (OperType->hasExceptionSpec()) {
3881 if (CheckEquivalentExceptionSpec(
3882 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003883 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003884 PDiag(),
3885 ExceptionType, SourceLocation(),
3886 OperType, MD->getLocation())) {
3887 HadError = true;
3888 }
3889 } else if (First) {
3890 // We set the declaration to have the computed exception spec here.
3891 // We duplicate the one parameter type.
3892 EPI.RefQualifier = OperType->getRefQualifier();
3893 EPI.ExtInfo = OperType->getExtInfo();
3894 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3895 }
3896
3897 if (HadError) {
3898 MD->setInvalidDecl();
3899 return;
3900 }
3901
3902 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3903 if (First) {
3904 MD->setDeletedAsWritten();
3905 } else {
3906 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003907 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003908 MD->setInvalidDecl();
3909 }
3910 }
3911}
3912
Sebastian Redl22653ba2011-08-30 19:58:05 +00003913void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3914 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3915
3916 // Whether this was the first-declared instance of the constructor.
3917 bool First = CD == CD->getCanonicalDecl();
3918
3919 bool HadError = false;
3920 if (CD->getNumParams() != 1) {
3921 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3922 << CD->getSourceRange();
3923 HadError = true;
3924 }
3925
3926 ImplicitExceptionSpecification Spec(
3927 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3928
3929 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3930 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3931 *ExceptionType = Context.getFunctionType(
3932 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3933
3934 // Check for parameter type matching.
3935 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3936 QualType ArgType = CtorType->getArgType(0);
3937 if (ArgType->getPointeeType().isVolatileQualified()) {
3938 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3939 HadError = true;
3940 }
3941 if (ArgType->getPointeeType().isConstQualified()) {
3942 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3943 HadError = true;
3944 }
3945
3946 if (CtorType->hasExceptionSpec()) {
3947 if (CheckEquivalentExceptionSpec(
3948 PDiag(diag::err_incorrect_defaulted_exception_spec)
3949 << CXXMoveConstructor,
3950 PDiag(),
3951 ExceptionType, SourceLocation(),
3952 CtorType, CD->getLocation())) {
3953 HadError = true;
3954 }
3955 } else if (First) {
3956 // We set the declaration to have the computed exception spec here.
3957 // We duplicate the one parameter type.
3958 EPI.ExtInfo = CtorType->getExtInfo();
3959 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3960 }
3961
3962 if (HadError) {
3963 CD->setInvalidDecl();
3964 return;
3965 }
3966
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00003967 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003968 if (First) {
3969 CD->setDeletedAsWritten();
3970 } else {
3971 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3972 << CXXMoveConstructor;
3973 CD->setInvalidDecl();
3974 }
3975 }
3976}
3977
3978void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3979 assert(MD->isExplicitlyDefaulted());
3980
3981 // Whether this was the first-declared instance of the operator
3982 bool First = MD == MD->getCanonicalDecl();
3983
3984 bool HadError = false;
3985 if (MD->getNumParams() != 1) {
3986 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3987 << MD->getSourceRange();
3988 HadError = true;
3989 }
3990
3991 QualType ReturnType =
3992 MD->getType()->getAs<FunctionType>()->getResultType();
3993 if (!ReturnType->isLValueReferenceType() ||
3994 !Context.hasSameType(
3995 Context.getCanonicalType(ReturnType->getPointeeType()),
3996 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3997 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3998 HadError = true;
3999 }
4000
4001 ImplicitExceptionSpecification Spec(
4002 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4003
4004 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4005 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4006 *ExceptionType = Context.getFunctionType(
4007 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4008
4009 QualType ArgType = OperType->getArgType(0);
4010 if (!ArgType->isRValueReferenceType()) {
4011 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4012 HadError = true;
4013 } else {
4014 if (ArgType->getPointeeType().isVolatileQualified()) {
4015 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4016 HadError = true;
4017 }
4018 if (ArgType->getPointeeType().isConstQualified()) {
4019 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4020 HadError = true;
4021 }
4022 }
4023
4024 if (OperType->getTypeQuals()) {
4025 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4026 HadError = true;
4027 }
4028
4029 if (OperType->hasExceptionSpec()) {
4030 if (CheckEquivalentExceptionSpec(
4031 PDiag(diag::err_incorrect_defaulted_exception_spec)
4032 << CXXMoveAssignment,
4033 PDiag(),
4034 ExceptionType, SourceLocation(),
4035 OperType, MD->getLocation())) {
4036 HadError = true;
4037 }
4038 } else if (First) {
4039 // We set the declaration to have the computed exception spec here.
4040 // We duplicate the one parameter type.
4041 EPI.RefQualifier = OperType->getRefQualifier();
4042 EPI.ExtInfo = OperType->getExtInfo();
4043 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4044 }
4045
4046 if (HadError) {
4047 MD->setInvalidDecl();
4048 return;
4049 }
4050
4051 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4052 if (First) {
4053 MD->setDeletedAsWritten();
4054 } else {
4055 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4056 << CXXMoveAssignment;
4057 MD->setInvalidDecl();
4058 }
4059 }
4060}
4061
Alexis Huntf91729462011-05-12 22:46:25 +00004062void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4063 assert(DD->isExplicitlyDefaulted());
4064
4065 // Whether this was the first-declared instance of the destructor.
4066 bool First = DD == DD->getCanonicalDecl();
4067
4068 ImplicitExceptionSpecification Spec
4069 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4070 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4071 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4072 *ExceptionType = Context.getFunctionType(
4073 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4074
4075 if (DtorType->hasExceptionSpec()) {
4076 if (CheckEquivalentExceptionSpec(
4077 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004078 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00004079 PDiag(),
4080 ExceptionType, SourceLocation(),
4081 DtorType, DD->getLocation())) {
4082 DD->setInvalidDecl();
4083 return;
4084 }
4085 } else if (First) {
4086 // We set the declaration to have the computed exception spec here.
4087 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00004088 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00004089 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4090 }
4091
4092 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00004093 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004094 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00004095 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00004096 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004097 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00004098 DD->setInvalidDecl();
4099 }
Alexis Huntf91729462011-05-12 22:46:25 +00004100 }
Alexis Huntf91729462011-05-12 22:46:25 +00004101}
4102
Alexis Huntd6da8762011-10-10 06:18:57 +00004103/// This function implements the following C++0x paragraphs:
4104/// - [class.ctor]/5
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004105/// - [class.copy]/11
Alexis Huntd6da8762011-10-10 06:18:57 +00004106bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4107 assert(!MD->isInvalidDecl());
4108 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00004109 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004110 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00004111 return false;
4112
Alexis Huntd6da8762011-10-10 06:18:57 +00004113 bool IsUnion = RD->isUnion();
4114 bool IsConstructor = false;
4115 bool IsAssignment = false;
4116 bool IsMove = false;
4117
4118 bool ConstArg = false;
4119
4120 switch (CSM) {
4121 case CXXDefaultConstructor:
4122 IsConstructor = true;
4123 break;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004124 case CXXCopyConstructor:
4125 IsConstructor = true;
4126 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4127 break;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004128 case CXXMoveConstructor:
4129 IsConstructor = true;
4130 IsMove = true;
4131 break;
Alexis Huntd6da8762011-10-10 06:18:57 +00004132 default:
4133 llvm_unreachable("function only currently implemented for default ctors");
4134 }
4135
4136 SourceLocation Loc = MD->getLocation();
Alexis Hunte77a28f2011-05-18 03:41:58 +00004137
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004138 // Do access control from the special member function
Alexis Huntd6da8762011-10-10 06:18:57 +00004139 ContextRAII MethodContext(*this, MD);
Alexis Huntea6f0322011-05-11 22:34:38 +00004140
Alexis Huntea6f0322011-05-11 22:34:38 +00004141 bool AllConst = true;
4142
Alexis Huntea6f0322011-05-11 22:34:38 +00004143 // We do this because we should never actually use an anonymous
4144 // union's constructor.
Alexis Huntd6da8762011-10-10 06:18:57 +00004145 if (IsUnion && RD->isAnonymousStructOrUnion())
Alexis Huntea6f0322011-05-11 22:34:38 +00004146 return false;
4147
4148 // FIXME: We should put some diagnostic logic right into this function.
4149
Alexis Huntea6f0322011-05-11 22:34:38 +00004150 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4151 BE = RD->bases_end();
4152 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00004153 // We'll handle this one later
4154 if (BI->isVirtual())
4155 continue;
4156
Alexis Huntea6f0322011-05-11 22:34:38 +00004157 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4158 assert(BaseDecl && "base isn't a CXXRecordDecl");
4159
Alexis Huntd6da8762011-10-10 06:18:57 +00004160 // Unless we have an assignment operator, the base's destructor must
4161 // be accessible and not deleted.
4162 if (!IsAssignment) {
4163 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4164 if (BaseDtor->isDeleted())
4165 return true;
4166 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4167 AR_accessible)
4168 return true;
4169 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004170
Alexis Huntd6da8762011-10-10 06:18:57 +00004171 // Finding the corresponding member in the base should lead to a
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004172 // unique, accessible, non-deleted function. If we are doing
4173 // a destructor, we have already checked this case.
Alexis Huntd6da8762011-10-10 06:18:57 +00004174 if (CSM != CXXDestructor) {
4175 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004176 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004177 false);
4178 if (!SMOR->hasSuccess())
4179 return true;
4180 CXXMethodDecl *BaseMember = SMOR->getMethod();
4181 if (IsConstructor) {
4182 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4183 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4184 PDiag()) != AR_accessible)
4185 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004186
4187 // For a move operation, the corresponding operation must actually
4188 // be a move operation (and not a copy selected by overload
4189 // resolution) unless we are working on a trivially copyable class.
4190 if (IsMove && !BaseCtor->isMoveConstructor() &&
4191 !BaseDecl->isTriviallyCopyable())
4192 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004193 }
4194 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004195 }
4196
4197 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4198 BE = RD->vbases_end();
4199 BI != BE; ++BI) {
4200 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4201 assert(BaseDecl && "base isn't a CXXRecordDecl");
4202
Alexis Huntd6da8762011-10-10 06:18:57 +00004203 // Unless we have an assignment operator, the base's destructor must
4204 // be accessible and not deleted.
4205 if (!IsAssignment) {
4206 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4207 if (BaseDtor->isDeleted())
4208 return true;
4209 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4210 AR_accessible)
4211 return true;
4212 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004213
Alexis Huntd6da8762011-10-10 06:18:57 +00004214 // Finding the corresponding member in the base should lead to a
4215 // unique, accessible, non-deleted function.
4216 if (CSM != CXXDestructor) {
4217 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004218 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004219 false);
4220 if (!SMOR->hasSuccess())
4221 return true;
4222 CXXMethodDecl *BaseMember = SMOR->getMethod();
4223 if (IsConstructor) {
4224 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4225 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4226 PDiag()) != AR_accessible)
4227 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004228
4229 // For a move operation, the corresponding operation must actually
4230 // be a move operation (and not a copy selected by overload
4231 // resolution) unless we are working on a trivially copyable class.
4232 if (IsMove && !BaseCtor->isMoveConstructor() &&
4233 !BaseDecl->isTriviallyCopyable())
4234 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004235 }
4236 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004237 }
4238
4239 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4240 FE = RD->field_end();
4241 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004242 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004243 continue;
4244
Alexis Huntea6f0322011-05-11 22:34:38 +00004245 QualType FieldType = Context.getBaseElementType(FI->getType());
4246 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00004247
Alexis Huntd6da8762011-10-10 06:18:57 +00004248 // For a default constructor, all references must be initialized in-class
4249 // and, if a union, it must have a non-const member.
4250 if (CSM == CXXDefaultConstructor) {
4251 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4252 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004253
Alexis Huntd6da8762011-10-10 06:18:57 +00004254 if (IsUnion && !FieldType.isConstQualified())
4255 AllConst = false;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004256 // For a copy constructor, data members must not be of rvalue reference
4257 // type.
4258 } else if (CSM == CXXCopyConstructor) {
4259 if (FieldType->isRValueReferenceType())
4260 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004261 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004262
4263 if (FieldRecord) {
Alexis Huntd6da8762011-10-10 06:18:57 +00004264 // For a default constructor, a const member must have a user-provided
4265 // default constructor or else be explicitly initialized.
4266 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00004267 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004268 !FieldRecord->hasUserProvidedDefaultConstructor())
4269 return true;
4270
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004271 // Some additional restrictions exist on the variant members.
4272 if (!IsUnion && FieldRecord->isUnion() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004273 FieldRecord->isAnonymousStructOrUnion()) {
4274 // We're okay to reuse AllConst here since we only care about the
4275 // value otherwise if we're in a union.
4276 AllConst = true;
4277
4278 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4279 UE = FieldRecord->field_end();
4280 UI != UE; ++UI) {
4281 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4282 CXXRecordDecl *UnionFieldRecord =
4283 UnionFieldType->getAsCXXRecordDecl();
4284
4285 if (!UnionFieldType.isConstQualified())
4286 AllConst = false;
4287
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004288 if (UnionFieldRecord) {
4289 // FIXME: Checking for accessibility and validity of this
4290 // destructor is technically going beyond the
4291 // standard, but this is believed to be a defect.
4292 if (!IsAssignment) {
4293 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4294 if (FieldDtor->isDeleted())
4295 return true;
4296 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4297 AR_accessible)
4298 return true;
4299 if (!FieldDtor->isTrivial())
4300 return true;
4301 }
4302
4303 if (CSM != CXXDestructor) {
4304 SpecialMemberOverloadResult *SMOR =
4305 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004306 false, false, false);
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004307 // FIXME: Checking for accessibility and validity of this
4308 // corresponding member is technically going beyond the
4309 // standard, but this is believed to be a defect.
4310 if (!SMOR->hasSuccess())
4311 return true;
4312
4313 CXXMethodDecl *FieldMember = SMOR->getMethod();
4314 // A member of a union must have a trivial corresponding
4315 // constructor.
4316 if (!FieldMember->isTrivial())
4317 return true;
4318
4319 if (IsConstructor) {
4320 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4321 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4322 PDiag()) != AR_accessible)
4323 return true;
4324 }
4325 }
4326 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004327 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00004328
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004329 // At least one member in each anonymous union must be non-const
4330 if (CSM == CXXDefaultConstructor && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004331 return true;
4332
4333 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00004334 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00004335 continue;
4336 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00004337
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004338 // Unless we're doing assignment, the field's destructor must be
4339 // accessible and not deleted.
4340 if (!IsAssignment) {
4341 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4342 if (FieldDtor->isDeleted())
4343 return true;
4344 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4345 AR_accessible)
4346 return true;
4347 }
4348
Alexis Huntd6da8762011-10-10 06:18:57 +00004349 // Check that the corresponding member of the field is accessible,
4350 // unique, and non-deleted. We don't do this if it has an explicit
4351 // initialization when default-constructing.
4352 if (CSM != CXXDestructor &&
4353 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4354 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004355 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004356 false);
4357 if (!SMOR->hasSuccess())
Richard Smith938f40b2011-06-11 17:19:42 +00004358 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004359
4360 CXXMethodDecl *FieldMember = SMOR->getMethod();
4361 if (IsConstructor) {
4362 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4363 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4364 PDiag()) != AR_accessible)
4365 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004366
4367 // For a move operation, the corresponding operation must actually
4368 // be a move operation (and not a copy selected by overload
4369 // resolution) unless we are working on a trivially copyable class.
4370 if (IsMove && !FieldCtor->isMoveConstructor() &&
4371 !FieldRecord->isTriviallyCopyable())
4372 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004373 }
4374
4375 // We need the corresponding member of a union to be trivial so that
4376 // we can safely copy them all simultaneously.
4377 // FIXME: Note that performing the check here (where we rely on the lack
4378 // of an in-class initializer) is technically ill-formed. However, this
4379 // seems most obviously to be a bug in the standard.
4380 if (IsUnion && !FieldMember->isTrivial())
Richard Smith938f40b2011-06-11 17:19:42 +00004381 return true;
4382 }
Alexis Huntd6da8762011-10-10 06:18:57 +00004383 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4384 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4385 // We can't initialize a const member of non-class type to any value.
Alexis Hunta671bca2011-05-20 21:43:47 +00004386 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004387 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004388 }
4389
Alexis Huntd6da8762011-10-10 06:18:57 +00004390 // We can't have all const members in a union when default-constructing,
4391 // or else they're all nonsensical garbage values that can't be changed.
4392 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004393 return true;
4394
4395 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004396}
4397
Alexis Huntb2f27802011-05-14 05:23:24 +00004398bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4399 CXXRecordDecl *RD = MD->getParent();
4400 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004401 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntb2f27802011-05-14 05:23:24 +00004402 return false;
4403
Alexis Hunte77a28f2011-05-18 03:41:58 +00004404 SourceLocation Loc = MD->getLocation();
4405
Alexis Huntb2f27802011-05-14 05:23:24 +00004406 // Do access control from the constructor
4407 ContextRAII MethodContext(*this, MD);
4408
4409 bool Union = RD->isUnion();
4410
Alexis Hunt491ec602011-06-21 23:42:56 +00004411 unsigned ArgQuals =
4412 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4413 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00004414
4415 // We do this because we should never actually use an anonymous
4416 // union's constructor.
4417 if (Union && RD->isAnonymousStructOrUnion())
4418 return false;
4419
Alexis Huntb2f27802011-05-14 05:23:24 +00004420 // FIXME: We should put some diagnostic logic right into this function.
4421
Sebastian Redl22653ba2011-08-30 19:58:05 +00004422 // C++0x [class.copy]/20
Alexis Huntb2f27802011-05-14 05:23:24 +00004423 // A defaulted [copy] assignment operator for class X is defined as deleted
4424 // if X has:
4425
4426 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4427 BE = RD->bases_end();
4428 BI != BE; ++BI) {
4429 // We'll handle this one later
4430 if (BI->isVirtual())
4431 continue;
4432
4433 QualType BaseType = BI->getType();
4434 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4435 assert(BaseDecl && "base isn't a CXXRecordDecl");
4436
4437 // -- a [direct base class] B that cannot be [copied] because overload
4438 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00004439 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00004440 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004441 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4442 0);
4443 if (!CopyOper || CopyOper->isDeleted())
4444 return true;
4445 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004446 return true;
4447 }
4448
4449 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4450 BE = RD->vbases_end();
4451 BI != BE; ++BI) {
4452 QualType BaseType = BI->getType();
4453 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4454 assert(BaseDecl && "base isn't a CXXRecordDecl");
4455
Alexis Huntb2f27802011-05-14 05:23:24 +00004456 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00004457 // resolution, as applied to B's [copy] assignment operator, results in
4458 // an ambiguity or a function that is deleted or inaccessible from the
4459 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004460 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4461 0);
4462 if (!CopyOper || CopyOper->isDeleted())
4463 return true;
4464 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004465 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00004466 }
4467
4468 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4469 FE = RD->field_end();
4470 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004471 if (FI->isUnnamedBitfield())
4472 continue;
4473
Alexis Huntb2f27802011-05-14 05:23:24 +00004474 QualType FieldType = Context.getBaseElementType(FI->getType());
4475
4476 // -- a non-static data member of reference type
4477 if (FieldType->isReferenceType())
4478 return true;
4479
4480 // -- a non-static data member of const non-class type (or array thereof)
4481 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4482 return true;
4483
4484 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4485
4486 if (FieldRecord) {
4487 // This is an anonymous union
4488 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4489 // Anonymous unions inside unions do not variant members create
4490 if (!Union) {
4491 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4492 UE = FieldRecord->field_end();
4493 UI != UE; ++UI) {
4494 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4495 CXXRecordDecl *UnionFieldRecord =
4496 UnionFieldType->getAsCXXRecordDecl();
4497
4498 // -- a variant member with a non-trivial [copy] assignment operator
4499 // and X is a union-like class
4500 if (UnionFieldRecord &&
4501 !UnionFieldRecord->hasTrivialCopyAssignment())
4502 return true;
4503 }
4504 }
4505
4506 // Don't try to initalize an anonymous union
4507 continue;
4508 // -- a variant member with a non-trivial [copy] assignment operator
4509 // and X is a union-like class
4510 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4511 return true;
4512 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004513
Alexis Hunt491ec602011-06-21 23:42:56 +00004514 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4515 false, 0);
4516 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl22653ba2011-08-30 19:58:05 +00004517 return true;
Alexis Hunt491ec602011-06-21 23:42:56 +00004518 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl22653ba2011-08-30 19:58:05 +00004519 return true;
4520 }
4521 }
4522
4523 return false;
4524}
4525
Sebastian Redl22653ba2011-08-30 19:58:05 +00004526bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4527 CXXRecordDecl *RD = MD->getParent();
4528 assert(!RD->isDependentType() && "do deletion after instantiation");
4529 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4530 return false;
4531
4532 SourceLocation Loc = MD->getLocation();
4533
4534 // Do access control from the constructor
4535 ContextRAII MethodContext(*this, MD);
4536
4537 bool Union = RD->isUnion();
4538
4539 // We do this because we should never actually use an anonymous
4540 // union's constructor.
4541 if (Union && RD->isAnonymousStructOrUnion())
4542 return false;
4543
4544 // C++0x [class.copy]/20
4545 // A defaulted [move] assignment operator for class X is defined as deleted
4546 // if X has:
4547
4548 // -- for the move constructor, [...] any direct or indirect virtual base
4549 // class.
4550 if (RD->getNumVBases() != 0)
4551 return true;
4552
4553 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4554 BE = RD->bases_end();
4555 BI != BE; ++BI) {
4556
4557 QualType BaseType = BI->getType();
4558 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4559 assert(BaseDecl && "base isn't a CXXRecordDecl");
4560
4561 // -- a [direct base class] B that cannot be [moved] because overload
4562 // resolution, as applied to B's [move] assignment operator, results in
4563 // an ambiguity or a function that is deleted or inaccessible from the
4564 // assignment operator
4565 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4566 if (!MoveOper || MoveOper->isDeleted())
4567 return true;
4568 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4569 return true;
4570
4571 // -- for the move assignment operator, a [direct base class] with a type
4572 // that does not have a move assignment operator and is not trivially
4573 // copyable.
4574 if (!MoveOper->isMoveAssignmentOperator() &&
4575 !BaseDecl->isTriviallyCopyable())
4576 return true;
4577 }
4578
4579 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4580 FE = RD->field_end();
4581 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004582 if (FI->isUnnamedBitfield())
4583 continue;
4584
Sebastian Redl22653ba2011-08-30 19:58:05 +00004585 QualType FieldType = Context.getBaseElementType(FI->getType());
4586
4587 // -- a non-static data member of reference type
4588 if (FieldType->isReferenceType())
4589 return true;
4590
4591 // -- a non-static data member of const non-class type (or array thereof)
4592 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4593 return true;
4594
4595 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4596
4597 if (FieldRecord) {
4598 // This is an anonymous union
4599 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4600 // Anonymous unions inside unions do not variant members create
4601 if (!Union) {
4602 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4603 UE = FieldRecord->field_end();
4604 UI != UE; ++UI) {
4605 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4606 CXXRecordDecl *UnionFieldRecord =
4607 UnionFieldType->getAsCXXRecordDecl();
4608
4609 // -- a variant member with a non-trivial [move] assignment operator
4610 // and X is a union-like class
4611 if (UnionFieldRecord &&
4612 !UnionFieldRecord->hasTrivialMoveAssignment())
4613 return true;
4614 }
4615 }
4616
4617 // Don't try to initalize an anonymous union
4618 continue;
4619 // -- a variant member with a non-trivial [move] assignment operator
4620 // and X is a union-like class
4621 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4622 return true;
4623 }
4624
4625 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4626 if (!MoveOper || MoveOper->isDeleted())
4627 return true;
4628 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4629 return true;
4630
4631 // -- for the move assignment operator, a [non-static data member] with a
4632 // type that does not have a move assignment operator and is not
4633 // trivially copyable.
4634 if (!MoveOper->isMoveAssignmentOperator() &&
4635 !FieldRecord->isTriviallyCopyable())
4636 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004637 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004638 }
4639
4640 return false;
4641}
4642
Alexis Huntf91729462011-05-12 22:46:25 +00004643bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4644 CXXRecordDecl *RD = DD->getParent();
4645 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004646 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntf91729462011-05-12 22:46:25 +00004647 return false;
4648
Alexis Hunte77a28f2011-05-18 03:41:58 +00004649 SourceLocation Loc = DD->getLocation();
4650
Alexis Huntf91729462011-05-12 22:46:25 +00004651 // Do access control from the destructor
4652 ContextRAII CtorContext(*this, DD);
4653
4654 bool Union = RD->isUnion();
4655
Alexis Hunt913820d2011-05-13 06:10:58 +00004656 // We do this because we should never actually use an anonymous
4657 // union's destructor.
4658 if (Union && RD->isAnonymousStructOrUnion())
4659 return false;
4660
Alexis Huntf91729462011-05-12 22:46:25 +00004661 // C++0x [class.dtor]p5
4662 // A defaulted destructor for a class X is defined as deleted if:
4663 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4664 BE = RD->bases_end();
4665 BI != BE; ++BI) {
4666 // We'll handle this one later
4667 if (BI->isVirtual())
4668 continue;
4669
4670 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4671 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4672 assert(BaseDtor && "base has no destructor");
4673
4674 // -- any direct or virtual base class has a deleted destructor or
4675 // a destructor that is inaccessible from the defaulted destructor
4676 if (BaseDtor->isDeleted())
4677 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004678 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004679 AR_accessible)
4680 return true;
4681 }
4682
4683 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4684 BE = RD->vbases_end();
4685 BI != BE; ++BI) {
4686 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4687 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4688 assert(BaseDtor && "base has no destructor");
4689
4690 // -- any direct or virtual base class has a deleted destructor or
4691 // a destructor that is inaccessible from the defaulted destructor
4692 if (BaseDtor->isDeleted())
4693 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004694 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004695 AR_accessible)
4696 return true;
4697 }
4698
4699 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4700 FE = RD->field_end();
4701 FI != FE; ++FI) {
4702 QualType FieldType = Context.getBaseElementType(FI->getType());
4703 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4704 if (FieldRecord) {
4705 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4706 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4707 UE = FieldRecord->field_end();
4708 UI != UE; ++UI) {
4709 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4710 CXXRecordDecl *UnionFieldRecord =
4711 UnionFieldType->getAsCXXRecordDecl();
4712
4713 // -- X is a union-like class that has a variant member with a non-
4714 // trivial destructor.
4715 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4716 return true;
4717 }
4718 // Technically we are supposed to do this next check unconditionally.
4719 // But that makes absolutely no sense.
4720 } else {
4721 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4722
4723 // -- any of the non-static data members has class type M (or array
4724 // thereof) and M has a deleted destructor or a destructor that is
4725 // inaccessible from the defaulted destructor
4726 if (FieldDtor->isDeleted())
4727 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004728 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004729 AR_accessible)
4730 return true;
4731
4732 // -- X is a union-like class that has a variant member with a non-
4733 // trivial destructor.
4734 if (Union && !FieldDtor->isTrivial())
4735 return true;
4736 }
4737 }
4738 }
4739
4740 if (DD->isVirtual()) {
4741 FunctionDecl *OperatorDelete = 0;
4742 DeclarationName Name =
4743 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004744 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004745 false))
4746 return true;
4747 }
4748
4749
4750 return false;
4751}
4752
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004753/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004754namespace {
4755 struct FindHiddenVirtualMethodData {
4756 Sema *S;
4757 CXXMethodDecl *Method;
4758 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004759 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00004760 };
4761}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004762
4763/// \brief Member lookup function that determines whether a given C++
4764/// method overloads virtual methods in a base class without overriding any,
4765/// to be used with CXXRecordDecl::lookupInBases().
4766static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4767 CXXBasePath &Path,
4768 void *UserData) {
4769 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4770
4771 FindHiddenVirtualMethodData &Data
4772 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4773
4774 DeclarationName Name = Data.Method->getDeclName();
4775 assert(Name.getNameKind() == DeclarationName::Identifier);
4776
4777 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004778 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004779 for (Path.Decls = BaseRecord->lookup(Name);
4780 Path.Decls.first != Path.Decls.second;
4781 ++Path.Decls.first) {
4782 NamedDecl *D = *Path.Decls.first;
4783 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004784 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004785 foundSameNameMethod = true;
4786 // Interested only in hidden virtual methods.
4787 if (!MD->isVirtual())
4788 continue;
4789 // If the method we are checking overrides a method from its base
4790 // don't warn about the other overloaded methods.
4791 if (!Data.S->IsOverload(Data.Method, MD, false))
4792 return true;
4793 // Collect the overload only if its hidden.
4794 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4795 overloadedMethods.push_back(MD);
4796 }
4797 }
4798
4799 if (foundSameNameMethod)
4800 Data.OverloadedMethods.append(overloadedMethods.begin(),
4801 overloadedMethods.end());
4802 return foundSameNameMethod;
4803}
4804
4805/// \brief See if a method overloads virtual methods in a base class without
4806/// overriding any.
4807void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4808 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikie9c902b52011-09-25 23:23:43 +00004809 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004810 return;
4811 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4812 return;
4813
4814 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4815 /*bool RecordPaths=*/false,
4816 /*bool DetectVirtual=*/false);
4817 FindHiddenVirtualMethodData Data;
4818 Data.Method = MD;
4819 Data.S = this;
4820
4821 // Keep the base methods that were overriden or introduced in the subclass
4822 // by 'using' in a set. A base method not in this set is hidden.
4823 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4824 res.first != res.second; ++res.first) {
4825 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4826 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4827 E = MD->end_overridden_methods();
4828 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004829 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004830 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4831 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004832 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004833 }
4834
4835 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4836 !Data.OverloadedMethods.empty()) {
4837 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4838 << MD << (Data.OverloadedMethods.size() > 1);
4839
4840 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4841 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4842 Diag(overloadedMD->getLocation(),
4843 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4844 }
4845 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00004846}
4847
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004848void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00004849 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004850 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004851 SourceLocation RBrac,
4852 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004853 if (!TagDecl)
4854 return;
Mike Stump11289f42009-09-09 15:08:12 +00004855
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004856 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00004857
David Blaikie751c5582011-09-22 02:58:26 +00004858 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00004859 // strict aliasing violation!
4860 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00004861 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00004862
Douglas Gregor0be31a22010-07-02 17:43:08 +00004863 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00004864 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004865}
4866
Douglas Gregor05379422008-11-03 17:51:48 +00004867/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4868/// special functions, such as the default constructor, copy
4869/// constructor, or destructor, to the given C++ class (C++
4870/// [special]p1). This routine can only be executed just before the
4871/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004872void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004873 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00004874 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004875
Douglas Gregor54be3392010-07-01 17:57:27 +00004876 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00004877 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004878
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004879 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4880 ++ASTContext::NumImplicitCopyAssignmentOperators;
4881
4882 // If we have a dynamic class, then the copy assignment operator may be
4883 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4884 // it shows up in the right place in the vtable and that we diagnose
4885 // problems with the implicit exception specification.
4886 if (ClassDecl->isDynamicClass())
4887 DeclareImplicitCopyAssignment(ClassDecl);
4888 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004889
Douglas Gregor7454c562010-07-02 20:37:36 +00004890 if (!ClassDecl->hasUserDeclaredDestructor()) {
4891 ++ASTContext::NumImplicitDestructors;
4892
4893 // If we have a dynamic class, then the destructor may be virtual, so we
4894 // have to declare the destructor immediately. This ensures that, e.g., it
4895 // shows up in the right place in the vtable and that we diagnose problems
4896 // with the implicit exception specification.
4897 if (ClassDecl->isDynamicClass())
4898 DeclareImplicitDestructor(ClassDecl);
4899 }
Douglas Gregor05379422008-11-03 17:51:48 +00004900}
4901
Francois Pichet1c229c02011-04-22 22:18:13 +00004902void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4903 if (!D)
4904 return;
4905
4906 int NumParamList = D->getNumTemplateParameterLists();
4907 for (int i = 0; i < NumParamList; i++) {
4908 TemplateParameterList* Params = D->getTemplateParameterList(i);
4909 for (TemplateParameterList::iterator Param = Params->begin(),
4910 ParamEnd = Params->end();
4911 Param != ParamEnd; ++Param) {
4912 NamedDecl *Named = cast<NamedDecl>(*Param);
4913 if (Named->getDeclName()) {
4914 S->AddDecl(Named);
4915 IdResolver.AddDecl(Named);
4916 }
4917 }
4918 }
4919}
4920
John McCall48871652010-08-21 09:40:31 +00004921void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00004922 if (!D)
4923 return;
4924
4925 TemplateParameterList *Params = 0;
4926 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4927 Params = Template->getTemplateParameters();
4928 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4929 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4930 Params = PartialSpec->getTemplateParameters();
4931 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004932 return;
4933
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004934 for (TemplateParameterList::iterator Param = Params->begin(),
4935 ParamEnd = Params->end();
4936 Param != ParamEnd; ++Param) {
4937 NamedDecl *Named = cast<NamedDecl>(*Param);
4938 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00004939 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004940 IdResolver.AddDecl(Named);
4941 }
4942 }
4943}
4944
John McCall48871652010-08-21 09:40:31 +00004945void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004946 if (!RecordD) return;
4947 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00004948 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00004949 PushDeclContext(S, Record);
4950}
4951
John McCall48871652010-08-21 09:40:31 +00004952void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004953 if (!RecordD) return;
4954 PopDeclContext();
4955}
4956
Douglas Gregor4d87df52008-12-16 21:30:33 +00004957/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4958/// parsing a top-level (non-nested) C++ class, and we are now
4959/// parsing those parts of the given Method declaration that could
4960/// not be parsed earlier (C++ [class.mem]p2), such as default
4961/// arguments. This action should enter the scope of the given
4962/// Method declaration as if we had just parsed the qualified method
4963/// name. However, it should not bring the parameters into scope;
4964/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00004965void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004966}
4967
4968/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4969/// C++ method declaration. We're (re-)introducing the given
4970/// function parameter into scope for use in parsing later parts of
4971/// the method declaration. For example, we could see an
4972/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00004973void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004974 if (!ParamD)
4975 return;
Mike Stump11289f42009-09-09 15:08:12 +00004976
John McCall48871652010-08-21 09:40:31 +00004977 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00004978
4979 // If this parameter has an unparsed default argument, clear it out
4980 // to make way for the parsed default argument.
4981 if (Param->hasUnparsedDefaultArg())
4982 Param->setDefaultArg(0);
4983
John McCall48871652010-08-21 09:40:31 +00004984 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004985 if (Param->getDeclName())
4986 IdResolver.AddDecl(Param);
4987}
4988
4989/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4990/// processing the delayed method declaration for Method. The method
4991/// declaration is now considered finished. There may be a separate
4992/// ActOnStartOfFunctionDef action later (not necessarily
4993/// immediately!) for this method, if it was also defined inside the
4994/// class body.
John McCall48871652010-08-21 09:40:31 +00004995void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004996 if (!MethodD)
4997 return;
Mike Stump11289f42009-09-09 15:08:12 +00004998
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004999 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00005000
John McCall48871652010-08-21 09:40:31 +00005001 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005002
5003 // Now that we have our default arguments, check the constructor
5004 // again. It could produce additional diagnostics or affect whether
5005 // the class has implicitly-declared destructors, among other
5006 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005007 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5008 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005009
5010 // Check the default arguments, which we may have added.
5011 if (!Method->isInvalidDecl())
5012 CheckCXXDefaultArguments(Method);
5013}
5014
Douglas Gregor831c93f2008-11-05 20:51:48 +00005015/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00005016/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00005017/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005018/// emit diagnostics and set the invalid bit to true. In any case, the type
5019/// will be updated to reflect a well-formed type for the constructor and
5020/// returned.
5021QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005022 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005023 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005024
5025 // C++ [class.ctor]p3:
5026 // A constructor shall not be virtual (10.3) or static (9.4). A
5027 // constructor can be invoked for a const, volatile or const
5028 // volatile object. A constructor shall not be declared const,
5029 // volatile, or const volatile (9.3.2).
5030 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005031 if (!D.isInvalidType())
5032 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5033 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5034 << SourceRange(D.getIdentifierLoc());
5035 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005036 }
John McCall8e7d6562010-08-26 03:08:43 +00005037 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005038 if (!D.isInvalidType())
5039 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5040 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5041 << SourceRange(D.getIdentifierLoc());
5042 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005043 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005044 }
Mike Stump11289f42009-09-09 15:08:12 +00005045
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005046 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005047 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00005048 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005049 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5050 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005051 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005052 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5053 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005054 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005055 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5056 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00005057 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005058 }
Mike Stump11289f42009-09-09 15:08:12 +00005059
Douglas Gregordb9d6642011-01-26 05:01:58 +00005060 // C++0x [class.ctor]p4:
5061 // A constructor shall not be declared with a ref-qualifier.
5062 if (FTI.hasRefQualifier()) {
5063 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5064 << FTI.RefQualifierIsLValueRef
5065 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5066 D.setInvalidType();
5067 }
5068
Douglas Gregor831c93f2008-11-05 20:51:48 +00005069 // Rebuild the function type "R" without any type qualifiers (in
5070 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00005071 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00005072 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005073 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5074 return R;
5075
5076 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5077 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005078 EPI.RefQualifier = RQ_None;
5079
Chris Lattner38378bf2009-04-25 08:28:21 +00005080 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005081 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005082}
5083
Douglas Gregor4d87df52008-12-16 21:30:33 +00005084/// CheckConstructor - Checks a fully-formed constructor for
5085/// well-formedness, issuing any diagnostics required. Returns true if
5086/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005087void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00005088 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005089 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5090 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005091 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005092
5093 // C++ [class.copy]p3:
5094 // A declaration of a constructor for a class X is ill-formed if
5095 // its first parameter is of type (optionally cv-qualified) X and
5096 // either there are no other parameters or else all other
5097 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005098 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00005099 ((Constructor->getNumParams() == 1) ||
5100 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00005101 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5102 Constructor->getTemplateSpecializationKind()
5103 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005104 QualType ParamType = Constructor->getParamDecl(0)->getType();
5105 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5106 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00005107 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00005108 const char *ConstRef
5109 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5110 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00005111 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00005112 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00005113
5114 // FIXME: Rather that making the constructor invalid, we should endeavor
5115 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005116 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005117 }
5118 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00005119}
5120
John McCalldeb646e2010-08-04 01:04:25 +00005121/// CheckDestructor - Checks a fully-formed destructor definition for
5122/// well-formedness, issuing any diagnostics required. Returns true
5123/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00005124bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00005125 CXXRecordDecl *RD = Destructor->getParent();
5126
5127 if (Destructor->isVirtual()) {
5128 SourceLocation Loc;
5129
5130 if (!Destructor->isImplicit())
5131 Loc = Destructor->getLocation();
5132 else
5133 Loc = RD->getLocation();
5134
5135 // If we have a virtual destructor, look up the deallocation function
5136 FunctionDecl *OperatorDelete = 0;
5137 DeclarationName Name =
5138 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005139 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00005140 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00005141
5142 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00005143
5144 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005145 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00005146
5147 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00005148}
5149
Mike Stump11289f42009-09-09 15:08:12 +00005150static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00005151FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5152 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5153 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005154 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00005155}
5156
Douglas Gregor831c93f2008-11-05 20:51:48 +00005157/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5158/// the well-formednes of the destructor declarator @p D with type @p
5159/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005160/// emit diagnostics and set the declarator to invalid. Even if this happens,
5161/// will be updated to reflect a well-formed type for the destructor and
5162/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00005163QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005164 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005165 // C++ [class.dtor]p1:
5166 // [...] A typedef-name that names a class is a class-name
5167 // (7.1.3); however, a typedef-name that names a class shall not
5168 // be used as the identifier in the declarator for a destructor
5169 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00005170 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00005171 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00005172 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00005173 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005174 else if (const TemplateSpecializationType *TST =
5175 DeclaratorType->getAs<TemplateSpecializationType>())
5176 if (TST->isTypeAlias())
5177 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5178 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005179
5180 // C++ [class.dtor]p2:
5181 // A destructor is used to destroy objects of its class type. A
5182 // destructor takes no parameters, and no return type can be
5183 // specified for it (not even void). The address of a destructor
5184 // shall not be taken. A destructor shall not be static. A
5185 // destructor can be invoked for a const, volatile or const
5186 // volatile object. A destructor shall not be declared const,
5187 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00005188 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005189 if (!D.isInvalidType())
5190 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5191 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00005192 << SourceRange(D.getIdentifierLoc())
5193 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5194
John McCall8e7d6562010-08-26 03:08:43 +00005195 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005196 }
Chris Lattner38378bf2009-04-25 08:28:21 +00005197 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005198 // Destructors don't have return types, but the parser will
5199 // happily parse something like:
5200 //
5201 // class X {
5202 // float ~X();
5203 // };
5204 //
5205 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00005206 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5207 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5208 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00005209 }
Mike Stump11289f42009-09-09 15:08:12 +00005210
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005211 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005212 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005213 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005214 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5215 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005216 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005217 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5218 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005219 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005220 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5221 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00005222 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005223 }
5224
Douglas Gregordb9d6642011-01-26 05:01:58 +00005225 // C++0x [class.dtor]p2:
5226 // A destructor shall not be declared with a ref-qualifier.
5227 if (FTI.hasRefQualifier()) {
5228 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5229 << FTI.RefQualifierIsLValueRef
5230 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5231 D.setInvalidType();
5232 }
5233
Douglas Gregor831c93f2008-11-05 20:51:48 +00005234 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00005235 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005236 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5237
5238 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00005239 FTI.freeArgs();
5240 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005241 }
5242
Mike Stump11289f42009-09-09 15:08:12 +00005243 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00005244 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005245 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00005246 D.setInvalidType();
5247 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00005248
5249 // Rebuild the function type "R" without any type qualifiers or
5250 // parameters (in case any of the errors above fired) and with
5251 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00005252 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00005253 if (!D.isInvalidType())
5254 return R;
5255
Douglas Gregor95755162010-07-01 05:10:53 +00005256 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005257 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5258 EPI.Variadic = false;
5259 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005260 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005261 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005262}
5263
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005264/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5265/// well-formednes of the conversion function declarator @p D with
5266/// type @p R. If there are any errors in the declarator, this routine
5267/// will emit diagnostics and return true. Otherwise, it will return
5268/// false. Either way, the type @p R will be updated to reflect a
5269/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005270void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00005271 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005272 // C++ [class.conv.fct]p1:
5273 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00005274 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00005275 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00005276 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005277 if (!D.isInvalidType())
5278 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5279 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5280 << SourceRange(D.getIdentifierLoc());
5281 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005282 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005283 }
John McCall212fa2e2010-04-13 00:04:31 +00005284
5285 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5286
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005287 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005288 // Conversion functions don't have return types, but the parser will
5289 // happily parse something like:
5290 //
5291 // class X {
5292 // float operator bool();
5293 // };
5294 //
5295 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00005296 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5297 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5298 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00005299 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005300 }
5301
John McCall212fa2e2010-04-13 00:04:31 +00005302 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5303
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005304 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00005305 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005306 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5307
5308 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005309 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005310 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00005311 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005312 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005313 D.setInvalidType();
5314 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005315
John McCall212fa2e2010-04-13 00:04:31 +00005316 // Diagnose "&operator bool()" and other such nonsense. This
5317 // is actually a gcc extension which we don't support.
5318 if (Proto->getResultType() != ConvType) {
5319 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5320 << Proto->getResultType();
5321 D.setInvalidType();
5322 ConvType = Proto->getResultType();
5323 }
5324
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005325 // C++ [class.conv.fct]p4:
5326 // The conversion-type-id shall not represent a function type nor
5327 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005328 if (ConvType->isArrayType()) {
5329 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5330 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005331 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005332 } else if (ConvType->isFunctionType()) {
5333 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5334 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005335 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005336 }
5337
5338 // Rebuild the function type "R" without any parameters (in case any
5339 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00005340 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00005341 if (D.isInvalidType())
5342 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005343
Douglas Gregor5fb53972009-01-14 15:45:31 +00005344 // C++0x explicit conversion operators.
5345 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00005346 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00005347 diag::warn_explicit_conversion_functions)
5348 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005349}
5350
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005351/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5352/// the declaration of the given C++ conversion function. This routine
5353/// is responsible for recording the conversion function in the C++
5354/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00005355Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005356 assert(Conversion && "Expected to receive a conversion function declaration");
5357
Douglas Gregor4287b372008-12-12 08:25:50 +00005358 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005359
5360 // Make sure we aren't redeclaring the conversion function.
5361 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005362
5363 // C++ [class.conv.fct]p1:
5364 // [...] A conversion function is never used to convert a
5365 // (possibly cv-qualified) object to the (possibly cv-qualified)
5366 // same object type (or a reference to it), to a (possibly
5367 // cv-qualified) base class of that type (or a reference to it),
5368 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00005369 // FIXME: Suppress this warning if the conversion function ends up being a
5370 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00005371 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005372 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005373 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005374 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005375 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5376 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00005377 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005378 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005379 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5380 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005381 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005382 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005383 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005384 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005385 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005386 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005387 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005388 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005389 }
5390
Douglas Gregor457104e2010-09-29 04:25:11 +00005391 if (FunctionTemplateDecl *ConversionTemplate
5392 = Conversion->getDescribedFunctionTemplate())
5393 return ConversionTemplate;
5394
John McCall48871652010-08-21 09:40:31 +00005395 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005396}
5397
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005398//===----------------------------------------------------------------------===//
5399// Namespace Handling
5400//===----------------------------------------------------------------------===//
5401
John McCallb1be5232010-08-26 09:15:37 +00005402
5403
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005404/// ActOnStartNamespaceDef - This is called at the start of a namespace
5405/// definition.
John McCall48871652010-08-21 09:40:31 +00005406Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00005407 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005408 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00005409 SourceLocation IdentLoc,
5410 IdentifierInfo *II,
5411 SourceLocation LBrace,
5412 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005413 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5414 // For anonymous namespace, take the location of the left brace.
5415 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00005416 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005417 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005418 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005419
5420 Scope *DeclRegionScope = NamespcScope->getParent();
5421
Anders Carlssona7bcade2010-02-07 01:09:23 +00005422 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5423
John McCall2faf32c2010-12-10 02:59:44 +00005424 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5425 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00005426
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005427 if (II) {
5428 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00005429 // The identifier in an original-namespace-definition shall not
5430 // have been previously defined in the declarative region in
5431 // which the original-namespace-definition appears. The
5432 // identifier in an original-namespace-definition is the name of
5433 // the namespace. Subsequently in that declarative region, it is
5434 // treated as an original-namespace-name.
5435 //
5436 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005437 // look through using directives, just look for any ordinary names.
5438
5439 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5440 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5441 Decl::IDNS_Namespace;
5442 NamedDecl *PrevDecl = 0;
5443 for (DeclContext::lookup_result R
5444 = CurContext->getRedeclContext()->lookup(II);
5445 R.first != R.second; ++R.first) {
5446 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5447 PrevDecl = *R.first;
5448 break;
5449 }
5450 }
5451
Douglas Gregor91f84212008-12-11 16:49:14 +00005452 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5453 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005454 if (Namespc->isInline() != OrigNS->isInline()) {
5455 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00005456 if (OrigNS->isInline()) {
5457 // The user probably just forgot the 'inline', so suggest that it
5458 // be added back.
5459 Diag(Namespc->getLocation(),
5460 diag::warn_inline_namespace_reopened_noninline)
5461 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5462 } else {
5463 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5464 << Namespc->isInline();
5465 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005466 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00005467
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005468 // Recover by ignoring the new namespace's inline status.
5469 Namespc->setInline(OrigNS->isInline());
5470 }
5471
Douglas Gregor91f84212008-12-11 16:49:14 +00005472 // Attach this namespace decl to the chain of extended namespace
5473 // definitions.
5474 OrigNS->setNextNamespace(Namespc);
5475 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005476
Mike Stump11289f42009-09-09 15:08:12 +00005477 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00005478 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00005479 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00005480 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005481 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005482 } else if (PrevDecl) {
5483 // This is an invalid name redefinition.
5484 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5485 << Namespc->getDeclName();
5486 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5487 Namespc->setInvalidDecl();
5488 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00005489 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00005490 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005491 // This is the first "real" definition of the namespace "std", so update
5492 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005493 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005494 // We had already defined a dummy namespace "std". Link this new
5495 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005496 StdNS->setNextNamespace(Namespc);
5497 StdNS->setLocation(IdentLoc);
5498 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00005499 }
5500
5501 // Make our StdNamespace cache point at the first real definition of the
5502 // "std" namespace.
5503 StdNamespace = Namespc;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005504
5505 // Add this instance of "std" to the set of known namespaces
5506 KnownNamespaces[Namespc] = false;
5507 } else if (!Namespc->isInline()) {
5508 // Since this is an "original" namespace, add it to the known set of
5509 // namespaces if it is not an inline namespace.
5510 KnownNamespaces[Namespc] = false;
Mike Stump11289f42009-09-09 15:08:12 +00005511 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005512
5513 PushOnScopeChains(Namespc, DeclRegionScope);
5514 } else {
John McCall4fa53422009-10-01 00:25:31 +00005515 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00005516 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00005517
5518 // Link the anonymous namespace into its parent.
5519 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00005520 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00005521 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5522 PrevDecl = TU->getAnonymousNamespace();
5523 TU->setAnonymousNamespace(Namespc);
5524 } else {
5525 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5526 PrevDecl = ND->getAnonymousNamespace();
5527 ND->setAnonymousNamespace(Namespc);
5528 }
5529
5530 // Link the anonymous namespace with its previous declaration.
5531 if (PrevDecl) {
5532 assert(PrevDecl->isAnonymousNamespace());
5533 assert(!PrevDecl->getNextNamespace());
5534 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5535 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005536
5537 if (Namespc->isInline() != PrevDecl->isInline()) {
5538 // inline-ness must match
5539 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5540 << Namespc->isInline();
5541 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5542 Namespc->setInvalidDecl();
5543 // Recover by ignoring the new namespace's inline status.
5544 Namespc->setInline(PrevDecl->isInline());
5545 }
John McCall0db42252009-12-16 02:06:49 +00005546 }
John McCall4fa53422009-10-01 00:25:31 +00005547
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00005548 CurContext->addDecl(Namespc);
5549
John McCall4fa53422009-10-01 00:25:31 +00005550 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5551 // behaves as if it were replaced by
5552 // namespace unique { /* empty body */ }
5553 // using namespace unique;
5554 // namespace unique { namespace-body }
5555 // where all occurrences of 'unique' in a translation unit are
5556 // replaced by the same identifier and this identifier differs
5557 // from all other identifiers in the entire program.
5558
5559 // We just create the namespace with an empty name and then add an
5560 // implicit using declaration, just like the standard suggests.
5561 //
5562 // CodeGen enforces the "universally unique" aspect by giving all
5563 // declarations semantically contained within an anonymous
5564 // namespace internal linkage.
5565
John McCall0db42252009-12-16 02:06:49 +00005566 if (!PrevDecl) {
5567 UsingDirectiveDecl* UD
5568 = UsingDirectiveDecl::Create(Context, CurContext,
5569 /* 'using' */ LBrace,
5570 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00005571 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00005572 /* identifier */ SourceLocation(),
5573 Namespc,
5574 /* Ancestor */ CurContext);
5575 UD->setImplicit();
5576 CurContext->addDecl(UD);
5577 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005578 }
5579
5580 // Although we could have an invalid decl (i.e. the namespace name is a
5581 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00005582 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5583 // for the namespace has the declarations that showed up in that particular
5584 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00005585 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00005586 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005587}
5588
Sebastian Redla6602e92009-11-23 15:34:23 +00005589/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5590/// is a namespace alias, returns the namespace it points to.
5591static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5592 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5593 return AD->getNamespace();
5594 return dyn_cast_or_null<NamespaceDecl>(D);
5595}
5596
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005597/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5598/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00005599void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005600 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5601 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005602 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005603 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00005604 if (Namespc->hasAttr<VisibilityAttr>())
5605 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005606}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005607
John McCall28a0cf72010-08-25 07:42:41 +00005608CXXRecordDecl *Sema::getStdBadAlloc() const {
5609 return cast_or_null<CXXRecordDecl>(
5610 StdBadAlloc.get(Context.getExternalSource()));
5611}
5612
5613NamespaceDecl *Sema::getStdNamespace() const {
5614 return cast_or_null<NamespaceDecl>(
5615 StdNamespace.get(Context.getExternalSource()));
5616}
5617
Douglas Gregorcdf87022010-06-29 17:53:46 +00005618/// \brief Retrieve the special "std" namespace, which may require us to
5619/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005620NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00005621 if (!StdNamespace) {
5622 // The "std" namespace has not yet been defined, so build one implicitly.
5623 StdNamespace = NamespaceDecl::Create(Context,
5624 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005625 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00005626 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005627 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005628 }
5629
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005630 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005631}
5632
Douglas Gregora172e082011-03-26 22:25:30 +00005633/// \brief Determine whether a using statement is in a context where it will be
5634/// apply in all contexts.
5635static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5636 switch (CurContext->getDeclKind()) {
5637 case Decl::TranslationUnit:
5638 return true;
5639 case Decl::LinkageSpec:
5640 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5641 default:
5642 return false;
5643 }
5644}
5645
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005646static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5647 CXXScopeSpec &SS,
5648 SourceLocation IdentLoc,
5649 IdentifierInfo *Ident) {
5650 R.clear();
5651 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5652 R.getLookupKind(), Sc, &SS, NULL,
5653 false, S.CTC_NoKeywords, NULL)) {
5654 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5655 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5656 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5657 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5658 if (DeclContext *DC = S.computeDeclContext(SS, false))
5659 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5660 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5661 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5662 else
5663 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5664 << Ident << CorrectedQuotedStr
5665 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5666
5667 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5668 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5669
5670 Ident = Corrected.getCorrectionAsIdentifierInfo();
5671 R.addDecl(Corrected.getCorrectionDecl());
5672 return true;
5673 }
5674 R.setLookupName(Ident);
5675 }
5676 return false;
5677}
5678
John McCall48871652010-08-21 09:40:31 +00005679Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005680 SourceLocation UsingLoc,
5681 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005682 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00005683 SourceLocation IdentLoc,
5684 IdentifierInfo *NamespcName,
5685 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00005686 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5687 assert(NamespcName && "Invalid NamespcName.");
5688 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00005689
5690 // This can only happen along a recovery path.
5691 while (S->getFlags() & Scope::TemplateParamScope)
5692 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00005693 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00005694
Douglas Gregor889ceb72009-02-03 19:21:40 +00005695 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00005696 NestedNameSpecifier *Qualifier = 0;
5697 if (SS.isSet())
5698 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5699
Douglas Gregor34074322009-01-14 22:20:51 +00005700 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005701 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5702 LookupParsedName(R, S, &SS);
5703 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005704 return 0;
John McCall27b18f82009-11-17 02:14:36 +00005705
Douglas Gregorcdf87022010-06-29 17:53:46 +00005706 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005707 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005708 // Allow "using namespace std;" or "using namespace ::std;" even if
5709 // "std" hasn't been defined yet, for GCC compatibility.
5710 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5711 NamespcName->isStr("std")) {
5712 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005713 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00005714 R.resolveKind();
5715 }
5716 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005717 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005718 }
5719
John McCall9f3059a2009-10-09 21:13:30 +00005720 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00005721 NamedDecl *Named = R.getFoundDecl();
5722 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5723 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00005724 // C++ [namespace.udir]p1:
5725 // A using-directive specifies that the names in the nominated
5726 // namespace can be used in the scope in which the
5727 // using-directive appears after the using-directive. During
5728 // unqualified name lookup (3.4.1), the names appear as if they
5729 // were declared in the nearest enclosing namespace which
5730 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00005731 // namespace. [Note: in this context, "contains" means "contains
5732 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00005733
5734 // Find enclosing context containing both using-directive and
5735 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00005736 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005737 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5738 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5739 CommonAncestor = CommonAncestor->getParent();
5740
Sebastian Redla6602e92009-11-23 15:34:23 +00005741 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00005742 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00005743 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005744
Douglas Gregora172e082011-03-26 22:25:30 +00005745 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00005746 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005747 Diag(IdentLoc, diag::warn_using_directive_in_header);
5748 }
5749
Douglas Gregor889ceb72009-02-03 19:21:40 +00005750 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005751 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00005752 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00005753 }
5754
Douglas Gregor889ceb72009-02-03 19:21:40 +00005755 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00005756 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00005757}
5758
5759void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5760 // If scope has associated entity, then using directive is at namespace
5761 // or translation unit scope. We add UsingDirectiveDecls, into
5762 // it's lookup structure.
5763 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005764 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005765 else
5766 // Otherwise it is block-sope. using-directives will affect lookup
5767 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00005768 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005769}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005770
Douglas Gregorfec52632009-06-20 00:51:54 +00005771
John McCall48871652010-08-21 09:40:31 +00005772Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00005773 AccessSpecifier AS,
5774 bool HasUsingKeyword,
5775 SourceLocation UsingLoc,
5776 CXXScopeSpec &SS,
5777 UnqualifiedId &Name,
5778 AttributeList *AttrList,
5779 bool IsTypeName,
5780 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00005781 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00005782
Douglas Gregor220f4272009-11-04 16:30:06 +00005783 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00005784 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00005785 case UnqualifiedId::IK_Identifier:
5786 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00005787 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00005788 case UnqualifiedId::IK_ConversionFunctionId:
5789 break;
5790
5791 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005792 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00005793 // C++0x inherited constructors.
5794 if (getLangOptions().CPlusPlus0x) break;
5795
Douglas Gregor220f4272009-11-04 16:30:06 +00005796 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5797 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005798 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005799
5800 case UnqualifiedId::IK_DestructorName:
5801 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5802 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005803 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005804
5805 case UnqualifiedId::IK_TemplateId:
5806 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5807 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00005808 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005809 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005810
5811 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5812 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00005813 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00005814 return 0;
John McCall3969e302009-12-08 07:46:18 +00005815
John McCalla0097262009-12-11 02:10:03 +00005816 // Warn about using declarations.
5817 // TODO: store that the declaration was written without 'using' and
5818 // talk about access decls instead of using decls in the
5819 // diagnostics.
5820 if (!HasUsingKeyword) {
5821 UsingLoc = Name.getSourceRange().getBegin();
5822
5823 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00005824 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00005825 }
5826
Douglas Gregorc4356532010-12-16 00:46:58 +00005827 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5828 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5829 return 0;
5830
John McCall3f746822009-11-17 05:59:44 +00005831 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005832 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005833 /* IsInstantiation */ false,
5834 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00005835 if (UD)
5836 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00005837
John McCall48871652010-08-21 09:40:31 +00005838 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00005839}
5840
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005841/// \brief Determine whether a using declaration considers the given
5842/// declarations as "equivalent", e.g., if they are redeclarations of
5843/// the same entity or are both typedefs of the same type.
5844static bool
5845IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5846 bool &SuppressRedeclaration) {
5847 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5848 SuppressRedeclaration = false;
5849 return true;
5850 }
5851
Richard Smithdda56e42011-04-15 14:24:37 +00005852 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5853 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005854 SuppressRedeclaration = true;
5855 return Context.hasSameType(TD1->getUnderlyingType(),
5856 TD2->getUnderlyingType());
5857 }
5858
5859 return false;
5860}
5861
5862
John McCall84d87672009-12-10 09:41:52 +00005863/// Determines whether to create a using shadow decl for a particular
5864/// decl, given the set of decls existing prior to this using lookup.
5865bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5866 const LookupResult &Previous) {
5867 // Diagnose finding a decl which is not from a base class of the
5868 // current class. We do this now because there are cases where this
5869 // function will silently decide not to build a shadow decl, which
5870 // will pre-empt further diagnostics.
5871 //
5872 // We don't need to do this in C++0x because we do the check once on
5873 // the qualifier.
5874 //
5875 // FIXME: diagnose the following if we care enough:
5876 // struct A { int foo; };
5877 // struct B : A { using A::foo; };
5878 // template <class T> struct C : A {};
5879 // template <class T> struct D : C<T> { using B::foo; } // <---
5880 // This is invalid (during instantiation) in C++03 because B::foo
5881 // resolves to the using decl in B, which is not a base class of D<T>.
5882 // We can't diagnose it immediately because C<T> is an unknown
5883 // specialization. The UsingShadowDecl in D<T> then points directly
5884 // to A::foo, which will look well-formed when we instantiate.
5885 // The right solution is to not collapse the shadow-decl chain.
5886 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5887 DeclContext *OrigDC = Orig->getDeclContext();
5888
5889 // Handle enums and anonymous structs.
5890 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5891 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5892 while (OrigRec->isAnonymousStructOrUnion())
5893 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5894
5895 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5896 if (OrigDC == CurContext) {
5897 Diag(Using->getLocation(),
5898 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005899 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005900 Diag(Orig->getLocation(), diag::note_using_decl_target);
5901 return true;
5902 }
5903
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005904 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00005905 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005906 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00005907 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005908 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005909 Diag(Orig->getLocation(), diag::note_using_decl_target);
5910 return true;
5911 }
5912 }
5913
5914 if (Previous.empty()) return false;
5915
5916 NamedDecl *Target = Orig;
5917 if (isa<UsingShadowDecl>(Target))
5918 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5919
John McCalla17e83e2009-12-11 02:33:26 +00005920 // If the target happens to be one of the previous declarations, we
5921 // don't have a conflict.
5922 //
5923 // FIXME: but we might be increasing its access, in which case we
5924 // should redeclare it.
5925 NamedDecl *NonTag = 0, *Tag = 0;
5926 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5927 I != E; ++I) {
5928 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005929 bool Result;
5930 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5931 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00005932
5933 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5934 }
5935
John McCall84d87672009-12-10 09:41:52 +00005936 if (Target->isFunctionOrFunctionTemplate()) {
5937 FunctionDecl *FD;
5938 if (isa<FunctionTemplateDecl>(Target))
5939 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5940 else
5941 FD = cast<FunctionDecl>(Target);
5942
5943 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00005944 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00005945 case Ovl_Overload:
5946 return false;
5947
5948 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00005949 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005950 break;
5951
5952 // We found a decl with the exact signature.
5953 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005954 // If we're in a record, we want to hide the target, so we
5955 // return true (without a diagnostic) to tell the caller not to
5956 // build a shadow decl.
5957 if (CurContext->isRecord())
5958 return true;
5959
5960 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00005961 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005962 break;
5963 }
5964
5965 Diag(Target->getLocation(), diag::note_using_decl_target);
5966 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5967 return true;
5968 }
5969
5970 // Target is not a function.
5971
John McCall84d87672009-12-10 09:41:52 +00005972 if (isa<TagDecl>(Target)) {
5973 // No conflict between a tag and a non-tag.
5974 if (!Tag) return false;
5975
John McCalle29c5cd2009-12-10 19:51:03 +00005976 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005977 Diag(Target->getLocation(), diag::note_using_decl_target);
5978 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5979 return true;
5980 }
5981
5982 // No conflict between a tag and a non-tag.
5983 if (!NonTag) return false;
5984
John McCalle29c5cd2009-12-10 19:51:03 +00005985 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005986 Diag(Target->getLocation(), diag::note_using_decl_target);
5987 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5988 return true;
5989}
5990
John McCall3f746822009-11-17 05:59:44 +00005991/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00005992UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00005993 UsingDecl *UD,
5994 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00005995
5996 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00005997 NamedDecl *Target = Orig;
5998 if (isa<UsingShadowDecl>(Target)) {
5999 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6000 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00006001 }
6002
6003 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00006004 = UsingShadowDecl::Create(Context, CurContext,
6005 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00006006 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00006007
6008 Shadow->setAccess(UD->getAccess());
6009 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6010 Shadow->setInvalidDecl();
6011
John McCall3f746822009-11-17 05:59:44 +00006012 if (S)
John McCall3969e302009-12-08 07:46:18 +00006013 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00006014 else
John McCall3969e302009-12-08 07:46:18 +00006015 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00006016
John McCall3969e302009-12-08 07:46:18 +00006017
John McCall84d87672009-12-10 09:41:52 +00006018 return Shadow;
6019}
John McCall3969e302009-12-08 07:46:18 +00006020
John McCall84d87672009-12-10 09:41:52 +00006021/// Hides a using shadow declaration. This is required by the current
6022/// using-decl implementation when a resolvable using declaration in a
6023/// class is followed by a declaration which would hide or override
6024/// one or more of the using decl's targets; for example:
6025///
6026/// struct Base { void foo(int); };
6027/// struct Derived : Base {
6028/// using Base::foo;
6029/// void foo(int);
6030/// };
6031///
6032/// The governing language is C++03 [namespace.udecl]p12:
6033///
6034/// When a using-declaration brings names from a base class into a
6035/// derived class scope, member functions in the derived class
6036/// override and/or hide member functions with the same name and
6037/// parameter types in a base class (rather than conflicting).
6038///
6039/// There are two ways to implement this:
6040/// (1) optimistically create shadow decls when they're not hidden
6041/// by existing declarations, or
6042/// (2) don't create any shadow decls (or at least don't make them
6043/// visible) until we've fully parsed/instantiated the class.
6044/// The problem with (1) is that we might have to retroactively remove
6045/// a shadow decl, which requires several O(n) operations because the
6046/// decl structures are (very reasonably) not designed for removal.
6047/// (2) avoids this but is very fiddly and phase-dependent.
6048void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00006049 if (Shadow->getDeclName().getNameKind() ==
6050 DeclarationName::CXXConversionFunctionName)
6051 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6052
John McCall84d87672009-12-10 09:41:52 +00006053 // Remove it from the DeclContext...
6054 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006055
John McCall84d87672009-12-10 09:41:52 +00006056 // ...and the scope, if applicable...
6057 if (S) {
John McCall48871652010-08-21 09:40:31 +00006058 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00006059 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006060 }
6061
John McCall84d87672009-12-10 09:41:52 +00006062 // ...and the using decl.
6063 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6064
6065 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00006066 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00006067}
6068
John McCalle61f2ba2009-11-18 02:36:19 +00006069/// Builds a using declaration.
6070///
6071/// \param IsInstantiation - Whether this call arises from an
6072/// instantiation of an unresolved using declaration. We treat
6073/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00006074NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6075 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006076 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006077 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00006078 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006079 bool IsInstantiation,
6080 bool IsTypeName,
6081 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00006082 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006083 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00006084 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00006085
Anders Carlssonf038fc22009-08-28 05:49:21 +00006086 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00006087
Anders Carlsson59140b32009-08-28 03:16:11 +00006088 if (SS.isEmpty()) {
6089 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00006090 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00006091 }
Mike Stump11289f42009-09-09 15:08:12 +00006092
John McCall84d87672009-12-10 09:41:52 +00006093 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006094 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00006095 ForRedeclaration);
6096 Previous.setHideTags(false);
6097 if (S) {
6098 LookupName(Previous, S);
6099
6100 // It is really dumb that we have to do this.
6101 LookupResult::Filter F = Previous.makeFilter();
6102 while (F.hasNext()) {
6103 NamedDecl *D = F.next();
6104 if (!isDeclInScope(D, CurContext, S))
6105 F.erase();
6106 }
6107 F.done();
6108 } else {
6109 assert(IsInstantiation && "no scope in non-instantiation");
6110 assert(CurContext->isRecord() && "scope not record in instantiation");
6111 LookupQualifiedName(Previous, CurContext);
6112 }
6113
John McCall84d87672009-12-10 09:41:52 +00006114 // Check for invalid redeclarations.
6115 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6116 return 0;
6117
6118 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00006119 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6120 return 0;
6121
John McCall84c16cf2009-11-12 03:15:40 +00006122 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006123 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006124 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00006125 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00006126 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00006127 // FIXME: not all declaration name kinds are legal here
6128 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6129 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006130 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006131 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00006132 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006133 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6134 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00006135 }
John McCallb96ec562009-12-04 22:46:56 +00006136 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006137 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6138 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00006139 }
John McCallb96ec562009-12-04 22:46:56 +00006140 D->setAccess(AS);
6141 CurContext->addDecl(D);
6142
6143 if (!LookupContext) return D;
6144 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00006145
John McCall0b66eb32010-05-01 00:40:08 +00006146 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00006147 UD->setInvalidDecl();
6148 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00006149 }
6150
Sebastian Redl08905022011-02-05 19:23:19 +00006151 // Constructor inheriting using decls get special treatment.
6152 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00006153 if (CheckInheritedConstructorUsingDecl(UD))
6154 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00006155 return UD;
6156 }
6157
6158 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00006159
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006160 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00006161
John McCall3969e302009-12-08 07:46:18 +00006162 // Unlike most lookups, we don't always want to hide tag
6163 // declarations: tag names are visible through the using declaration
6164 // even if hidden by ordinary names, *except* in a dependent context
6165 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00006166 if (!IsInstantiation)
6167 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00006168
John McCall27b18f82009-11-17 02:14:36 +00006169 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00006170
John McCall9f3059a2009-10-09 21:13:30 +00006171 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00006172 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006173 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006174 UD->setInvalidDecl();
6175 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006176 }
6177
John McCallb96ec562009-12-04 22:46:56 +00006178 if (R.isAmbiguous()) {
6179 UD->setInvalidDecl();
6180 return UD;
6181 }
Mike Stump11289f42009-09-09 15:08:12 +00006182
John McCalle61f2ba2009-11-18 02:36:19 +00006183 if (IsTypeName) {
6184 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00006185 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006186 Diag(IdentLoc, diag::err_using_typename_non_type);
6187 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6188 Diag((*I)->getUnderlyingDecl()->getLocation(),
6189 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006190 UD->setInvalidDecl();
6191 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006192 }
6193 } else {
6194 // If we asked for a non-typename and we got a type, error out,
6195 // but only if this is an instantiation of an unresolved using
6196 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00006197 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006198 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6199 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006200 UD->setInvalidDecl();
6201 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006202 }
Anders Carlsson59140b32009-08-28 03:16:11 +00006203 }
6204
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006205 // C++0x N2914 [namespace.udecl]p6:
6206 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00006207 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006208 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6209 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006210 UD->setInvalidDecl();
6211 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006212 }
Mike Stump11289f42009-09-09 15:08:12 +00006213
John McCall84d87672009-12-10 09:41:52 +00006214 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6215 if (!CheckUsingShadowDecl(UD, *I, Previous))
6216 BuildUsingShadowDecl(S, UD, *I);
6217 }
John McCall3f746822009-11-17 05:59:44 +00006218
6219 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006220}
6221
Sebastian Redl08905022011-02-05 19:23:19 +00006222/// Additional checks for a using declaration referring to a constructor name.
6223bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6224 if (UD->isTypeName()) {
6225 // FIXME: Cannot specify typename when specifying constructor
6226 return true;
6227 }
6228
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006229 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00006230 assert(SourceType &&
6231 "Using decl naming constructor doesn't have type in scope spec.");
6232 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6233
6234 // Check whether the named type is a direct base class.
6235 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6236 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6237 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6238 BaseIt != BaseE; ++BaseIt) {
6239 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6240 if (CanonicalSourceType == BaseType)
6241 break;
6242 }
6243
6244 if (BaseIt == BaseE) {
6245 // Did not find SourceType in the bases.
6246 Diag(UD->getUsingLocation(),
6247 diag::err_using_decl_constructor_not_in_direct_base)
6248 << UD->getNameInfo().getSourceRange()
6249 << QualType(SourceType, 0) << TargetClass;
6250 return true;
6251 }
6252
6253 BaseIt->setInheritConstructors();
6254
6255 return false;
6256}
6257
John McCall84d87672009-12-10 09:41:52 +00006258/// Checks that the given using declaration is not an invalid
6259/// redeclaration. Note that this is checking only for the using decl
6260/// itself, not for any ill-formedness among the UsingShadowDecls.
6261bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6262 bool isTypeName,
6263 const CXXScopeSpec &SS,
6264 SourceLocation NameLoc,
6265 const LookupResult &Prev) {
6266 // C++03 [namespace.udecl]p8:
6267 // C++0x [namespace.udecl]p10:
6268 // A using-declaration is a declaration and can therefore be used
6269 // repeatedly where (and only where) multiple declarations are
6270 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00006271 //
John McCall032092f2010-11-29 18:01:58 +00006272 // That's in non-member contexts.
6273 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00006274 return false;
6275
6276 NestedNameSpecifier *Qual
6277 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6278
6279 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6280 NamedDecl *D = *I;
6281
6282 bool DTypename;
6283 NestedNameSpecifier *DQual;
6284 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6285 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006286 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006287 } else if (UnresolvedUsingValueDecl *UD
6288 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6289 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006290 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006291 } else if (UnresolvedUsingTypenameDecl *UD
6292 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6293 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006294 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006295 } else continue;
6296
6297 // using decls differ if one says 'typename' and the other doesn't.
6298 // FIXME: non-dependent using decls?
6299 if (isTypeName != DTypename) continue;
6300
6301 // using decls differ if they name different scopes (but note that
6302 // template instantiation can cause this check to trigger when it
6303 // didn't before instantiation).
6304 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6305 Context.getCanonicalNestedNameSpecifier(DQual))
6306 continue;
6307
6308 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00006309 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00006310 return true;
6311 }
6312
6313 return false;
6314}
6315
John McCall3969e302009-12-08 07:46:18 +00006316
John McCallb96ec562009-12-04 22:46:56 +00006317/// Checks that the given nested-name qualifier used in a using decl
6318/// in the current context is appropriately related to the current
6319/// scope. If an error is found, diagnoses it and returns true.
6320bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6321 const CXXScopeSpec &SS,
6322 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00006323 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006324
John McCall3969e302009-12-08 07:46:18 +00006325 if (!CurContext->isRecord()) {
6326 // C++03 [namespace.udecl]p3:
6327 // C++0x [namespace.udecl]p8:
6328 // A using-declaration for a class member shall be a member-declaration.
6329
6330 // If we weren't able to compute a valid scope, it must be a
6331 // dependent class scope.
6332 if (!NamedContext || NamedContext->isRecord()) {
6333 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6334 << SS.getRange();
6335 return true;
6336 }
6337
6338 // Otherwise, everything is known to be fine.
6339 return false;
6340 }
6341
6342 // The current scope is a record.
6343
6344 // If the named context is dependent, we can't decide much.
6345 if (!NamedContext) {
6346 // FIXME: in C++0x, we can diagnose if we can prove that the
6347 // nested-name-specifier does not refer to a base class, which is
6348 // still possible in some cases.
6349
6350 // Otherwise we have to conservatively report that things might be
6351 // okay.
6352 return false;
6353 }
6354
6355 if (!NamedContext->isRecord()) {
6356 // Ideally this would point at the last name in the specifier,
6357 // but we don't have that level of source info.
6358 Diag(SS.getRange().getBegin(),
6359 diag::err_using_decl_nested_name_specifier_is_not_class)
6360 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6361 return true;
6362 }
6363
Douglas Gregor7c842292010-12-21 07:41:49 +00006364 if (!NamedContext->isDependentContext() &&
6365 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6366 return true;
6367
John McCall3969e302009-12-08 07:46:18 +00006368 if (getLangOptions().CPlusPlus0x) {
6369 // C++0x [namespace.udecl]p3:
6370 // In a using-declaration used as a member-declaration, the
6371 // nested-name-specifier shall name a base class of the class
6372 // being defined.
6373
6374 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6375 cast<CXXRecordDecl>(NamedContext))) {
6376 if (CurContext == NamedContext) {
6377 Diag(NameLoc,
6378 diag::err_using_decl_nested_name_specifier_is_current_class)
6379 << SS.getRange();
6380 return true;
6381 }
6382
6383 Diag(SS.getRange().getBegin(),
6384 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6385 << (NestedNameSpecifier*) SS.getScopeRep()
6386 << cast<CXXRecordDecl>(CurContext)
6387 << SS.getRange();
6388 return true;
6389 }
6390
6391 return false;
6392 }
6393
6394 // C++03 [namespace.udecl]p4:
6395 // A using-declaration used as a member-declaration shall refer
6396 // to a member of a base class of the class being defined [etc.].
6397
6398 // Salient point: SS doesn't have to name a base class as long as
6399 // lookup only finds members from base classes. Therefore we can
6400 // diagnose here only if we can prove that that can't happen,
6401 // i.e. if the class hierarchies provably don't intersect.
6402
6403 // TODO: it would be nice if "definitely valid" results were cached
6404 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6405 // need to be repeated.
6406
6407 struct UserData {
6408 llvm::DenseSet<const CXXRecordDecl*> Bases;
6409
6410 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6411 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6412 Data->Bases.insert(Base);
6413 return true;
6414 }
6415
6416 bool hasDependentBases(const CXXRecordDecl *Class) {
6417 return !Class->forallBases(collect, this);
6418 }
6419
6420 /// Returns true if the base is dependent or is one of the
6421 /// accumulated base classes.
6422 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6423 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6424 return !Data->Bases.count(Base);
6425 }
6426
6427 bool mightShareBases(const CXXRecordDecl *Class) {
6428 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6429 }
6430 };
6431
6432 UserData Data;
6433
6434 // Returns false if we find a dependent base.
6435 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6436 return false;
6437
6438 // Returns false if the class has a dependent base or if it or one
6439 // of its bases is present in the base set of the current context.
6440 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6441 return false;
6442
6443 Diag(SS.getRange().getBegin(),
6444 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6445 << (NestedNameSpecifier*) SS.getScopeRep()
6446 << cast<CXXRecordDecl>(CurContext)
6447 << SS.getRange();
6448
6449 return true;
John McCallb96ec562009-12-04 22:46:56 +00006450}
6451
Richard Smithdda56e42011-04-15 14:24:37 +00006452Decl *Sema::ActOnAliasDeclaration(Scope *S,
6453 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006454 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00006455 SourceLocation UsingLoc,
6456 UnqualifiedId &Name,
6457 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00006458 // Skip up to the relevant declaration scope.
6459 while (S->getFlags() & Scope::TemplateParamScope)
6460 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00006461 assert((S->getFlags() & Scope::DeclScope) &&
6462 "got alias-declaration outside of declaration scope");
6463
6464 if (Type.isInvalid())
6465 return 0;
6466
6467 bool Invalid = false;
6468 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6469 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00006470 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00006471
6472 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6473 return 0;
6474
6475 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006476 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00006477 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006478 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6479 TInfo->getTypeLoc().getBeginLoc());
6480 }
Richard Smithdda56e42011-04-15 14:24:37 +00006481
6482 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6483 LookupName(Previous, S);
6484
6485 // Warn about shadowing the name of a template parameter.
6486 if (Previous.isSingleResult() &&
6487 Previous.getFoundDecl()->isTemplateParameter()) {
6488 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6489 Previous.getFoundDecl()))
6490 Invalid = true;
6491 Previous.clear();
6492 }
6493
6494 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6495 "name in alias declaration must be an identifier");
6496 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6497 Name.StartLocation,
6498 Name.Identifier, TInfo);
6499
6500 NewTD->setAccess(AS);
6501
6502 if (Invalid)
6503 NewTD->setInvalidDecl();
6504
Richard Smith3f1b5d02011-05-05 21:57:07 +00006505 CheckTypedefForVariablyModifiedType(S, NewTD);
6506 Invalid |= NewTD->isInvalidDecl();
6507
Richard Smithdda56e42011-04-15 14:24:37 +00006508 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006509
6510 NamedDecl *NewND;
6511 if (TemplateParamLists.size()) {
6512 TypeAliasTemplateDecl *OldDecl = 0;
6513 TemplateParameterList *OldTemplateParams = 0;
6514
6515 if (TemplateParamLists.size() != 1) {
6516 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6517 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6518 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6519 }
6520 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6521
6522 // Only consider previous declarations in the same scope.
6523 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6524 /*ExplicitInstantiationOrSpecialization*/false);
6525 if (!Previous.empty()) {
6526 Redeclaration = true;
6527
6528 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6529 if (!OldDecl && !Invalid) {
6530 Diag(UsingLoc, diag::err_redefinition_different_kind)
6531 << Name.Identifier;
6532
6533 NamedDecl *OldD = Previous.getRepresentativeDecl();
6534 if (OldD->getLocation().isValid())
6535 Diag(OldD->getLocation(), diag::note_previous_definition);
6536
6537 Invalid = true;
6538 }
6539
6540 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6541 if (TemplateParameterListsAreEqual(TemplateParams,
6542 OldDecl->getTemplateParameters(),
6543 /*Complain=*/true,
6544 TPL_TemplateMatch))
6545 OldTemplateParams = OldDecl->getTemplateParameters();
6546 else
6547 Invalid = true;
6548
6549 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6550 if (!Invalid &&
6551 !Context.hasSameType(OldTD->getUnderlyingType(),
6552 NewTD->getUnderlyingType())) {
6553 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6554 // but we can't reasonably accept it.
6555 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6556 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6557 if (OldTD->getLocation().isValid())
6558 Diag(OldTD->getLocation(), diag::note_previous_definition);
6559 Invalid = true;
6560 }
6561 }
6562 }
6563
6564 // Merge any previous default template arguments into our parameters,
6565 // and check the parameter list.
6566 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6567 TPC_TypeAliasTemplate))
6568 return 0;
6569
6570 TypeAliasTemplateDecl *NewDecl =
6571 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6572 Name.Identifier, TemplateParams,
6573 NewTD);
6574
6575 NewDecl->setAccess(AS);
6576
6577 if (Invalid)
6578 NewDecl->setInvalidDecl();
6579 else if (OldDecl)
6580 NewDecl->setPreviousDeclaration(OldDecl);
6581
6582 NewND = NewDecl;
6583 } else {
6584 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6585 NewND = NewTD;
6586 }
Richard Smithdda56e42011-04-15 14:24:37 +00006587
6588 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00006589 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00006590
Richard Smith3f1b5d02011-05-05 21:57:07 +00006591 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00006592}
6593
John McCall48871652010-08-21 09:40:31 +00006594Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006595 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006596 SourceLocation AliasLoc,
6597 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006598 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006599 SourceLocation IdentLoc,
6600 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00006601
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006602 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006603 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6604 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006605
Anders Carlssondca83c42009-03-28 06:23:46 +00006606 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00006607 NamedDecl *PrevDecl
6608 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6609 ForRedeclaration);
6610 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6611 PrevDecl = 0;
6612
6613 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006614 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00006615 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006616 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00006617 // FIXME: At some point, we'll want to create the (redundant)
6618 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00006619 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00006620 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00006621 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006622 }
Mike Stump11289f42009-09-09 15:08:12 +00006623
Anders Carlssondca83c42009-03-28 06:23:46 +00006624 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6625 diag::err_redefinition_different_kind;
6626 Diag(AliasLoc, DiagID) << Alias;
6627 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00006628 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00006629 }
6630
John McCall27b18f82009-11-17 02:14:36 +00006631 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006632 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006633
John McCall9f3059a2009-10-09 21:13:30 +00006634 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006635 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006636 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006637 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006638 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00006639 }
Mike Stump11289f42009-09-09 15:08:12 +00006640
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006641 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00006642 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00006643 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00006644 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006645
John McCalld8d0d432010-02-16 06:53:13 +00006646 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00006647 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00006648}
6649
Douglas Gregora57478e2010-05-01 15:04:51 +00006650namespace {
6651 /// \brief Scoped object used to handle the state changes required in Sema
6652 /// to implicitly define the body of a C++ member function;
6653 class ImplicitlyDefinedFunctionScope {
6654 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00006655 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00006656
6657 public:
6658 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00006659 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00006660 {
Douglas Gregora57478e2010-05-01 15:04:51 +00006661 S.PushFunctionScope();
6662 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6663 }
6664
6665 ~ImplicitlyDefinedFunctionScope() {
6666 S.PopExpressionEvaluationContext();
6667 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00006668 }
6669 };
6670}
6671
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006672Sema::ImplicitExceptionSpecification
6673Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00006674 // C++ [except.spec]p14:
6675 // An implicitly declared special member function (Clause 12) shall have an
6676 // exception-specification. [...]
6677 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006678 if (ClassDecl->isInvalidDecl())
6679 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00006680
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006681 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006682 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6683 BEnd = ClassDecl->bases_end();
6684 B != BEnd; ++B) {
6685 if (B->isVirtual()) // Handled below.
6686 continue;
6687
Douglas Gregor9672f922010-07-03 00:47:00 +00006688 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6689 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006690 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6691 // If this is a deleted function, add it anyway. This might be conformant
6692 // with the standard. This might not. I'm not sure. It might not matter.
6693 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006694 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006695 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006696 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006697
6698 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006699 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6700 BEnd = ClassDecl->vbases_end();
6701 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00006702 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6703 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006704 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6705 // If this is a deleted function, add it anyway. This might be conformant
6706 // with the standard. This might not. I'm not sure. It might not matter.
6707 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006708 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006709 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006710 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006711
6712 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006713 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6714 FEnd = ClassDecl->field_end();
6715 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00006716 if (F->hasInClassInitializer()) {
6717 if (Expr *E = F->getInClassInitializer())
6718 ExceptSpec.CalledExpr(E);
6719 else if (!F->isInvalidDecl())
6720 ExceptSpec.SetDelayed();
6721 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00006722 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00006723 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6724 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6725 // If this is a deleted function, add it anyway. This might be conformant
6726 // with the standard. This might not. I'm not sure. It might not matter.
6727 // In particular, the problem is that this function never gets called. It
6728 // might just be ill-formed because this function attempts to refer to
6729 // a deleted function here.
6730 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006731 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006732 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006733 }
John McCalldb40c7f2010-12-14 08:05:40 +00006734
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006735 return ExceptSpec;
6736}
6737
6738CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6739 CXXRecordDecl *ClassDecl) {
6740 // C++ [class.ctor]p5:
6741 // A default constructor for a class X is a constructor of class X
6742 // that can be called without an argument. If there is no
6743 // user-declared constructor for class X, a default constructor is
6744 // implicitly declared. An implicitly-declared default constructor
6745 // is an inline public member of its class.
6746 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6747 "Should not build implicit default constructor!");
6748
6749 ImplicitExceptionSpecification Spec =
6750 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6751 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00006752
Douglas Gregor6d880b12010-07-01 22:31:05 +00006753 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006754 CanQualType ClassType
6755 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006756 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006757 DeclarationName Name
6758 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006759 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006760 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00006761 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006762 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00006763 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006764 /*TInfo=*/0,
6765 /*isExplicit=*/false,
6766 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00006767 /*isImplicitlyDeclared=*/true,
6768 // FIXME: apply the rules for definitions here
6769 /*isConstexpr=*/false);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006770 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00006771 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006772 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00006773 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00006774
6775 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00006776 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6777
Douglas Gregor0be31a22010-07-02 17:43:08 +00006778 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00006779 PushOnScopeChains(DefaultCon, S, false);
6780 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00006781
Alexis Huntd6da8762011-10-10 06:18:57 +00006782 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00006783 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00006784
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006785 return DefaultCon;
6786}
6787
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006788void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6789 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00006790 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006791 !Constructor->doesThisDeclarationHaveABody() &&
6792 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006793 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006794
Anders Carlsson423f5d82010-04-23 16:04:08 +00006795 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00006796 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00006797
Douglas Gregora57478e2010-05-01 15:04:51 +00006798 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006799 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00006800 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006801 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006802 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00006803 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00006804 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00006805 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00006806 }
Douglas Gregor73193272010-09-20 16:48:21 +00006807
6808 SourceLocation Loc = Constructor->getLocation();
6809 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6810
6811 Constructor->setUsed();
6812 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006813
6814 if (ASTMutationListener *L = getASTMutationListener()) {
6815 L->CompletedImplicitDefinition(Constructor);
6816 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006817}
6818
Richard Smith938f40b2011-06-11 17:19:42 +00006819/// Get any existing defaulted default constructor for the given class. Do not
6820/// implicitly define one if it does not exist.
6821static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6822 CXXRecordDecl *D) {
6823 ASTContext &Context = Self.Context;
6824 QualType ClassType = Context.getTypeDeclType(D);
6825 DeclarationName ConstructorName
6826 = Context.DeclarationNames.getCXXConstructorName(
6827 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6828
6829 DeclContext::lookup_const_iterator Con, ConEnd;
6830 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6831 Con != ConEnd; ++Con) {
6832 // A function template cannot be defaulted.
6833 if (isa<FunctionTemplateDecl>(*Con))
6834 continue;
6835
6836 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6837 if (Constructor->isDefaultConstructor())
6838 return Constructor->isDefaulted() ? Constructor : 0;
6839 }
6840 return 0;
6841}
6842
6843void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6844 if (!D) return;
6845 AdjustDeclIfTemplate(D);
6846
6847 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6848 CXXConstructorDecl *CtorDecl
6849 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6850
6851 if (!CtorDecl) return;
6852
6853 // Compute the exception specification for the default constructor.
6854 const FunctionProtoType *CtorTy =
6855 CtorDecl->getType()->castAs<FunctionProtoType>();
6856 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6857 ImplicitExceptionSpecification Spec =
6858 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6859 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6860 assert(EPI.ExceptionSpecType != EST_Delayed);
6861
6862 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6863 }
6864
6865 // If the default constructor is explicitly defaulted, checking the exception
6866 // specification is deferred until now.
6867 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6868 !ClassDecl->isDependentType())
6869 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6870}
6871
Sebastian Redl08905022011-02-05 19:23:19 +00006872void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6873 // We start with an initial pass over the base classes to collect those that
6874 // inherit constructors from. If there are none, we can forgo all further
6875 // processing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006876 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redl08905022011-02-05 19:23:19 +00006877 BasesVector BasesToInheritFrom;
6878 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6879 BaseE = ClassDecl->bases_end();
6880 BaseIt != BaseE; ++BaseIt) {
6881 if (BaseIt->getInheritConstructors()) {
6882 QualType Base = BaseIt->getType();
6883 if (Base->isDependentType()) {
6884 // If we inherit constructors from anything that is dependent, just
6885 // abort processing altogether. We'll get another chance for the
6886 // instantiations.
6887 return;
6888 }
6889 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6890 }
6891 }
6892 if (BasesToInheritFrom.empty())
6893 return;
6894
6895 // Now collect the constructors that we already have in the current class.
6896 // Those take precedence over inherited constructors.
6897 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6898 // unless there is a user-declared constructor with the same signature in
6899 // the class where the using-declaration appears.
6900 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6901 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6902 CtorE = ClassDecl->ctor_end();
6903 CtorIt != CtorE; ++CtorIt) {
6904 ExistingConstructors.insert(
6905 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6906 }
6907
6908 Scope *S = getScopeForContext(ClassDecl);
6909 DeclarationName CreatedCtorName =
6910 Context.DeclarationNames.getCXXConstructorName(
6911 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6912
6913 // Now comes the true work.
6914 // First, we keep a map from constructor types to the base that introduced
6915 // them. Needed for finding conflicting constructors. We also keep the
6916 // actually inserted declarations in there, for pretty diagnostics.
6917 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6918 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6919 ConstructorToSourceMap InheritedConstructors;
6920 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6921 BaseE = BasesToInheritFrom.end();
6922 BaseIt != BaseE; ++BaseIt) {
6923 const RecordType *Base = *BaseIt;
6924 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6925 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6926 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6927 CtorE = BaseDecl->ctor_end();
6928 CtorIt != CtorE; ++CtorIt) {
6929 // Find the using declaration for inheriting this base's constructors.
6930 DeclarationName Name =
6931 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6932 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6933 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6934 SourceLocation UsingLoc = UD ? UD->getLocation() :
6935 ClassDecl->getLocation();
6936
6937 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6938 // from the class X named in the using-declaration consists of actual
6939 // constructors and notional constructors that result from the
6940 // transformation of defaulted parameters as follows:
6941 // - all non-template default constructors of X, and
6942 // - for each non-template constructor of X that has at least one
6943 // parameter with a default argument, the set of constructors that
6944 // results from omitting any ellipsis parameter specification and
6945 // successively omitting parameters with a default argument from the
6946 // end of the parameter-type-list.
6947 CXXConstructorDecl *BaseCtor = *CtorIt;
6948 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6949 const FunctionProtoType *BaseCtorType =
6950 BaseCtor->getType()->getAs<FunctionProtoType>();
6951
6952 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6953 maxParams = BaseCtor->getNumParams();
6954 params <= maxParams; ++params) {
6955 // Skip default constructors. They're never inherited.
6956 if (params == 0)
6957 continue;
6958 // Skip copy and move constructors for the same reason.
6959 if (CanBeCopyOrMove && params == 1)
6960 continue;
6961
6962 // Build up a function type for this particular constructor.
6963 // FIXME: The working paper does not consider that the exception spec
6964 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00006965 // source. This code doesn't yet, either. When it does, this code will
6966 // need to be delayed until after exception specifications and in-class
6967 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00006968 const Type *NewCtorType;
6969 if (params == maxParams)
6970 NewCtorType = BaseCtorType;
6971 else {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006972 SmallVector<QualType, 16> Args;
Sebastian Redl08905022011-02-05 19:23:19 +00006973 for (unsigned i = 0; i < params; ++i) {
6974 Args.push_back(BaseCtorType->getArgType(i));
6975 }
6976 FunctionProtoType::ExtProtoInfo ExtInfo =
6977 BaseCtorType->getExtProtoInfo();
6978 ExtInfo.Variadic = false;
6979 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6980 Args.data(), params, ExtInfo)
6981 .getTypePtr();
6982 }
6983 const Type *CanonicalNewCtorType =
6984 Context.getCanonicalType(NewCtorType);
6985
6986 // Now that we have the type, first check if the class already has a
6987 // constructor with this signature.
6988 if (ExistingConstructors.count(CanonicalNewCtorType))
6989 continue;
6990
6991 // Then we check if we have already declared an inherited constructor
6992 // with this signature.
6993 std::pair<ConstructorToSourceMap::iterator, bool> result =
6994 InheritedConstructors.insert(std::make_pair(
6995 CanonicalNewCtorType,
6996 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6997 if (!result.second) {
6998 // Already in the map. If it came from a different class, that's an
6999 // error. Not if it's from the same.
7000 CanQualType PreviousBase = result.first->second.first;
7001 if (CanonicalBase != PreviousBase) {
7002 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7003 const CXXConstructorDecl *PrevBaseCtor =
7004 PrevCtor->getInheritedConstructor();
7005 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7006
7007 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7008 Diag(BaseCtor->getLocation(),
7009 diag::note_using_decl_constructor_conflict_current_ctor);
7010 Diag(PrevBaseCtor->getLocation(),
7011 diag::note_using_decl_constructor_conflict_previous_ctor);
7012 Diag(PrevCtor->getLocation(),
7013 diag::note_using_decl_constructor_conflict_previous_using);
7014 }
7015 continue;
7016 }
7017
7018 // OK, we're there, now add the constructor.
7019 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smitha77a0a62011-08-15 21:04:07 +00007020 // user-written inline constructor [...]
Sebastian Redl08905022011-02-05 19:23:19 +00007021 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7022 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00007023 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7024 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00007025 /*ImplicitlyDeclared=*/true,
7026 // FIXME: Due to a defect in the standard, we treat inherited
7027 // constructors as constexpr even if that makes them ill-formed.
7028 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redl08905022011-02-05 19:23:19 +00007029 NewCtor->setAccess(BaseCtor->getAccess());
7030
7031 // Build up the parameter decls and add them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007032 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redl08905022011-02-05 19:23:19 +00007033 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007034 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7035 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00007036 /*IdentifierInfo=*/0,
7037 BaseCtorType->getArgType(i),
7038 /*TInfo=*/0, SC_None,
7039 SC_None, /*DefaultArg=*/0));
7040 }
David Blaikie9c70e042011-09-21 18:16:56 +00007041 NewCtor->setParams(ParamDecls);
Sebastian Redl08905022011-02-05 19:23:19 +00007042 NewCtor->setInheritedConstructor(BaseCtor);
7043
7044 PushOnScopeChains(NewCtor, S, false);
7045 ClassDecl->addDecl(NewCtor);
7046 result.first->second.second = NewCtor;
7047 }
7048 }
7049 }
7050}
7051
Alexis Huntf91729462011-05-12 22:46:25 +00007052Sema::ImplicitExceptionSpecification
7053Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00007054 // C++ [except.spec]p14:
7055 // An implicitly declared special member function (Clause 12) shall have
7056 // an exception-specification.
7057 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007058 if (ClassDecl->isInvalidDecl())
7059 return ExceptSpec;
7060
Douglas Gregorf1203042010-07-01 19:09:28 +00007061 // Direct base-class destructors.
7062 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7063 BEnd = ClassDecl->bases_end();
7064 B != BEnd; ++B) {
7065 if (B->isVirtual()) // Handled below.
7066 continue;
7067
7068 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7069 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007070 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007071 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007072
Douglas Gregorf1203042010-07-01 19:09:28 +00007073 // Virtual base-class destructors.
7074 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7075 BEnd = ClassDecl->vbases_end();
7076 B != BEnd; ++B) {
7077 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7078 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007079 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007080 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007081
Douglas Gregorf1203042010-07-01 19:09:28 +00007082 // Field destructors.
7083 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7084 FEnd = ClassDecl->field_end();
7085 F != FEnd; ++F) {
7086 if (const RecordType *RecordTy
7087 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7088 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007089 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007090 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007091
Alexis Huntf91729462011-05-12 22:46:25 +00007092 return ExceptSpec;
7093}
7094
7095CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7096 // C++ [class.dtor]p2:
7097 // If a class has no user-declared destructor, a destructor is
7098 // declared implicitly. An implicitly-declared destructor is an
7099 // inline public member of its class.
7100
7101 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00007102 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00007103 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7104
Douglas Gregor7454c562010-07-02 20:37:36 +00007105 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00007106 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007107
Douglas Gregorf1203042010-07-01 19:09:28 +00007108 CanQualType ClassType
7109 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007110 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00007111 DeclarationName Name
7112 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007113 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00007114 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007115 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7116 /*isInline=*/true,
7117 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00007118 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00007119 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00007120 Destructor->setImplicit();
7121 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00007122
7123 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00007124 ++ASTContext::NumImplicitDestructorsDeclared;
7125
7126 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007127 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00007128 PushOnScopeChains(Destructor, S, false);
7129 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00007130
7131 // This could be uniqued if it ever proves significant.
7132 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00007133
7134 if (ShouldDeleteDestructor(Destructor))
7135 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00007136
7137 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00007138
Douglas Gregorf1203042010-07-01 19:09:28 +00007139 return Destructor;
7140}
7141
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007142void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00007143 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007144 assert((Destructor->isDefaulted() &&
7145 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007146 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00007147 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007148 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007149
Douglas Gregor54818f02010-05-12 16:39:35 +00007150 if (Destructor->isInvalidDecl())
7151 return;
7152
Douglas Gregora57478e2010-05-01 15:04:51 +00007153 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007154
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007155 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00007156 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7157 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00007158
Douglas Gregor54818f02010-05-12 16:39:35 +00007159 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007160 Diag(CurrentLocation, diag::note_member_synthesized_at)
7161 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7162
7163 Destructor->setInvalidDecl();
7164 return;
7165 }
7166
Douglas Gregor73193272010-09-20 16:48:21 +00007167 SourceLocation Loc = Destructor->getLocation();
7168 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregoreb4089a2011-09-22 20:32:43 +00007169 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007170 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007171 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007172
7173 if (ASTMutationListener *L = getASTMutationListener()) {
7174 L->CompletedImplicitDefinition(Destructor);
7175 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007176}
7177
Sebastian Redl623ea822011-05-19 05:13:44 +00007178void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7179 CXXDestructorDecl *destructor) {
7180 // C++11 [class.dtor]p3:
7181 // A declaration of a destructor that does not have an exception-
7182 // specification is implicitly considered to have the same exception-
7183 // specification as an implicit declaration.
7184 const FunctionProtoType *dtorType = destructor->getType()->
7185 getAs<FunctionProtoType>();
7186 if (dtorType->hasExceptionSpec())
7187 return;
7188
7189 ImplicitExceptionSpecification exceptSpec =
7190 ComputeDefaultedDtorExceptionSpec(classDecl);
7191
Chandler Carruth9a797572011-09-20 04:55:26 +00007192 // Replace the destructor's type, building off the existing one. Fortunately,
7193 // the only thing of interest in the destructor type is its extended info.
7194 // The return and arguments are fixed.
7195 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl623ea822011-05-19 05:13:44 +00007196 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7197 epi.NumExceptions = exceptSpec.size();
7198 epi.Exceptions = exceptSpec.data();
7199 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7200
7201 destructor->setType(ty);
7202
7203 // FIXME: If the destructor has a body that could throw, and the newly created
7204 // spec doesn't allow exceptions, we should emit a warning, because this
7205 // change in behavior can break conforming C++03 programs at runtime.
7206 // However, we don't have a body yet, so it needs to be done somewhere else.
7207}
7208
Sebastian Redl22653ba2011-08-30 19:58:05 +00007209/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00007210/// \c To.
7211///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007212/// This routine is used to copy/move the members of a class with an
7213/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00007214/// copied are arrays, this routine builds for loops to copy them.
7215///
7216/// \param S The Sema object used for type-checking.
7217///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007218/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007219///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007220/// \param T The type of the expressions being copied/moved. Both expressions
7221/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007222///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007223/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007224///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007225/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007226///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007227/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007228/// Otherwise, it's a non-static member subobject.
7229///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007230/// \param Copying Whether we're copying or moving.
7231///
Douglas Gregorb139cd52010-05-01 20:49:11 +00007232/// \param Depth Internal parameter recording the depth of the recursion.
7233///
7234/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00007235static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00007236BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00007237 Expr *To, Expr *From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007238 bool CopyingBaseSubobject, bool Copying,
7239 unsigned Depth = 0) {
7240 // C++0x [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00007241 // Each subobject is assigned in the manner appropriate to its type:
7242 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00007243 // - if the subobject is of class type, as if by a call to operator= with
7244 // the subobject as the object expression and the corresponding
7245 // subobject of x as a single function argument (as if by explicit
7246 // qualification; that is, ignoring any possible virtual overriding
7247 // functions in more derived classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007248 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7249 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7250
7251 // Look for operator=.
7252 DeclarationName Name
7253 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7254 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7255 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7256
Sebastian Redl22653ba2011-08-30 19:58:05 +00007257 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007258 LookupResult::Filter F = OpLookup.makeFilter();
7259 while (F.hasNext()) {
7260 NamedDecl *D = F.next();
7261 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl22653ba2011-08-30 19:58:05 +00007262 if (Copying ? Method->isCopyAssignmentOperator() :
7263 Method->isMoveAssignmentOperator())
Douglas Gregorb139cd52010-05-01 20:49:11 +00007264 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00007265
Douglas Gregorb139cd52010-05-01 20:49:11 +00007266 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00007267 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007268 F.done();
7269
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007270 // Suppress the protected check (C++ [class.protected]) for each of the
7271 // assignment operators we found. This strange dance is required when
7272 // we're assigning via a base classes's copy-assignment operator. To
7273 // ensure that we're getting the right base class subobject (without
7274 // ambiguities), we need to cast "this" to that subobject type; to
7275 // ensure that we don't go through the virtual call mechanism, we need
7276 // to qualify the operator= name with the base class (see below). However,
7277 // this means that if the base class has a protected copy assignment
7278 // operator, the protected member access check will fail. So, we
7279 // rewrite "protected" access to "public" access in this case, since we
7280 // know by construction that we're calling from a derived class.
7281 if (CopyingBaseSubobject) {
7282 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7283 L != LEnd; ++L) {
7284 if (L.getAccess() == AS_protected)
7285 L.setAccess(AS_public);
7286 }
7287 }
7288
Douglas Gregorb139cd52010-05-01 20:49:11 +00007289 // Create the nested-name-specifier that will be used to qualify the
7290 // reference to operator=; this is required to suppress the virtual
7291 // call mechanism.
7292 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00007293 SS.MakeTrivial(S.Context,
7294 NestedNameSpecifier::Create(S.Context, 0, false,
7295 T.getTypePtr()),
7296 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007297
7298 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00007299 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00007300 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007301 /*FirstQualifierInScope=*/0, OpLookup,
7302 /*TemplateArgs=*/0,
7303 /*SuppressQualifierCheck=*/true);
7304 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007305 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007306
7307 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00007308
John McCalldadc5752010-08-24 06:29:42 +00007309 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007310 OpEqualRef.takeAs<Expr>(),
7311 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007312 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007313 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007314
7315 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007316 }
John McCallab8c2732010-03-16 06:11:48 +00007317
Douglas Gregorb139cd52010-05-01 20:49:11 +00007318 // - if the subobject is of scalar type, the built-in assignment
7319 // operator is used.
7320 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7321 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00007322 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007323 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007324 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007325
7326 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007327 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007328
7329 // - if the subobject is an array, each element is assigned, in the
7330 // manner appropriate to the element type;
7331
7332 // Construct a loop over the array bounds, e.g.,
7333 //
7334 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7335 //
7336 // that will copy each of the array elements.
7337 QualType SizeType = S.Context.getSizeType();
7338
7339 // Create the iteration variable.
7340 IdentifierInfo *IterationVarName = 0;
7341 {
7342 llvm::SmallString<8> Str;
7343 llvm::raw_svector_ostream OS(Str);
7344 OS << "__i" << Depth;
7345 IterationVarName = &S.Context.Idents.get(OS.str());
7346 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00007347 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007348 IterationVarName, SizeType,
7349 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007350 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007351
7352 // Initialize the iteration variable to zero.
7353 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007354 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00007355
7356 // Create a reference to the iteration variable; we'll use this several
7357 // times throughout.
7358 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00007359 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007360 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7361
7362 // Create the DeclStmt that holds the iteration variable.
7363 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7364
7365 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007366 llvm::APInt Upper
7367 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00007368 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00007369 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00007370 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7371 BO_NE, S.Context.BoolTy,
7372 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007373
7374 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007375 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00007376 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7377 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007378
7379 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007380 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7381 IterationVarRef, Loc));
7382 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7383 IterationVarRef, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00007384 if (!Copying) // Cast to rvalue
7385 From = CastForMoving(S, From);
7386
7387 // Build the copy/move for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00007388 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7389 To, From, CopyingBaseSubobject,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007390 Copying, Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00007391 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007392 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007393
7394 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00007395 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007396 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00007397 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00007398 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007399}
7400
Alexis Hunt119f3652011-05-14 05:23:20 +00007401std::pair<Sema::ImplicitExceptionSpecification, bool>
7402Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7403 CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007404 if (ClassDecl->isInvalidDecl())
7405 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7406
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007407 // C++ [class.copy]p10:
7408 // If the class definition does not explicitly declare a copy
7409 // assignment operator, one is declared implicitly.
7410 // The implicitly-defined copy assignment operator for a class X
7411 // will have the form
7412 //
7413 // X& X::operator=(const X&)
7414 //
7415 // if
7416 bool HasConstCopyAssignment = true;
7417
7418 // -- each direct base class B of X has a copy assignment operator
7419 // whose parameter is of type const B&, const volatile B& or B,
7420 // and
7421 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7422 BaseEnd = ClassDecl->bases_end();
7423 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007424 // We'll handle this below
7425 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7426 continue;
7427
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007428 assert(!Base->getType()->isDependentType() &&
7429 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00007430 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7431 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7432 &HasConstCopyAssignment);
7433 }
7434
7435 // In C++0x, the above citation has "or virtual added"
7436 if (LangOpts.CPlusPlus0x) {
7437 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7438 BaseEnd = ClassDecl->vbases_end();
7439 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7440 assert(!Base->getType()->isDependentType() &&
7441 "Cannot generate implicit members for class with dependent bases.");
7442 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7443 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7444 &HasConstCopyAssignment);
7445 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007446 }
7447
7448 // -- for all the nonstatic data members of X that are of a class
7449 // type M (or array thereof), each such class type has a copy
7450 // assignment operator whose parameter is of type const M&,
7451 // const volatile M& or M.
7452 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7453 FieldEnd = ClassDecl->field_end();
7454 HasConstCopyAssignment && Field != FieldEnd;
7455 ++Field) {
7456 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007457 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7458 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7459 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007460 }
7461 }
7462
7463 // Otherwise, the implicitly declared copy assignment operator will
7464 // have the form
7465 //
7466 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007467
Douglas Gregor68e11362010-07-01 17:48:08 +00007468 // C++ [except.spec]p14:
7469 // An implicitly declared special member function (Clause 12) shall have an
7470 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00007471
7472 // It is unspecified whether or not an implicit copy assignment operator
7473 // attempts to deduplicate calls to assignment operators of virtual bases are
7474 // made. As such, this exception specification is effectively unspecified.
7475 // Based on a similar decision made for constness in C++0x, we're erring on
7476 // the side of assuming such calls to be made regardless of whether they
7477 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00007478 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00007479 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00007480 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7481 BaseEnd = ClassDecl->bases_end();
7482 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007483 if (Base->isVirtual())
7484 continue;
7485
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007486 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00007487 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007488 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7489 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00007490 ExceptSpec.CalledDecl(CopyAssign);
7491 }
Alexis Hunt491ec602011-06-21 23:42:56 +00007492
7493 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7494 BaseEnd = ClassDecl->vbases_end();
7495 Base != BaseEnd; ++Base) {
7496 CXXRecordDecl *BaseClassDecl
7497 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7498 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7499 ArgQuals, false, 0))
7500 ExceptSpec.CalledDecl(CopyAssign);
7501 }
7502
Douglas Gregor68e11362010-07-01 17:48:08 +00007503 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7504 FieldEnd = ClassDecl->field_end();
7505 Field != FieldEnd;
7506 ++Field) {
7507 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007508 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7509 if (CXXMethodDecl *CopyAssign =
7510 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7511 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007512 }
Douglas Gregor68e11362010-07-01 17:48:08 +00007513 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007514
Alexis Hunt119f3652011-05-14 05:23:20 +00007515 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7516}
7517
7518CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7519 // Note: The following rules are largely analoguous to the copy
7520 // constructor rules. Note that virtual bases are not taken into account
7521 // for determining the argument type of the operator. Note also that
7522 // operators taking an object instead of a reference are allowed.
7523
7524 ImplicitExceptionSpecification Spec(Context);
7525 bool Const;
7526 llvm::tie(Spec, Const) =
7527 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7528
7529 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7530 QualType RetType = Context.getLValueReferenceType(ArgType);
7531 if (Const)
7532 ArgType = ArgType.withConst();
7533 ArgType = Context.getLValueReferenceType(ArgType);
7534
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007535 // An implicitly-declared copy assignment operator is an inline public
7536 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00007537 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007538 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007539 SourceLocation ClassLoc = ClassDecl->getLocation();
7540 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007541 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00007542 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00007543 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007544 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00007545 /*StorageClassAsWritten=*/SC_None,
Richard Smitha77a0a62011-08-15 21:04:07 +00007546 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf2f08062011-03-08 17:10:18 +00007547 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007548 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00007549 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007550 CopyAssignment->setImplicit();
7551 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007552
7553 // Add the parameter to the operator.
7554 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007555 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007556 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007557 SC_None,
7558 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007559 CopyAssignment->setParams(FromParam);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007560
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007561 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007562 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00007563
Douglas Gregor0be31a22010-07-02 17:43:08 +00007564 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007565 PushOnScopeChains(CopyAssignment, S, false);
7566 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007567
Alexis Huntd74c85f2011-06-22 01:05:13 +00007568 // C++0x [class.copy]p18:
7569 // ... If the class definition declares a move constructor or move
7570 // assignment operator, the implicitly declared copy assignment operator is
7571 // defined as deleted; ...
7572 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7573 ClassDecl->hasUserDeclaredMoveAssignment() ||
7574 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007575 CopyAssignment->setDeletedAsWritten();
7576
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007577 AddOverriddenMethods(ClassDecl, CopyAssignment);
7578 return CopyAssignment;
7579}
7580
Douglas Gregorb139cd52010-05-01 20:49:11 +00007581void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7582 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00007583 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007584 CopyAssignOperator->isOverloadedOperator() &&
7585 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007586 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007587 "DefineImplicitCopyAssignment called for wrong function");
7588
7589 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7590
7591 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7592 CopyAssignOperator->setInvalidDecl();
7593 return;
7594 }
7595
7596 CopyAssignOperator->setUsed();
7597
7598 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007599 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007600
7601 // C++0x [class.copy]p30:
7602 // The implicitly-defined or explicitly-defaulted copy assignment operator
7603 // for a non-union class X performs memberwise copy assignment of its
7604 // subobjects. The direct base classes of X are assigned first, in the
7605 // order of their declaration in the base-specifier-list, and then the
7606 // immediate non-static data members of X are assigned, in the order in
7607 // which they were declared in the class definition.
7608
7609 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00007610 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007611
7612 // The parameter for the "other" object, which we are copying from.
7613 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7614 Qualifiers OtherQuals = Other->getType().getQualifiers();
7615 QualType OtherRefType = Other->getType();
7616 if (const LValueReferenceType *OtherRef
7617 = OtherRefType->getAs<LValueReferenceType>()) {
7618 OtherRefType = OtherRef->getPointeeType();
7619 OtherQuals = OtherRefType.getQualifiers();
7620 }
7621
7622 // Our location for everything implicitly-generated.
7623 SourceLocation Loc = CopyAssignOperator->getLocation();
7624
7625 // Construct a reference to the "other" object. We'll be using this
7626 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00007627 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007628 assert(OtherRef && "Reference to parameter cannot fail!");
7629
7630 // Construct the "this" pointer. We'll be using this throughout the generated
7631 // ASTs.
7632 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7633 assert(This && "Reference to this cannot fail!");
7634
7635 // Assign base classes.
7636 bool Invalid = false;
7637 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7638 E = ClassDecl->bases_end(); Base != E; ++Base) {
7639 // Form the assignment:
7640 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7641 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00007642 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007643 Invalid = true;
7644 continue;
7645 }
7646
John McCallcf142162010-08-07 06:22:56 +00007647 CXXCastPath BasePath;
7648 BasePath.push_back(Base);
7649
Douglas Gregorb139cd52010-05-01 20:49:11 +00007650 // Construct the "from" expression, which is an implicit cast to the
7651 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00007652 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00007653 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7654 CK_UncheckedDerivedToBase,
7655 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007656
7657 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00007658 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007659
7660 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00007661 To = ImpCastExprToType(To.take(),
7662 Context.getCVRQualifiedType(BaseType,
7663 CopyAssignOperator->getTypeQualifiers()),
7664 CK_UncheckedDerivedToBase,
7665 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007666
7667 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00007668 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00007669 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007670 /*CopyingBaseSubobject=*/true,
7671 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007672 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007673 Diag(CurrentLocation, diag::note_member_synthesized_at)
7674 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7675 CopyAssignOperator->setInvalidDecl();
7676 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007677 }
7678
7679 // Success! Record the copy.
7680 Statements.push_back(Copy.takeAs<Expr>());
7681 }
7682
7683 // \brief Reference to the __builtin_memcpy function.
7684 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007685 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007686 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007687
7688 // Assign non-static members.
7689 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7690 FieldEnd = ClassDecl->field_end();
7691 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00007692 if (Field->isUnnamedBitfield())
7693 continue;
7694
Douglas Gregorb139cd52010-05-01 20:49:11 +00007695 // Check for members of reference type; we can't copy those.
7696 if (Field->getType()->isReferenceType()) {
7697 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7698 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7699 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007700 Diag(CurrentLocation, diag::note_member_synthesized_at)
7701 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007702 Invalid = true;
7703 continue;
7704 }
7705
7706 // Check for members of const-qualified, non-class type.
7707 QualType BaseType = Context.getBaseElementType(Field->getType());
7708 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7709 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7710 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7711 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007712 Diag(CurrentLocation, diag::note_member_synthesized_at)
7713 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007714 Invalid = true;
7715 continue;
7716 }
John McCall1b1a1db2011-06-17 00:18:42 +00007717
7718 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00007719 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7720 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007721
7722 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007723 if (FieldType->isIncompleteArrayType()) {
7724 assert(ClassDecl->hasFlexibleArrayMember() &&
7725 "Incomplete array type is not valid");
7726 continue;
7727 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007728
7729 // Build references to the field in the object we're copying from and to.
7730 CXXScopeSpec SS; // Intentionally empty
7731 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7732 LookupMemberName);
7733 MemberLookup.addDecl(*Field);
7734 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00007735 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00007736 Loc, /*IsArrow=*/false,
7737 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00007738 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00007739 Loc, /*IsArrow=*/true,
7740 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007741 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7742 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7743
7744 // If the field should be copied with __builtin_memcpy rather than via
7745 // explicit assignments, do so. This optimization only applies for arrays
7746 // of scalars and arrays of class type with trivial copy-assignment
7747 // operators.
Fariborz Jahanianc1a151b2011-08-09 00:26:11 +00007748 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl22653ba2011-08-30 19:58:05 +00007749 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007750 // Compute the size of the memory buffer to be copied.
7751 QualType SizeType = Context.getSizeType();
7752 llvm::APInt Size(Context.getTypeSize(SizeType),
7753 Context.getTypeSizeInChars(BaseType).getQuantity());
7754 for (const ConstantArrayType *Array
7755 = Context.getAsConstantArrayType(FieldType);
7756 Array;
7757 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00007758 llvm::APInt ArraySize
7759 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007760 Size *= ArraySize;
7761 }
7762
7763 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00007764 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7765 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007766
7767 bool NeedsCollectableMemCpy =
7768 (BaseType->isRecordType() &&
7769 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7770
7771 if (NeedsCollectableMemCpy) {
7772 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007773 // Create a reference to the __builtin_objc_memmove_collectable function.
7774 LookupResult R(*this,
7775 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007776 Loc, LookupOrdinaryName);
7777 LookupName(R, TUScope, true);
7778
7779 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7780 if (!CollectableMemCpy) {
7781 // Something went horribly wrong earlier, and we will have
7782 // complained about it.
7783 Invalid = true;
7784 continue;
7785 }
7786
7787 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7788 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007789 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007790 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7791 }
7792 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007793 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007794 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007795 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7796 LookupOrdinaryName);
7797 LookupName(R, TUScope, true);
7798
7799 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7800 if (!BuiltinMemCpy) {
7801 // Something went horribly wrong earlier, and we will have complained
7802 // about it.
7803 Invalid = true;
7804 continue;
7805 }
7806
7807 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7808 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007809 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007810 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7811 }
7812
John McCall37ad5512010-08-23 06:44:23 +00007813 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007814 CallArgs.push_back(To.takeAs<Expr>());
7815 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007816 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00007817 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007818 if (NeedsCollectableMemCpy)
7819 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007820 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007821 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007822 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007823 else
7824 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007825 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007826 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007827 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007828
Douglas Gregorb139cd52010-05-01 20:49:11 +00007829 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7830 Statements.push_back(Call.takeAs<Expr>());
7831 continue;
7832 }
7833
7834 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00007835 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007836 To.get(), From.get(),
7837 /*CopyingBaseSubobject=*/false,
7838 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007839 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007840 Diag(CurrentLocation, diag::note_member_synthesized_at)
7841 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7842 CopyAssignOperator->setInvalidDecl();
7843 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007844 }
7845
7846 // Success! Record the copy.
7847 Statements.push_back(Copy.takeAs<Stmt>());
7848 }
7849
7850 if (!Invalid) {
7851 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00007852 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007853
John McCalldadc5752010-08-24 06:29:42 +00007854 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007855 if (Return.isInvalid())
7856 Invalid = true;
7857 else {
7858 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00007859
7860 if (Trap.hasErrorOccurred()) {
7861 Diag(CurrentLocation, diag::note_member_synthesized_at)
7862 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7863 Invalid = true;
7864 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007865 }
7866 }
7867
7868 if (Invalid) {
7869 CopyAssignOperator->setInvalidDecl();
7870 return;
7871 }
7872
John McCalldadc5752010-08-24 06:29:42 +00007873 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00007874 /*isStmtExpr=*/false);
7875 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7876 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00007877
7878 if (ASTMutationListener *L = getASTMutationListener()) {
7879 L->CompletedImplicitDefinition(CopyAssignOperator);
7880 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007881}
7882
Sebastian Redl22653ba2011-08-30 19:58:05 +00007883Sema::ImplicitExceptionSpecification
7884Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7885 ImplicitExceptionSpecification ExceptSpec(Context);
7886
7887 if (ClassDecl->isInvalidDecl())
7888 return ExceptSpec;
7889
7890 // C++0x [except.spec]p14:
7891 // An implicitly declared special member function (Clause 12) shall have an
7892 // exception-specification. [...]
7893
7894 // It is unspecified whether or not an implicit move assignment operator
7895 // attempts to deduplicate calls to assignment operators of virtual bases are
7896 // made. As such, this exception specification is effectively unspecified.
7897 // Based on a similar decision made for constness in C++0x, we're erring on
7898 // the side of assuming such calls to be made regardless of whether they
7899 // actually happen.
7900 // Note that a move constructor is not implicitly declared when there are
7901 // virtual bases, but it can still be user-declared and explicitly defaulted.
7902 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7903 BaseEnd = ClassDecl->bases_end();
7904 Base != BaseEnd; ++Base) {
7905 if (Base->isVirtual())
7906 continue;
7907
7908 CXXRecordDecl *BaseClassDecl
7909 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7910 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7911 false, 0))
7912 ExceptSpec.CalledDecl(MoveAssign);
7913 }
7914
7915 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7916 BaseEnd = ClassDecl->vbases_end();
7917 Base != BaseEnd; ++Base) {
7918 CXXRecordDecl *BaseClassDecl
7919 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7920 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7921 false, 0))
7922 ExceptSpec.CalledDecl(MoveAssign);
7923 }
7924
7925 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7926 FieldEnd = ClassDecl->field_end();
7927 Field != FieldEnd;
7928 ++Field) {
7929 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7930 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7931 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7932 false, 0))
7933 ExceptSpec.CalledDecl(MoveAssign);
7934 }
7935 }
7936
7937 return ExceptSpec;
7938}
7939
7940CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7941 // Note: The following rules are largely analoguous to the move
7942 // constructor rules.
7943
7944 ImplicitExceptionSpecification Spec(
7945 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7946
7947 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7948 QualType RetType = Context.getLValueReferenceType(ArgType);
7949 ArgType = Context.getRValueReferenceType(ArgType);
7950
7951 // An implicitly-declared move assignment operator is an inline public
7952 // member of its class.
7953 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7954 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7955 SourceLocation ClassLoc = ClassDecl->getLocation();
7956 DeclarationNameInfo NameInfo(Name, ClassLoc);
7957 CXXMethodDecl *MoveAssignment
7958 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7959 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7960 /*TInfo=*/0, /*isStatic=*/false,
7961 /*StorageClassAsWritten=*/SC_None,
7962 /*isInline=*/true,
7963 /*isConstexpr=*/false,
7964 SourceLocation());
7965 MoveAssignment->setAccess(AS_public);
7966 MoveAssignment->setDefaulted();
7967 MoveAssignment->setImplicit();
7968 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7969
7970 // Add the parameter to the operator.
7971 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7972 ClassLoc, ClassLoc, /*Id=*/0,
7973 ArgType, /*TInfo=*/0,
7974 SC_None,
7975 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007976 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00007977
7978 // Note that we have added this copy-assignment operator.
7979 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7980
7981 // C++0x [class.copy]p9:
7982 // If the definition of a class X does not explicitly declare a move
7983 // assignment operator, one will be implicitly declared as defaulted if and
7984 // only if:
7985 // [...]
7986 // - the move assignment operator would not be implicitly defined as
7987 // deleted.
7988 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7989 // Cache this result so that we don't try to generate this over and over
7990 // on every lookup, leaking memory and wasting time.
7991 ClassDecl->setFailedImplicitMoveAssignment();
7992 return 0;
7993 }
7994
7995 if (Scope *S = getScopeForContext(ClassDecl))
7996 PushOnScopeChains(MoveAssignment, S, false);
7997 ClassDecl->addDecl(MoveAssignment);
7998
7999 AddOverriddenMethods(ClassDecl, MoveAssignment);
8000 return MoveAssignment;
8001}
8002
8003void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8004 CXXMethodDecl *MoveAssignOperator) {
8005 assert((MoveAssignOperator->isDefaulted() &&
8006 MoveAssignOperator->isOverloadedOperator() &&
8007 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8008 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8009 "DefineImplicitMoveAssignment called for wrong function");
8010
8011 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8012
8013 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8014 MoveAssignOperator->setInvalidDecl();
8015 return;
8016 }
8017
8018 MoveAssignOperator->setUsed();
8019
8020 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8021 DiagnosticErrorTrap Trap(Diags);
8022
8023 // C++0x [class.copy]p28:
8024 // The implicitly-defined or move assignment operator for a non-union class
8025 // X performs memberwise move assignment of its subobjects. The direct base
8026 // classes of X are assigned first, in the order of their declaration in the
8027 // base-specifier-list, and then the immediate non-static data members of X
8028 // are assigned, in the order in which they were declared in the class
8029 // definition.
8030
8031 // The statements that form the synthesized function body.
8032 ASTOwningVector<Stmt*> Statements(*this);
8033
8034 // The parameter for the "other" object, which we are move from.
8035 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8036 QualType OtherRefType = Other->getType()->
8037 getAs<RValueReferenceType>()->getPointeeType();
8038 assert(OtherRefType.getQualifiers() == 0 &&
8039 "Bad argument type of defaulted move assignment");
8040
8041 // Our location for everything implicitly-generated.
8042 SourceLocation Loc = MoveAssignOperator->getLocation();
8043
8044 // Construct a reference to the "other" object. We'll be using this
8045 // throughout the generated ASTs.
8046 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8047 assert(OtherRef && "Reference to parameter cannot fail!");
8048 // Cast to rvalue.
8049 OtherRef = CastForMoving(*this, OtherRef);
8050
8051 // Construct the "this" pointer. We'll be using this throughout the generated
8052 // ASTs.
8053 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8054 assert(This && "Reference to this cannot fail!");
8055
8056 // Assign base classes.
8057 bool Invalid = false;
8058 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8059 E = ClassDecl->bases_end(); Base != E; ++Base) {
8060 // Form the assignment:
8061 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8062 QualType BaseType = Base->getType().getUnqualifiedType();
8063 if (!BaseType->isRecordType()) {
8064 Invalid = true;
8065 continue;
8066 }
8067
8068 CXXCastPath BasePath;
8069 BasePath.push_back(Base);
8070
8071 // Construct the "from" expression, which is an implicit cast to the
8072 // appropriately-qualified base type.
8073 Expr *From = OtherRef;
8074 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00008075 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00008076
8077 // Dereference "this".
8078 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8079
8080 // Implicitly cast "this" to the appropriately-qualified base type.
8081 To = ImpCastExprToType(To.take(),
8082 Context.getCVRQualifiedType(BaseType,
8083 MoveAssignOperator->getTypeQualifiers()),
8084 CK_UncheckedDerivedToBase,
8085 VK_LValue, &BasePath);
8086
8087 // Build the move.
8088 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8089 To.get(), From,
8090 /*CopyingBaseSubobject=*/true,
8091 /*Copying=*/false);
8092 if (Move.isInvalid()) {
8093 Diag(CurrentLocation, diag::note_member_synthesized_at)
8094 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8095 MoveAssignOperator->setInvalidDecl();
8096 return;
8097 }
8098
8099 // Success! Record the move.
8100 Statements.push_back(Move.takeAs<Expr>());
8101 }
8102
8103 // \brief Reference to the __builtin_memcpy function.
8104 Expr *BuiltinMemCpyRef = 0;
8105 // \brief Reference to the __builtin_objc_memmove_collectable function.
8106 Expr *CollectableMemCpyRef = 0;
8107
8108 // Assign non-static members.
8109 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8110 FieldEnd = ClassDecl->field_end();
8111 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00008112 if (Field->isUnnamedBitfield())
8113 continue;
8114
Sebastian Redl22653ba2011-08-30 19:58:05 +00008115 // Check for members of reference type; we can't move those.
8116 if (Field->getType()->isReferenceType()) {
8117 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8118 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8119 Diag(Field->getLocation(), diag::note_declared_at);
8120 Diag(CurrentLocation, diag::note_member_synthesized_at)
8121 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8122 Invalid = true;
8123 continue;
8124 }
8125
8126 // Check for members of const-qualified, non-class type.
8127 QualType BaseType = Context.getBaseElementType(Field->getType());
8128 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8129 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8130 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8131 Diag(Field->getLocation(), diag::note_declared_at);
8132 Diag(CurrentLocation, diag::note_member_synthesized_at)
8133 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8134 Invalid = true;
8135 continue;
8136 }
8137
8138 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00008139 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8140 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00008141
8142 QualType FieldType = Field->getType().getNonReferenceType();
8143 if (FieldType->isIncompleteArrayType()) {
8144 assert(ClassDecl->hasFlexibleArrayMember() &&
8145 "Incomplete array type is not valid");
8146 continue;
8147 }
8148
8149 // Build references to the field in the object we're copying from and to.
8150 CXXScopeSpec SS; // Intentionally empty
8151 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8152 LookupMemberName);
8153 MemberLookup.addDecl(*Field);
8154 MemberLookup.resolveKind();
8155 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8156 Loc, /*IsArrow=*/false,
8157 SS, 0, MemberLookup, 0);
8158 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8159 Loc, /*IsArrow=*/true,
8160 SS, 0, MemberLookup, 0);
8161 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8162 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8163
8164 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8165 "Member reference with rvalue base must be rvalue except for reference "
8166 "members, which aren't allowed for move assignment.");
8167
8168 // If the field should be copied with __builtin_memcpy rather than via
8169 // explicit assignments, do so. This optimization only applies for arrays
8170 // of scalars and arrays of class type with trivial move-assignment
8171 // operators.
8172 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8173 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8174 // Compute the size of the memory buffer to be copied.
8175 QualType SizeType = Context.getSizeType();
8176 llvm::APInt Size(Context.getTypeSize(SizeType),
8177 Context.getTypeSizeInChars(BaseType).getQuantity());
8178 for (const ConstantArrayType *Array
8179 = Context.getAsConstantArrayType(FieldType);
8180 Array;
8181 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8182 llvm::APInt ArraySize
8183 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8184 Size *= ArraySize;
8185 }
8186
Douglas Gregor528499b2011-09-01 02:09:07 +00008187 // Take the address of the field references for "from" and "to". We
8188 // directly construct UnaryOperators here because semantic analysis
8189 // does not permit us to take the address of an xvalue.
8190 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8191 Context.getPointerType(From.get()->getType()),
8192 VK_RValue, OK_Ordinary, Loc);
8193 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8194 Context.getPointerType(To.get()->getType()),
8195 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008196
8197 bool NeedsCollectableMemCpy =
8198 (BaseType->isRecordType() &&
8199 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8200
8201 if (NeedsCollectableMemCpy) {
8202 if (!CollectableMemCpyRef) {
8203 // Create a reference to the __builtin_objc_memmove_collectable function.
8204 LookupResult R(*this,
8205 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8206 Loc, LookupOrdinaryName);
8207 LookupName(R, TUScope, true);
8208
8209 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8210 if (!CollectableMemCpy) {
8211 // Something went horribly wrong earlier, and we will have
8212 // complained about it.
8213 Invalid = true;
8214 continue;
8215 }
8216
8217 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8218 CollectableMemCpy->getType(),
8219 VK_LValue, Loc, 0).take();
8220 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8221 }
8222 }
8223 // Create a reference to the __builtin_memcpy builtin function.
8224 else if (!BuiltinMemCpyRef) {
8225 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8226 LookupOrdinaryName);
8227 LookupName(R, TUScope, true);
8228
8229 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8230 if (!BuiltinMemCpy) {
8231 // Something went horribly wrong earlier, and we will have complained
8232 // about it.
8233 Invalid = true;
8234 continue;
8235 }
8236
8237 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8238 BuiltinMemCpy->getType(),
8239 VK_LValue, Loc, 0).take();
8240 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8241 }
8242
8243 ASTOwningVector<Expr*> CallArgs(*this);
8244 CallArgs.push_back(To.takeAs<Expr>());
8245 CallArgs.push_back(From.takeAs<Expr>());
8246 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8247 ExprResult Call = ExprError();
8248 if (NeedsCollectableMemCpy)
8249 Call = ActOnCallExpr(/*Scope=*/0,
8250 CollectableMemCpyRef,
8251 Loc, move_arg(CallArgs),
8252 Loc);
8253 else
8254 Call = ActOnCallExpr(/*Scope=*/0,
8255 BuiltinMemCpyRef,
8256 Loc, move_arg(CallArgs),
8257 Loc);
8258
8259 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8260 Statements.push_back(Call.takeAs<Expr>());
8261 continue;
8262 }
8263
8264 // Build the move of this field.
8265 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8266 To.get(), From.get(),
8267 /*CopyingBaseSubobject=*/false,
8268 /*Copying=*/false);
8269 if (Move.isInvalid()) {
8270 Diag(CurrentLocation, diag::note_member_synthesized_at)
8271 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8272 MoveAssignOperator->setInvalidDecl();
8273 return;
8274 }
8275
8276 // Success! Record the copy.
8277 Statements.push_back(Move.takeAs<Stmt>());
8278 }
8279
8280 if (!Invalid) {
8281 // Add a "return *this;"
8282 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8283
8284 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8285 if (Return.isInvalid())
8286 Invalid = true;
8287 else {
8288 Statements.push_back(Return.takeAs<Stmt>());
8289
8290 if (Trap.hasErrorOccurred()) {
8291 Diag(CurrentLocation, diag::note_member_synthesized_at)
8292 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8293 Invalid = true;
8294 }
8295 }
8296 }
8297
8298 if (Invalid) {
8299 MoveAssignOperator->setInvalidDecl();
8300 return;
8301 }
8302
8303 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8304 /*isStmtExpr=*/false);
8305 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8306 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8307
8308 if (ASTMutationListener *L = getASTMutationListener()) {
8309 L->CompletedImplicitDefinition(MoveAssignOperator);
8310 }
8311}
8312
Alexis Hunt913820d2011-05-13 06:10:58 +00008313std::pair<Sema::ImplicitExceptionSpecification, bool>
8314Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008315 if (ClassDecl->isInvalidDecl())
8316 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8317
Douglas Gregor54be3392010-07-01 17:57:27 +00008318 // C++ [class.copy]p5:
8319 // The implicitly-declared copy constructor for a class X will
8320 // have the form
8321 //
8322 // X::X(const X&)
8323 //
8324 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00008325 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00008326 bool HasConstCopyConstructor = true;
8327
8328 // -- each direct or virtual base class B of X has a copy
8329 // constructor whose first parameter is of type const B& or
8330 // const volatile B&, and
8331 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8332 BaseEnd = ClassDecl->bases_end();
8333 HasConstCopyConstructor && Base != BaseEnd;
8334 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008335 // Virtual bases are handled below.
8336 if (Base->isVirtual())
8337 continue;
8338
Douglas Gregora6d69502010-07-02 23:41:54 +00008339 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00008340 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008341 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8342 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00008343 }
8344
8345 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8346 BaseEnd = ClassDecl->vbases_end();
8347 HasConstCopyConstructor && Base != BaseEnd;
8348 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008349 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00008350 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008351 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8352 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008353 }
8354
8355 // -- for all the nonstatic data members of X that are of a
8356 // class type M (or array thereof), each such class type
8357 // has a copy constructor whose first parameter is of type
8358 // const M& or const volatile M&.
8359 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8360 FieldEnd = ClassDecl->field_end();
8361 HasConstCopyConstructor && Field != FieldEnd;
8362 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008363 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008364 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008365 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8366 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008367 }
8368 }
Douglas Gregor54be3392010-07-01 17:57:27 +00008369 // Otherwise, the implicitly declared copy constructor will have
8370 // the form
8371 //
8372 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00008373
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008374 // C++ [except.spec]p14:
8375 // An implicitly declared special member function (Clause 12) shall have an
8376 // exception-specification. [...]
8377 ImplicitExceptionSpecification ExceptSpec(Context);
8378 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8379 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8380 BaseEnd = ClassDecl->bases_end();
8381 Base != BaseEnd;
8382 ++Base) {
8383 // Virtual bases are handled below.
8384 if (Base->isVirtual())
8385 continue;
8386
Douglas Gregora6d69502010-07-02 23:41:54 +00008387 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008388 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008389 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008390 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008391 ExceptSpec.CalledDecl(CopyConstructor);
8392 }
8393 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8394 BaseEnd = ClassDecl->vbases_end();
8395 Base != BaseEnd;
8396 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008397 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008398 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008399 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008400 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008401 ExceptSpec.CalledDecl(CopyConstructor);
8402 }
8403 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8404 FieldEnd = ClassDecl->field_end();
8405 Field != FieldEnd;
8406 ++Field) {
8407 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008408 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8409 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008410 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00008411 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008412 }
8413 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008414
Alexis Hunt913820d2011-05-13 06:10:58 +00008415 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8416}
8417
8418CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8419 CXXRecordDecl *ClassDecl) {
8420 // C++ [class.copy]p4:
8421 // If the class definition does not explicitly declare a copy
8422 // constructor, one is declared implicitly.
8423
8424 ImplicitExceptionSpecification Spec(Context);
8425 bool Const;
8426 llvm::tie(Spec, Const) =
8427 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8428
8429 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8430 QualType ArgType = ClassType;
8431 if (Const)
8432 ArgType = ArgType.withConst();
8433 ArgType = Context.getLValueReferenceType(ArgType);
8434
8435 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8436
Douglas Gregor54be3392010-07-01 17:57:27 +00008437 DeclarationName Name
8438 = Context.DeclarationNames.getCXXConstructorName(
8439 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008440 SourceLocation ClassLoc = ClassDecl->getLocation();
8441 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00008442
8443 // An implicitly-declared copy constructor is an inline public
8444 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00008445 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00008446 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00008447 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00008448 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00008449 /*TInfo=*/0,
8450 /*isExplicit=*/false,
8451 /*isInline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00008452 /*isImplicitlyDeclared=*/true,
8453 // FIXME: apply the rules for definitions here
8454 /*isConstexpr=*/false);
Douglas Gregor54be3392010-07-01 17:57:27 +00008455 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00008456 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00008457 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8458
Douglas Gregora6d69502010-07-02 23:41:54 +00008459 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00008460 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8461
Douglas Gregor54be3392010-07-01 17:57:27 +00008462 // Add the parameter to the constructor.
8463 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008464 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00008465 /*IdentifierInfo=*/0,
8466 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008467 SC_None,
8468 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008469 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +00008470
Douglas Gregor0be31a22010-07-02 17:43:08 +00008471 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00008472 PushOnScopeChains(CopyConstructor, S, false);
8473 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008474
Alexis Huntd74c85f2011-06-22 01:05:13 +00008475 // C++0x [class.copy]p7:
8476 // ... If the class definition declares a move constructor or move
8477 // assignment operator, the implicitly declared constructor is defined as
8478 // deleted; ...
8479 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8480 ClassDecl->hasUserDeclaredMoveAssignment() ||
Alexis Hunt1bc6f712011-10-11 04:55:36 +00008481 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00008482 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00008483
8484 return CopyConstructor;
8485}
8486
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008487void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00008488 CXXConstructorDecl *CopyConstructor) {
8489 assert((CopyConstructor->isDefaulted() &&
8490 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008491 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008492 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008493
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00008494 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008495 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008496
Douglas Gregora57478e2010-05-01 15:04:51 +00008497 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008498 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008499
Alexis Hunt1d792652011-01-08 20:30:50 +00008500 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008501 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00008502 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00008503 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00008504 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00008505 } else {
8506 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8507 CopyConstructor->getLocation(),
8508 MultiStmtArg(*this, 0, 0),
8509 /*isStmtExpr=*/false)
8510 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008511 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00008512 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00008513
8514 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00008515 if (ASTMutationListener *L = getASTMutationListener()) {
8516 L->CompletedImplicitDefinition(CopyConstructor);
8517 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008518}
8519
Sebastian Redl22653ba2011-08-30 19:58:05 +00008520Sema::ImplicitExceptionSpecification
8521Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8522 // C++ [except.spec]p14:
8523 // An implicitly declared special member function (Clause 12) shall have an
8524 // exception-specification. [...]
8525 ImplicitExceptionSpecification ExceptSpec(Context);
8526 if (ClassDecl->isInvalidDecl())
8527 return ExceptSpec;
8528
8529 // Direct base-class constructors.
8530 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8531 BEnd = ClassDecl->bases_end();
8532 B != BEnd; ++B) {
8533 if (B->isVirtual()) // Handled below.
8534 continue;
8535
8536 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8537 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8538 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8539 // If this is a deleted function, add it anyway. This might be conformant
8540 // with the standard. This might not. I'm not sure. It might not matter.
8541 if (Constructor)
8542 ExceptSpec.CalledDecl(Constructor);
8543 }
8544 }
8545
8546 // Virtual base-class constructors.
8547 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8548 BEnd = ClassDecl->vbases_end();
8549 B != BEnd; ++B) {
8550 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8551 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8552 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8553 // If this is a deleted function, add it anyway. This might be conformant
8554 // with the standard. This might not. I'm not sure. It might not matter.
8555 if (Constructor)
8556 ExceptSpec.CalledDecl(Constructor);
8557 }
8558 }
8559
8560 // Field constructors.
8561 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8562 FEnd = ClassDecl->field_end();
8563 F != FEnd; ++F) {
8564 if (F->hasInClassInitializer()) {
8565 if (Expr *E = F->getInClassInitializer())
8566 ExceptSpec.CalledExpr(E);
8567 else if (!F->isInvalidDecl())
8568 ExceptSpec.SetDelayed();
8569 } else if (const RecordType *RecordTy
8570 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8571 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8572 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8573 // If this is a deleted function, add it anyway. This might be conformant
8574 // with the standard. This might not. I'm not sure. It might not matter.
8575 // In particular, the problem is that this function never gets called. It
8576 // might just be ill-formed because this function attempts to refer to
8577 // a deleted function here.
8578 if (Constructor)
8579 ExceptSpec.CalledDecl(Constructor);
8580 }
8581 }
8582
8583 return ExceptSpec;
8584}
8585
8586CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8587 CXXRecordDecl *ClassDecl) {
8588 ImplicitExceptionSpecification Spec(
8589 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8590
8591 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8592 QualType ArgType = Context.getRValueReferenceType(ClassType);
8593
8594 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8595
8596 DeclarationName Name
8597 = Context.DeclarationNames.getCXXConstructorName(
8598 Context.getCanonicalType(ClassType));
8599 SourceLocation ClassLoc = ClassDecl->getLocation();
8600 DeclarationNameInfo NameInfo(Name, ClassLoc);
8601
8602 // C++0x [class.copy]p11:
8603 // An implicitly-declared copy/move constructor is an inline public
8604 // member of its class.
8605 CXXConstructorDecl *MoveConstructor
8606 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8607 Context.getFunctionType(Context.VoidTy,
8608 &ArgType, 1, EPI),
8609 /*TInfo=*/0,
8610 /*isExplicit=*/false,
8611 /*isInline=*/true,
8612 /*isImplicitlyDeclared=*/true,
8613 // FIXME: apply the rules for definitions here
8614 /*isConstexpr=*/false);
8615 MoveConstructor->setAccess(AS_public);
8616 MoveConstructor->setDefaulted();
8617 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8618
8619 // Add the parameter to the constructor.
8620 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8621 ClassLoc, ClassLoc,
8622 /*IdentifierInfo=*/0,
8623 ArgType, /*TInfo=*/0,
8624 SC_None,
8625 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008626 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008627
8628 // C++0x [class.copy]p9:
8629 // If the definition of a class X does not explicitly declare a move
8630 // constructor, one will be implicitly declared as defaulted if and only if:
8631 // [...]
8632 // - the move constructor would not be implicitly defined as deleted.
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00008633 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00008634 // Cache this result so that we don't try to generate this over and over
8635 // on every lookup, leaking memory and wasting time.
8636 ClassDecl->setFailedImplicitMoveConstructor();
8637 return 0;
8638 }
8639
8640 // Note that we have declared this constructor.
8641 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8642
8643 if (Scope *S = getScopeForContext(ClassDecl))
8644 PushOnScopeChains(MoveConstructor, S, false);
8645 ClassDecl->addDecl(MoveConstructor);
8646
8647 return MoveConstructor;
8648}
8649
8650void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8651 CXXConstructorDecl *MoveConstructor) {
8652 assert((MoveConstructor->isDefaulted() &&
8653 MoveConstructor->isMoveConstructor() &&
8654 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8655 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8656
8657 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8658 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8659
8660 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8661 DiagnosticErrorTrap Trap(Diags);
8662
8663 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8664 Trap.hasErrorOccurred()) {
8665 Diag(CurrentLocation, diag::note_member_synthesized_at)
8666 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8667 MoveConstructor->setInvalidDecl();
8668 } else {
8669 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8670 MoveConstructor->getLocation(),
8671 MultiStmtArg(*this, 0, 0),
8672 /*isStmtExpr=*/false)
8673 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008674 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008675 }
8676
8677 MoveConstructor->setUsed();
8678
8679 if (ASTMutationListener *L = getASTMutationListener()) {
8680 L->CompletedImplicitDefinition(MoveConstructor);
8681 }
8682}
8683
John McCalldadc5752010-08-24 06:29:42 +00008684ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008685Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00008686 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008687 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008688 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008689 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008690 unsigned ConstructKind,
8691 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00008692 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00008693
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008694 // C++0x [class.copy]p34:
8695 // When certain criteria are met, an implementation is allowed to
8696 // omit the copy/move construction of a class object, even if the
8697 // copy/move constructor and/or destructor for the object have
8698 // side effects. [...]
8699 // - when a temporary class object that has not been bound to a
8700 // reference (12.2) would be copied/moved to a class object
8701 // with the same cv-unqualified type, the copy/move operation
8702 // can be omitted by constructing the temporary object
8703 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00008704 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00008705 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00008706 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00008707 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00008708 }
Mike Stump11289f42009-09-09 15:08:12 +00008709
8710 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008711 Elidable, move(ExprArgs), HadMultipleCandidates,
8712 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00008713}
8714
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008715/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8716/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00008717ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008718Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8719 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008720 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008721 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008722 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008723 unsigned ConstructKind,
8724 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00008725 unsigned NumExprs = ExprArgs.size();
8726 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00008727
Nick Lewyckyd4693212011-03-25 01:44:32 +00008728 for (specific_attr_iterator<NonNullAttr>
8729 i = Constructor->specific_attr_begin<NonNullAttr>(),
8730 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8731 const NonNullAttr *NonNull = *i;
8732 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8733 }
8734
Douglas Gregor27381f32009-11-23 12:27:39 +00008735 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00008736 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008737 Constructor, Elidable, Exprs, NumExprs,
8738 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008739 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8740 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008741}
8742
Mike Stump11289f42009-09-09 15:08:12 +00008743bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00008744 CXXConstructorDecl *Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008745 MultiExprArg Exprs,
8746 bool HadMultipleCandidates) {
Chandler Carruth01718152010-10-25 08:47:36 +00008747 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00008748 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00008749 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008750 move(Exprs), HadMultipleCandidates, false,
8751 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008752 if (TempResult.isInvalid())
8753 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008754
Anders Carlsson6eb55572009-08-25 05:12:04 +00008755 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00008756 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00008757 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00008758 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00008759 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00008760
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00008761 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00008762}
8763
John McCall03c48482010-02-02 09:10:11 +00008764void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00008765 if (VD->isInvalidDecl()) return;
8766
John McCall03c48482010-02-02 09:10:11 +00008767 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00008768 if (ClassDecl->isInvalidDecl()) return;
8769 if (ClassDecl->hasTrivialDestructor()) return;
8770 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00008771
Chandler Carruth86d17d32011-03-27 21:26:48 +00008772 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8773 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8774 CheckDestructorAccess(VD->getLocation(), Destructor,
8775 PDiag(diag::err_access_dtor_var)
8776 << VD->getDeclName()
8777 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00008778
Chandler Carruth86d17d32011-03-27 21:26:48 +00008779 if (!VD->hasGlobalStorage()) return;
8780
8781 // Emit warning for non-trivial dtor in global scope (a real global,
8782 // class-static, function-static).
8783 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8784
8785 // TODO: this should be re-enabled for static locals by !CXAAtExit
8786 if (!VD->isStaticLocal())
8787 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008788}
8789
Mike Stump11289f42009-09-09 15:08:12 +00008790/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008791/// ActOnDeclarator, when a C++ direct initializer is present.
8792/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00008793void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00008794 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008795 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00008796 SourceLocation RParenLoc,
8797 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00008798 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008799
8800 // If there is no declaration, there was an error parsing it. Just ignore
8801 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00008802 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008803 return;
Mike Stump11289f42009-09-09 15:08:12 +00008804
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008805 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8806 if (!VDecl) {
8807 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8808 RealDecl->setInvalidDecl();
8809 return;
8810 }
8811
Richard Smith30482bc2011-02-20 03:19:35 +00008812 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8813 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00008814 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8815 if (Exprs.size() > 1) {
8816 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8817 diag::err_auto_var_init_multiple_expressions)
8818 << VDecl->getDeclName() << VDecl->getType()
8819 << VDecl->getSourceRange();
8820 RealDecl->setInvalidDecl();
8821 return;
8822 }
8823
8824 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00008825 TypeSourceInfo *DeducedType = 0;
8826 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00008827 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8828 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8829 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00008830 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00008831 RealDecl->setInvalidDecl();
8832 return;
8833 }
Richard Smith9647d3c2011-03-17 16:11:59 +00008834 VDecl->setTypeSourceInfo(DeducedType);
8835 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00008836
John McCall31168b02011-06-15 23:02:42 +00008837 // In ARC, infer lifetime.
8838 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8839 VDecl->setInvalidDecl();
8840
Richard Smith30482bc2011-02-20 03:19:35 +00008841 // If this is a redeclaration, check that the type we just deduced matches
8842 // the previously declared type.
8843 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8844 MergeVarDeclTypes(VDecl, Old);
8845 }
8846
Douglas Gregor402250f2009-08-26 21:14:46 +00008847 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00008848 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008849 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8850 //
8851 // Clients that want to distinguish between the two forms, can check for
8852 // direct initializer using VarDecl::hasCXXDirectInitializer().
8853 // A major benefit is that clients that don't particularly care about which
8854 // exactly form was it (like the CodeGen) can handle both cases without
8855 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00008856
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008857 // C++ 8.5p11:
8858 // The form of initialization (using parentheses or '=') is generally
8859 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00008860 // class type.
8861
Douglas Gregor50dc2192010-02-11 22:55:30 +00008862 if (!VDecl->getType()->isDependentType() &&
Douglas Gregorb06fa542011-10-10 16:05:18 +00008863 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor50dc2192010-02-11 22:55:30 +00008864 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00008865 diag::err_typecheck_decl_incomplete_type)) {
8866 VDecl->setInvalidDecl();
8867 return;
8868 }
8869
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008870 // The variable can not have an abstract class type.
8871 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8872 diag::err_abstract_type_in_decl,
8873 AbstractVariableType))
8874 VDecl->setInvalidDecl();
8875
Sebastian Redl5ca79842010-02-01 20:16:42 +00008876 const VarDecl *Def;
8877 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008878 Diag(VDecl->getLocation(), diag::err_redefinition)
8879 << VDecl->getDeclName();
8880 Diag(Def->getLocation(), diag::note_previous_definition);
8881 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00008882 return;
8883 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00008884
Douglas Gregorf0f83692010-08-24 05:27:49 +00008885 // C++ [class.static.data]p4
8886 // If a static data member is of const integral or const
8887 // enumeration type, its declaration in the class definition can
8888 // specify a constant-initializer which shall be an integral
8889 // constant expression (5.19). In that case, the member can appear
8890 // in integral constant expressions. The member shall still be
8891 // defined in a namespace scope if it is used in the program and the
8892 // namespace scope definition shall not contain an initializer.
8893 //
8894 // We already performed a redefinition check above, but for static
8895 // data members we also need to check whether there was an in-class
8896 // declaration with an initializer.
8897 const VarDecl* PrevInit = 0;
8898 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8899 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8900 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8901 return;
8902 }
8903
Douglas Gregor71f39c92010-12-16 01:31:22 +00008904 bool IsDependent = false;
8905 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8906 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8907 VDecl->setInvalidDecl();
8908 return;
8909 }
8910
8911 if (Exprs.get()[I]->isTypeDependent())
8912 IsDependent = true;
8913 }
8914
Douglas Gregor50dc2192010-02-11 22:55:30 +00008915 // If either the declaration has a dependent type or if any of the
8916 // expressions is type-dependent, we represent the initialization
8917 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00008918 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00008919 // Let clients know that initialization was done with a direct initializer.
8920 VDecl->setCXXDirectInitializer(true);
8921
8922 // Store the initialization expressions as a ParenListExpr.
8923 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00008924 VDecl->setInit(new (Context) ParenListExpr(
8925 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8926 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00008927 return;
8928 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008929
8930 // Capture the variable that is being initialized and the style of
8931 // initialization.
8932 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8933
8934 // FIXME: Poor source location information.
8935 InitializationKind Kind
8936 = InitializationKind::CreateDirect(VDecl->getLocation(),
8937 LParenLoc, RParenLoc);
8938
Douglas Gregorb06fa542011-10-10 16:05:18 +00008939 QualType T = VDecl->getType();
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008940 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00008941 Exprs.get(), Exprs.size());
Douglas Gregorb06fa542011-10-10 16:05:18 +00008942 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008943 if (Result.isInvalid()) {
8944 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008945 return;
Douglas Gregorb06fa542011-10-10 16:05:18 +00008946 } else if (T != VDecl->getType()) {
8947 VDecl->setType(T);
8948 Result.get()->setType(T);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008949 }
John McCallacf0ee52010-10-08 02:01:28 +00008950
Douglas Gregorb06fa542011-10-10 16:05:18 +00008951
Richard Smith2316cd82011-09-29 19:11:37 +00008952 Expr *Init = Result.get();
8953 CheckImplicitConversions(Init, LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00008954
Richard Smith2316cd82011-09-29 19:11:37 +00008955 if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() &&
8956 !Init->isValueDependent() &&
8957 !Init->isConstantInitializer(Context,
8958 VDecl->getType()->isReferenceType())) {
8959 // FIXME: Improve this diagnostic to explain why the initializer is not
8960 // a constant expression.
8961 Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init)
8962 << VDecl << Init->getSourceRange();
8963 }
8964
8965 Init = MaybeCreateExprWithCleanups(Init);
8966 VDecl->setInit(Init);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008967 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00008968
John McCall8b7fd8f12011-01-19 11:48:09 +00008969 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008970}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00008971
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008972/// \brief Given a constructor and the set of arguments provided for the
8973/// constructor, convert the arguments and add any required default arguments
8974/// to form a proper call to this constructor.
8975///
8976/// \returns true if an error occurred, false otherwise.
8977bool
8978Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8979 MultiExprArg ArgsPtr,
8980 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00008981 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008982 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8983 unsigned NumArgs = ArgsPtr.size();
8984 Expr **Args = (Expr **)ArgsPtr.get();
8985
8986 const FunctionProtoType *Proto
8987 = Constructor->getType()->getAs<FunctionProtoType>();
8988 assert(Proto && "Constructor without a prototype?");
8989 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008990
8991 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008992 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008993 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008994 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00008995 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00008996
8997 VariadicCallType CallType =
8998 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008999 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009000 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9001 Proto, 0, Args, NumArgs, AllArgs,
9002 CallType);
9003 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9004 ConvertedArgs.push_back(AllArgs[i]);
9005 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00009006}
9007
Anders Carlssone363c8e2009-12-12 00:32:00 +00009008static inline bool
9009CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9010 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00009011 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00009012 if (isa<NamespaceDecl>(DC)) {
9013 return SemaRef.Diag(FnDecl->getLocation(),
9014 diag::err_operator_new_delete_declared_in_namespace)
9015 << FnDecl->getDeclName();
9016 }
9017
9018 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00009019 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009020 return SemaRef.Diag(FnDecl->getLocation(),
9021 diag::err_operator_new_delete_declared_static)
9022 << FnDecl->getDeclName();
9023 }
9024
Anders Carlsson60659a82009-12-12 02:43:16 +00009025 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00009026}
9027
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009028static inline bool
9029CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9030 CanQualType ExpectedResultType,
9031 CanQualType ExpectedFirstParamType,
9032 unsigned DependentParamTypeDiag,
9033 unsigned InvalidParamTypeDiag) {
9034 QualType ResultType =
9035 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9036
9037 // Check that the result type is not dependent.
9038 if (ResultType->isDependentType())
9039 return SemaRef.Diag(FnDecl->getLocation(),
9040 diag::err_operator_new_delete_dependent_result_type)
9041 << FnDecl->getDeclName() << ExpectedResultType;
9042
9043 // Check that the result type is what we expect.
9044 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9045 return SemaRef.Diag(FnDecl->getLocation(),
9046 diag::err_operator_new_delete_invalid_result_type)
9047 << FnDecl->getDeclName() << ExpectedResultType;
9048
9049 // A function template must have at least 2 parameters.
9050 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9051 return SemaRef.Diag(FnDecl->getLocation(),
9052 diag::err_operator_new_delete_template_too_few_parameters)
9053 << FnDecl->getDeclName();
9054
9055 // The function decl must have at least 1 parameter.
9056 if (FnDecl->getNumParams() == 0)
9057 return SemaRef.Diag(FnDecl->getLocation(),
9058 diag::err_operator_new_delete_too_few_parameters)
9059 << FnDecl->getDeclName();
9060
9061 // Check the the first parameter type is not dependent.
9062 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9063 if (FirstParamType->isDependentType())
9064 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9065 << FnDecl->getDeclName() << ExpectedFirstParamType;
9066
9067 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00009068 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009069 ExpectedFirstParamType)
9070 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9071 << FnDecl->getDeclName() << ExpectedFirstParamType;
9072
9073 return false;
9074}
9075
Anders Carlsson12308f42009-12-11 23:23:22 +00009076static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009077CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009078 // C++ [basic.stc.dynamic.allocation]p1:
9079 // A program is ill-formed if an allocation function is declared in a
9080 // namespace scope other than global scope or declared static in global
9081 // scope.
9082 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9083 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009084
9085 CanQualType SizeTy =
9086 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9087
9088 // C++ [basic.stc.dynamic.allocation]p1:
9089 // The return type shall be void*. The first parameter shall have type
9090 // std::size_t.
9091 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9092 SizeTy,
9093 diag::err_operator_new_dependent_param_type,
9094 diag::err_operator_new_param_type))
9095 return true;
9096
9097 // C++ [basic.stc.dynamic.allocation]p1:
9098 // The first parameter shall not have an associated default argument.
9099 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00009100 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009101 diag::err_operator_new_default_arg)
9102 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9103
9104 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00009105}
9106
9107static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00009108CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9109 // C++ [basic.stc.dynamic.deallocation]p1:
9110 // A program is ill-formed if deallocation functions are declared in a
9111 // namespace scope other than global scope or declared static in global
9112 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00009113 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9114 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009115
9116 // C++ [basic.stc.dynamic.deallocation]p2:
9117 // Each deallocation function shall return void and its first parameter
9118 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009119 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9120 SemaRef.Context.VoidPtrTy,
9121 diag::err_operator_delete_dependent_param_type,
9122 diag::err_operator_delete_param_type))
9123 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009124
Anders Carlsson12308f42009-12-11 23:23:22 +00009125 return false;
9126}
9127
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009128/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9129/// of this overloaded operator is well-formed. If so, returns false;
9130/// otherwise, emits appropriate diagnostics and returns true.
9131bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00009132 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009133 "Expected an overloaded operator declaration");
9134
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009135 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9136
Mike Stump11289f42009-09-09 15:08:12 +00009137 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009138 // The allocation and deallocation functions, operator new,
9139 // operator new[], operator delete and operator delete[], are
9140 // described completely in 3.7.3. The attributes and restrictions
9141 // found in the rest of this subclause do not apply to them unless
9142 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00009143 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00009144 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00009145
Anders Carlsson22f443f2009-12-12 00:26:23 +00009146 if (Op == OO_New || Op == OO_Array_New)
9147 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009148
9149 // C++ [over.oper]p6:
9150 // An operator function shall either be a non-static member
9151 // function or be a non-member function and have at least one
9152 // parameter whose type is a class, a reference to a class, an
9153 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00009154 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9155 if (MethodDecl->isStatic())
9156 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009157 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009158 } else {
9159 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00009160 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9161 ParamEnd = FnDecl->param_end();
9162 Param != ParamEnd; ++Param) {
9163 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00009164 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9165 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009166 ClassOrEnumParam = true;
9167 break;
9168 }
9169 }
9170
Douglas Gregord69246b2008-11-17 16:14:12 +00009171 if (!ClassOrEnumParam)
9172 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009173 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009174 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009175 }
9176
9177 // C++ [over.oper]p8:
9178 // An operator function cannot have default arguments (8.3.6),
9179 // except where explicitly stated below.
9180 //
Mike Stump11289f42009-09-09 15:08:12 +00009181 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009182 // (C++ [over.call]p1).
9183 if (Op != OO_Call) {
9184 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9185 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009186 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00009187 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00009188 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009189 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009190 }
9191 }
9192
Douglas Gregor6cf08062008-11-10 13:38:07 +00009193 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9194 { false, false, false }
9195#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9196 , { Unary, Binary, MemberOnly }
9197#include "clang/Basic/OperatorKinds.def"
9198 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009199
Douglas Gregor6cf08062008-11-10 13:38:07 +00009200 bool CanBeUnaryOperator = OperatorUses[Op][0];
9201 bool CanBeBinaryOperator = OperatorUses[Op][1];
9202 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009203
9204 // C++ [over.oper]p8:
9205 // [...] Operator functions cannot have more or fewer parameters
9206 // than the number required for the corresponding operator, as
9207 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00009208 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00009209 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009210 if (Op != OO_Call &&
9211 ((NumParams == 1 && !CanBeUnaryOperator) ||
9212 (NumParams == 2 && !CanBeBinaryOperator) ||
9213 (NumParams < 1) || (NumParams > 2))) {
9214 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009215 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00009216 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009217 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00009218 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009219 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009220 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00009221 assert(CanBeBinaryOperator &&
9222 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009223 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009224 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009225
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009226 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009227 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009228 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009229
Douglas Gregord69246b2008-11-17 16:14:12 +00009230 // Overloaded operators other than operator() cannot be variadic.
9231 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00009232 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009233 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009234 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009235 }
9236
9237 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00009238 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9239 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009240 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009241 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009242 }
9243
9244 // C++ [over.inc]p1:
9245 // The user-defined function called operator++ implements the
9246 // prefix and postfix ++ operator. If this function is a member
9247 // function with no parameters, or a non-member function with one
9248 // parameter of class or enumeration type, it defines the prefix
9249 // increment operator ++ for objects of that type. If the function
9250 // is a member function with one parameter (which shall be of type
9251 // int) or a non-member function with two parameters (the second
9252 // of which shall be of type int), it defines the postfix
9253 // increment operator ++ for objects of that type.
9254 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9255 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9256 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00009257 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009258 ParamIsInt = BT->getKind() == BuiltinType::Int;
9259
Chris Lattner2b786902008-11-21 07:50:02 +00009260 if (!ParamIsInt)
9261 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00009262 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009263 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009264 }
9265
Douglas Gregord69246b2008-11-17 16:14:12 +00009266 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009267}
Chris Lattner3b024a32008-12-17 07:09:26 +00009268
Alexis Huntc88db062010-01-13 09:01:02 +00009269/// CheckLiteralOperatorDeclaration - Check whether the declaration
9270/// of this literal operator function is well-formed. If so, returns
9271/// false; otherwise, emits appropriate diagnostics and returns true.
9272bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9273 DeclContext *DC = FnDecl->getDeclContext();
9274 Decl::Kind Kind = DC->getDeclKind();
9275 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9276 Kind != Decl::LinkageSpec) {
9277 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9278 << FnDecl->getDeclName();
9279 return true;
9280 }
9281
9282 bool Valid = false;
9283
Alexis Hunt7dd26172010-04-07 23:11:06 +00009284 // template <char...> type operator "" name() is the only valid template
9285 // signature, and the only valid signature with no parameters.
9286 if (FnDecl->param_size() == 0) {
9287 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9288 // Must have only one template parameter
9289 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9290 if (Params->size() == 1) {
9291 NonTypeTemplateParmDecl *PmDecl =
9292 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00009293
Alexis Hunt7dd26172010-04-07 23:11:06 +00009294 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00009295 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9296 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9297 Valid = true;
9298 }
9299 }
9300 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00009301 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00009302 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9303
Alexis Huntc88db062010-01-13 09:01:02 +00009304 QualType T = (*Param)->getType();
9305
Alexis Hunt079a6f72010-04-07 22:57:35 +00009306 // unsigned long long int, long double, and any character type are allowed
9307 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00009308 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9309 Context.hasSameType(T, Context.LongDoubleTy) ||
9310 Context.hasSameType(T, Context.CharTy) ||
9311 Context.hasSameType(T, Context.WCharTy) ||
9312 Context.hasSameType(T, Context.Char16Ty) ||
9313 Context.hasSameType(T, Context.Char32Ty)) {
9314 if (++Param == FnDecl->param_end())
9315 Valid = true;
9316 goto FinishedParams;
9317 }
9318
Alexis Hunt079a6f72010-04-07 22:57:35 +00009319 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00009320 const PointerType *PT = T->getAs<PointerType>();
9321 if (!PT)
9322 goto FinishedParams;
9323 T = PT->getPointeeType();
9324 if (!T.isConstQualified())
9325 goto FinishedParams;
9326 T = T.getUnqualifiedType();
9327
9328 // Move on to the second parameter;
9329 ++Param;
9330
9331 // If there is no second parameter, the first must be a const char *
9332 if (Param == FnDecl->param_end()) {
9333 if (Context.hasSameType(T, Context.CharTy))
9334 Valid = true;
9335 goto FinishedParams;
9336 }
9337
9338 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9339 // are allowed as the first parameter to a two-parameter function
9340 if (!(Context.hasSameType(T, Context.CharTy) ||
9341 Context.hasSameType(T, Context.WCharTy) ||
9342 Context.hasSameType(T, Context.Char16Ty) ||
9343 Context.hasSameType(T, Context.Char32Ty)))
9344 goto FinishedParams;
9345
9346 // The second and final parameter must be an std::size_t
9347 T = (*Param)->getType().getUnqualifiedType();
9348 if (Context.hasSameType(T, Context.getSizeType()) &&
9349 ++Param == FnDecl->param_end())
9350 Valid = true;
9351 }
9352
9353 // FIXME: This diagnostic is absolutely terrible.
9354FinishedParams:
9355 if (!Valid) {
9356 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9357 << FnDecl->getDeclName();
9358 return true;
9359 }
9360
Douglas Gregor86325ad2011-08-30 22:40:35 +00009361 StringRef LiteralName
9362 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9363 if (LiteralName[0] != '_') {
9364 // C++0x [usrlit.suffix]p1:
9365 // Literal suffix identifiers that do not start with an underscore are
9366 // reserved for future standardization.
9367 bool IsHexFloat = true;
9368 if (LiteralName.size() > 1 &&
9369 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9370 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9371 if (!isdigit(LiteralName[I])) {
9372 IsHexFloat = false;
9373 break;
9374 }
9375 }
9376 }
9377
9378 if (IsHexFloat)
9379 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9380 << LiteralName;
9381 else
9382 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9383 }
9384
Alexis Huntc88db062010-01-13 09:01:02 +00009385 return false;
9386}
9387
Douglas Gregor07665a62009-01-05 19:45:36 +00009388/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9389/// linkage specification, including the language and (if present)
9390/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9391/// the location of the language string literal, which is provided
9392/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9393/// the '{' brace. Otherwise, this linkage specification does not
9394/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00009395Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9396 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009397 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +00009398 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00009399 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009400 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009401 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009402 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009403 Language = LinkageSpecDecl::lang_cxx;
9404 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00009405 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00009406 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00009407 }
Mike Stump11289f42009-09-09 15:08:12 +00009408
Chris Lattner438e5012008-12-17 07:13:27 +00009409 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00009410
Douglas Gregor07665a62009-01-05 19:45:36 +00009411 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009412 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009413 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00009414 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00009415 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00009416}
9417
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00009418/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00009419/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9420/// valid, it's the position of the closing '}' brace in a linkage
9421/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00009422Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009423 Decl *LinkageSpec,
9424 SourceLocation RBraceLoc) {
9425 if (LinkageSpec) {
9426 if (RBraceLoc.isValid()) {
9427 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9428 LSDecl->setRBraceLoc(RBraceLoc);
9429 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009430 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009431 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009432 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00009433}
9434
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009435/// \brief Perform semantic analysis for the variable declaration that
9436/// occurs within a C++ catch clause, returning the newly-created
9437/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009438VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00009439 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009440 SourceLocation StartLoc,
9441 SourceLocation Loc,
9442 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009443 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009444 QualType ExDeclType = TInfo->getType();
9445
Sebastian Redl54c04d42008-12-22 19:15:10 +00009446 // Arrays and functions decay.
9447 if (ExDeclType->isArrayType())
9448 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9449 else if (ExDeclType->isFunctionType())
9450 ExDeclType = Context.getPointerType(ExDeclType);
9451
9452 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9453 // The exception-declaration shall not denote a pointer or reference to an
9454 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00009455 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00009456 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009457 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00009458 Invalid = true;
9459 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009460
Douglas Gregor104ee002010-03-08 01:47:36 +00009461 // GCC allows catching pointers and references to incomplete types
9462 // as an extension; so do we, but we warn by default.
9463
Sebastian Redl54c04d42008-12-22 19:15:10 +00009464 QualType BaseType = ExDeclType;
9465 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00009466 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00009467 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009468 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009469 BaseType = Ptr->getPointeeType();
9470 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00009471 DK = diag::ext_catch_incomplete_ptr;
9472 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00009473 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00009474 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009475 BaseType = Ref->getPointeeType();
9476 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00009477 DK = diag::ext_catch_incomplete_ref;
9478 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009479 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00009480 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00009481 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9482 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00009483 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009484
Mike Stump11289f42009-09-09 15:08:12 +00009485 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009486 RequireNonAbstractType(Loc, ExDeclType,
9487 diag::err_abstract_type_in_decl,
9488 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00009489 Invalid = true;
9490
John McCall2ca705e2010-07-24 00:37:23 +00009491 // Only the non-fragile NeXT runtime currently supports C++ catches
9492 // of ObjC types, and no runtime supports catching ObjC types by value.
9493 if (!Invalid && getLangOptions().ObjC1) {
9494 QualType T = ExDeclType;
9495 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9496 T = RT->getPointeeType();
9497
9498 if (T->isObjCObjectType()) {
9499 Diag(Loc, diag::err_objc_object_catch);
9500 Invalid = true;
9501 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00009502 if (!getLangOptions().ObjCNonFragileABI)
9503 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00009504 }
9505 }
9506
Abramo Bagnaradff19302011-03-08 08:55:46 +00009507 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9508 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00009509 ExDecl->setExceptionVariable(true);
9510
Douglas Gregor750734c2011-07-06 18:14:43 +00009511 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +00009512 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00009513 // C++ [except.handle]p16:
9514 // The object declared in an exception-declaration or, if the
9515 // exception-declaration does not specify a name, a temporary (12.2) is
9516 // copy-initialized (8.5) from the exception object. [...]
9517 // The object is destroyed when the handler exits, after the destruction
9518 // of any automatic objects initialized within the handler.
9519 //
9520 // We just pretend to initialize the object with itself, then make sure
9521 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00009522 QualType initType = ExDeclType;
9523
9524 InitializedEntity entity =
9525 InitializedEntity::InitializeVariable(ExDecl);
9526 InitializationKind initKind =
9527 InitializationKind::CreateCopy(Loc, SourceLocation());
9528
9529 Expr *opaqueValue =
9530 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9531 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9532 ExprResult result = sequence.Perform(*this, entity, initKind,
9533 MultiExprArg(&opaqueValue, 1));
9534 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00009535 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00009536 else {
9537 // If the constructor used was non-trivial, set this as the
9538 // "initializer".
9539 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9540 if (!construct->getConstructor()->isTrivial()) {
9541 Expr *init = MaybeCreateExprWithCleanups(construct);
9542 ExDecl->setInit(init);
9543 }
9544
9545 // And make sure it's destructable.
9546 FinalizeVarWithDestructor(ExDecl, recordType);
9547 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00009548 }
9549 }
9550
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009551 if (Invalid)
9552 ExDecl->setInvalidDecl();
9553
9554 return ExDecl;
9555}
9556
9557/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9558/// handler.
John McCall48871652010-08-21 09:40:31 +00009559Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00009560 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00009561 bool Invalid = D.isInvalidType();
9562
9563 // Check for unexpanded parameter packs.
9564 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9565 UPPC_ExceptionType)) {
9566 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9567 D.getIdentifierLoc());
9568 Invalid = true;
9569 }
9570
Sebastian Redl54c04d42008-12-22 19:15:10 +00009571 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009572 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00009573 LookupOrdinaryName,
9574 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009575 // The scope should be freshly made just for us. There is just no way
9576 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00009577 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00009578 if (PrevDecl->isTemplateParameter()) {
9579 // Maybe we will complain about the shadowed template parameter.
9580 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009581 }
9582 }
9583
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009584 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009585 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9586 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009587 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009588 }
9589
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009590 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009591 D.getSourceRange().getBegin(),
9592 D.getIdentifierLoc(),
9593 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009594 if (Invalid)
9595 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009596
Sebastian Redl54c04d42008-12-22 19:15:10 +00009597 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009598 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009599 PushOnScopeChains(ExDecl, S);
9600 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009601 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009602
Douglas Gregor758a8692009-06-17 21:51:59 +00009603 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00009604 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009605}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009606
Abramo Bagnaraea947882011-03-08 16:41:52 +00009607Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00009608 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009609 Expr *AssertMessageExpr_,
9610 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00009611 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009612
Anders Carlsson54b26982009-03-14 00:33:21 +00009613 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9614 llvm::APSInt Value(32);
9615 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009616 Diag(StaticAssertLoc,
9617 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00009618 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00009619 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00009620 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009621
Anders Carlsson54b26982009-03-14 00:33:21 +00009622 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00009623 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00009624 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00009625 }
9626 }
Mike Stump11289f42009-09-09 15:08:12 +00009627
Douglas Gregoref68fee2010-12-15 23:55:21 +00009628 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9629 return 0;
9630
Abramo Bagnaraea947882011-03-08 16:41:52 +00009631 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9632 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00009633
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009634 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00009635 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009636}
Sebastian Redlf769df52009-03-24 22:27:57 +00009637
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009638/// \brief Perform semantic analysis of the given friend type declaration.
9639///
9640/// \returns A friend declaration that.
9641FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9642 TypeSourceInfo *TSInfo) {
9643 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9644
9645 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009646 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009647
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009648 if (!getLangOptions().CPlusPlus0x) {
9649 // C++03 [class.friend]p2:
9650 // An elaborated-type-specifier shall be used in a friend declaration
9651 // for a class.*
9652 //
9653 // * The class-key of the elaborated-type-specifier is required.
9654 if (!ActiveTemplateInstantiations.empty()) {
9655 // Do not complain about the form of friend template types during
9656 // template instantiation; we will already have complained when the
9657 // template was declared.
9658 } else if (!T->isElaboratedTypeSpecifier()) {
9659 // If we evaluated the type to a record type, suggest putting
9660 // a tag in front.
9661 if (const RecordType *RT = T->getAs<RecordType>()) {
9662 RecordDecl *RD = RT->getDecl();
9663
9664 std::string InsertionText = std::string(" ") + RD->getKindName();
9665
9666 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9667 << (unsigned) RD->getTagKind()
9668 << T
9669 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9670 InsertionText);
9671 } else {
9672 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9673 << T
9674 << SourceRange(FriendLoc, TypeRange.getEnd());
9675 }
9676 } else if (T->getAs<EnumType>()) {
9677 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009678 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009679 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009680 }
9681 }
9682
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009683 // C++0x [class.friend]p3:
9684 // If the type specifier in a friend declaration designates a (possibly
9685 // cv-qualified) class type, that class is declared as a friend; otherwise,
9686 // the friend declaration is ignored.
9687
9688 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9689 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009690
9691 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9692}
9693
John McCallace48cd2010-10-19 01:40:49 +00009694/// Handle a friend tag declaration where the scope specifier was
9695/// templated.
9696Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9697 unsigned TagSpec, SourceLocation TagLoc,
9698 CXXScopeSpec &SS,
9699 IdentifierInfo *Name, SourceLocation NameLoc,
9700 AttributeList *Attr,
9701 MultiTemplateParamsArg TempParamLists) {
9702 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9703
9704 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00009705 bool Invalid = false;
9706
9707 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00009708 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00009709 TempParamLists.get(),
9710 TempParamLists.size(),
9711 /*friend*/ true,
9712 isExplicitSpecialization,
9713 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00009714 if (TemplateParams->size() > 0) {
9715 // This is a declaration of a class template.
9716 if (Invalid)
9717 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009718
Eric Christopher6f228b52011-07-21 05:34:24 +00009719 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9720 SS, Name, NameLoc, Attr,
9721 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +00009722 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +00009723 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00009724 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00009725 } else {
9726 // The "template<>" header is extraneous.
9727 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9728 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9729 isExplicitSpecialization = true;
9730 }
9731 }
9732
9733 if (Invalid) return 0;
9734
9735 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9736
9737 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00009738 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00009739 if (TempParamLists.get()[I]->size()) {
9740 isAllExplicitSpecializations = false;
9741 break;
9742 }
9743 }
9744
9745 // FIXME: don't ignore attributes.
9746
9747 // If it's explicit specializations all the way down, just forget
9748 // about the template header and build an appropriate non-templated
9749 // friend. TODO: for source fidelity, remember the headers.
9750 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009751 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00009752 ElaboratedTypeKeyword Keyword
9753 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009754 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00009755 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00009756 if (T.isNull())
9757 return 0;
9758
9759 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9760 if (isa<DependentNameType>(T)) {
9761 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9762 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009763 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009764 TL.setNameLoc(NameLoc);
9765 } else {
9766 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9767 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00009768 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00009769 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9770 }
9771
9772 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9773 TSI, FriendLoc);
9774 Friend->setAccess(AS_public);
9775 CurContext->addDecl(Friend);
9776 return Friend;
9777 }
9778
9779 // Handle the case of a templated-scope friend class. e.g.
9780 // template <class T> class A<T>::B;
9781 // FIXME: we don't support these right now.
9782 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9783 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9784 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9785 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9786 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00009787 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00009788 TL.setNameLoc(NameLoc);
9789
9790 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9791 TSI, FriendLoc);
9792 Friend->setAccess(AS_public);
9793 Friend->setUnsupportedFriend(true);
9794 CurContext->addDecl(Friend);
9795 return Friend;
9796}
9797
9798
John McCall11083da2009-09-16 22:47:08 +00009799/// Handle a friend type declaration. This works in tandem with
9800/// ActOnTag.
9801///
9802/// Notes on friend class templates:
9803///
9804/// We generally treat friend class declarations as if they were
9805/// declaring a class. So, for example, the elaborated type specifier
9806/// in a friend declaration is required to obey the restrictions of a
9807/// class-head (i.e. no typedefs in the scope chain), template
9808/// parameters are required to match up with simple template-ids, &c.
9809/// However, unlike when declaring a template specialization, it's
9810/// okay to refer to a template specialization without an empty
9811/// template parameter declaration, e.g.
9812/// friend class A<T>::B<unsigned>;
9813/// We permit this as a special case; if there are any template
9814/// parameters present at all, require proper matching, i.e.
9815/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00009816Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00009817 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00009818 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00009819
9820 assert(DS.isFriendSpecified());
9821 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9822
John McCall11083da2009-09-16 22:47:08 +00009823 // Try to convert the decl specifier to a type. This works for
9824 // friend templates because ActOnTag never produces a ClassTemplateDecl
9825 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00009826 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00009827 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9828 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00009829 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00009830 return 0;
John McCall07e91c02009-08-06 02:15:43 +00009831
Douglas Gregor6c110f32010-12-16 01:14:37 +00009832 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9833 return 0;
9834
John McCall11083da2009-09-16 22:47:08 +00009835 // This is definitely an error in C++98. It's probably meant to
9836 // be forbidden in C++0x, too, but the specification is just
9837 // poorly written.
9838 //
9839 // The problem is with declarations like the following:
9840 // template <T> friend A<T>::foo;
9841 // where deciding whether a class C is a friend or not now hinges
9842 // on whether there exists an instantiation of A that causes
9843 // 'foo' to equal C. There are restrictions on class-heads
9844 // (which we declare (by fiat) elaborated friend declarations to
9845 // be) that makes this tractable.
9846 //
9847 // FIXME: handle "template <> friend class A<T>;", which
9848 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00009849 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00009850 Diag(Loc, diag::err_tagless_friend_type_template)
9851 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00009852 return 0;
John McCall11083da2009-09-16 22:47:08 +00009853 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009854
John McCallaa74a0c2009-08-28 07:59:38 +00009855 // C++98 [class.friend]p1: A friend of a class is a function
9856 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00009857 // This is fixed in DR77, which just barely didn't make the C++03
9858 // deadline. It's also a very silly restriction that seriously
9859 // affects inner classes and which nobody else seems to implement;
9860 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00009861 //
9862 // But note that we could warn about it: it's always useless to
9863 // friend one of your own members (it's not, however, worthless to
9864 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00009865
John McCall11083da2009-09-16 22:47:08 +00009866 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009867 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00009868 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009869 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00009870 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00009871 TSI,
John McCall11083da2009-09-16 22:47:08 +00009872 DS.getFriendSpecLoc());
9873 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009874 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9875
9876 if (!D)
John McCall48871652010-08-21 09:40:31 +00009877 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009878
John McCall11083da2009-09-16 22:47:08 +00009879 D->setAccess(AS_public);
9880 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00009881
John McCall48871652010-08-21 09:40:31 +00009882 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00009883}
9884
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00009885Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCallde3fd222010-10-12 23:13:28 +00009886 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00009887 const DeclSpec &DS = D.getDeclSpec();
9888
9889 assert(DS.isFriendSpecified());
9890 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9891
9892 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00009893 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +00009894
9895 // C++ [class.friend]p1
9896 // A friend of a class is a function or class....
9897 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00009898 // It *doesn't* see through dependent types, which is correct
9899 // according to [temp.arg.type]p3:
9900 // If a declaration acquires a function type through a
9901 // type dependent on a template-parameter and this causes
9902 // a declaration that does not use the syntactic form of a
9903 // function declarator to have a function type, the program
9904 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00009905 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +00009906 Diag(Loc, diag::err_unexpected_friend);
9907
9908 // It might be worthwhile to try to recover by creating an
9909 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00009910 return 0;
John McCall07e91c02009-08-06 02:15:43 +00009911 }
9912
9913 // C++ [namespace.memdef]p3
9914 // - If a friend declaration in a non-local class first declares a
9915 // class or function, the friend class or function is a member
9916 // of the innermost enclosing namespace.
9917 // - The name of the friend is not found by simple name lookup
9918 // until a matching declaration is provided in that namespace
9919 // scope (either before or after the class declaration granting
9920 // friendship).
9921 // - If a friend function is called, its name may be found by the
9922 // name lookup that considers functions from namespaces and
9923 // classes associated with the types of the function arguments.
9924 // - When looking for a prior declaration of a class or a function
9925 // declared as a friend, scopes outside the innermost enclosing
9926 // namespace scope are not considered.
9927
John McCallde3fd222010-10-12 23:13:28 +00009928 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009929 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9930 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00009931 assert(Name);
9932
Douglas Gregor6c110f32010-12-16 01:14:37 +00009933 // Check for unexpanded parameter packs.
9934 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9935 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9936 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9937 return 0;
9938
John McCall07e91c02009-08-06 02:15:43 +00009939 // The context we found the declaration in, or in which we should
9940 // create the declaration.
9941 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00009942 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009943 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00009944 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00009945
John McCallde3fd222010-10-12 23:13:28 +00009946 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00009947
John McCallde3fd222010-10-12 23:13:28 +00009948 // There are four cases here.
9949 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00009950 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00009951 // there as appropriate.
9952 // Recover from invalid scope qualifiers as if they just weren't there.
9953 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00009954 // C++0x [namespace.memdef]p3:
9955 // If the name in a friend declaration is neither qualified nor
9956 // a template-id and the declaration is a function or an
9957 // elaborated-type-specifier, the lookup to determine whether
9958 // the entity has been previously declared shall not consider
9959 // any scopes outside the innermost enclosing namespace.
9960 // C++0x [class.friend]p11:
9961 // If a friend declaration appears in a local class and the name
9962 // specified is an unqualified name, a prior declaration is
9963 // looked up without considering scopes that are outside the
9964 // innermost enclosing non-class scope. For a friend function
9965 // declaration, if there is no prior declaration, the program is
9966 // ill-formed.
9967 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00009968 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00009969
John McCallf7cfb222010-10-13 05:45:15 +00009970 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00009971 DC = CurContext;
9972 while (true) {
9973 // Skip class contexts. If someone can cite chapter and verse
9974 // for this behavior, that would be nice --- it's what GCC and
9975 // EDG do, and it seems like a reasonable intent, but the spec
9976 // really only says that checks for unqualified existing
9977 // declarations should stop at the nearest enclosing namespace,
9978 // not that they should only consider the nearest enclosing
9979 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00009980 while (DC->isRecord())
9981 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00009982
John McCall1f82f242009-11-18 22:49:29 +00009983 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00009984
9985 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00009986 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00009987 break;
John McCallf7cfb222010-10-13 05:45:15 +00009988
John McCallf4776592010-10-14 22:22:28 +00009989 if (isTemplateId) {
9990 if (isa<TranslationUnitDecl>(DC)) break;
9991 } else {
9992 if (DC->isFileContext()) break;
9993 }
John McCall07e91c02009-08-06 02:15:43 +00009994 DC = DC->getParent();
9995 }
9996
9997 // C++ [class.friend]p1: A friend of a class is a function or
9998 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00009999 // C++0x changes this for both friend types and functions.
10000 // Most C++ 98 compilers do seem to give an error here, so
10001 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +000010002 if (!Previous.empty() && DC->Equals(CurContext)
10003 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +000010004 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +000010005
John McCallccbc0322010-10-13 06:22:15 +000010006 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +000010007
Douglas Gregor16e65612011-10-10 01:11:59 +000010008 // C++ [class.friend]p6:
10009 // A function can be defined in a friend declaration of a class if and
10010 // only if the class is a non-local class (9.8), the function name is
10011 // unqualified, and the function has namespace scope.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010012 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010013 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10014 }
10015
John McCallde3fd222010-10-12 23:13:28 +000010016 // - There's a non-dependent scope specifier, in which case we
10017 // compute it and do a previous lookup there for a function
10018 // or function template.
10019 } else if (!SS.getScopeRep()->isDependent()) {
10020 DC = computeDeclContext(SS);
10021 if (!DC) return 0;
10022
10023 if (RequireCompleteDeclContext(SS, DC)) return 0;
10024
10025 LookupQualifiedName(Previous, DC);
10026
10027 // Ignore things found implicitly in the wrong scope.
10028 // TODO: better diagnostics for this case. Suggesting the right
10029 // qualified scope would be nice...
10030 LookupResult::Filter F = Previous.makeFilter();
10031 while (F.hasNext()) {
10032 NamedDecl *D = F.next();
10033 if (!DC->InEnclosingNamespaceSetOf(
10034 D->getDeclContext()->getRedeclContext()))
10035 F.erase();
10036 }
10037 F.done();
10038
10039 if (Previous.empty()) {
10040 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010041 Diag(Loc, diag::err_qualified_friend_not_found)
10042 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000010043 return 0;
10044 }
10045
10046 // C++ [class.friend]p1: A friend of a class is a function or
10047 // class that is not a member of the class . . .
Richard Smithc30493d2011-10-18 18:33:57 +000010048 if (DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCallde3fd222010-10-12 23:13:28 +000010049 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000010050
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010051 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010052 // C++ [class.friend]p6:
10053 // A function can be defined in a friend declaration of a class if and
10054 // only if the class is a non-local class (9.8), the function name is
10055 // unqualified, and the function has namespace scope.
10056 SemaDiagnosticBuilder DB
10057 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10058
10059 DB << SS.getScopeRep();
10060 if (DC->isFileContext())
10061 DB << FixItHint::CreateRemoval(SS.getRange());
10062 SS.clear();
10063 }
John McCallde3fd222010-10-12 23:13:28 +000010064
10065 // - There's a scope specifier that does not match any template
10066 // parameter lists, in which case we use some arbitrary context,
10067 // create a method or method template, and wait for instantiation.
10068 // - There's a scope specifier that does match some template
10069 // parameter lists, which we don't handle right now.
10070 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010071 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010072 // C++ [class.friend]p6:
10073 // A function can be defined in a friend declaration of a class if and
10074 // only if the class is a non-local class (9.8), the function name is
10075 // unqualified, and the function has namespace scope.
10076 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10077 << SS.getScopeRep();
10078 }
10079
John McCallde3fd222010-10-12 23:13:28 +000010080 DC = CurContext;
10081 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000010082 }
Douglas Gregor16e65612011-10-10 01:11:59 +000010083
John McCallf7cfb222010-10-13 05:45:15 +000010084 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000010085 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000010086 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10087 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10088 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000010089 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000010090 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10091 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000010092 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010093 }
John McCall07e91c02009-08-06 02:15:43 +000010094 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010095
Francois Pichet00c7e6c2011-08-14 03:52:19 +000010096 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010097 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10098 move(TemplateParams), AddToScope);
John McCall48871652010-08-21 09:40:31 +000010099 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000010100
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010101 assert(ND->getDeclContext() == DC);
10102 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000010103
John McCall759e32b2009-08-31 22:39:49 +000010104 // Add the function declaration to the appropriate lookup tables,
10105 // adjusting the redeclarations list as necessary. We don't
10106 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000010107 //
John McCall759e32b2009-08-31 22:39:49 +000010108 // Also update the scope-based lookup if the target context's
10109 // lookup context is in lexical scope.
10110 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010111 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010112 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010113 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010114 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010115 }
John McCallaa74a0c2009-08-28 07:59:38 +000010116
10117 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010118 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000010119 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000010120 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000010121 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000010122
John McCallde3fd222010-10-12 23:13:28 +000010123 if (ND->isInvalidDecl())
10124 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +000010125 else {
10126 FunctionDecl *FD;
10127 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10128 FD = FTD->getTemplatedDecl();
10129 else
10130 FD = cast<FunctionDecl>(ND);
10131
10132 // Mark templated-scope function declarations as unsupported.
10133 if (FD->getNumTemplateParameterLists())
10134 FrD->setUnsupportedFriend(true);
10135 }
John McCallde3fd222010-10-12 23:13:28 +000010136
John McCall48871652010-08-21 09:40:31 +000010137 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000010138}
10139
John McCall48871652010-08-21 09:40:31 +000010140void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10141 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000010142
Sebastian Redlf769df52009-03-24 22:27:57 +000010143 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10144 if (!Fn) {
10145 Diag(DelLoc, diag::err_deleted_non_function);
10146 return;
10147 }
10148 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
10149 Diag(DelLoc, diag::err_deleted_decl_not_first);
10150 Diag(Prev->getLocation(), diag::note_previous_declaration);
10151 // If the declaration wasn't the first, we delete the function anyway for
10152 // recovery.
10153 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010154 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000010155}
Sebastian Redl4c018662009-04-27 21:33:24 +000010156
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010157void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10158 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10159
10160 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000010161 if (MD->getParent()->isDependentType()) {
10162 MD->setDefaulted();
10163 MD->setExplicitlyDefaulted();
10164 return;
10165 }
10166
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010167 CXXSpecialMember Member = getSpecialMember(MD);
10168 if (Member == CXXInvalid) {
10169 Diag(DefaultLoc, diag::err_default_special_members);
10170 return;
10171 }
10172
10173 MD->setDefaulted();
10174 MD->setExplicitlyDefaulted();
10175
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010176 // If this definition appears within the record, do the checking when
10177 // the record is complete.
10178 const FunctionDecl *Primary = MD;
10179 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10180 // Find the uninstantiated declaration that actually had the '= default'
10181 // on it.
10182 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10183
10184 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010185 return;
10186
10187 switch (Member) {
10188 case CXXDefaultConstructor: {
10189 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10190 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010191 if (!CD->isInvalidDecl())
10192 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10193 break;
10194 }
10195
10196 case CXXCopyConstructor: {
10197 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10198 CheckExplicitlyDefaultedCopyConstructor(CD);
10199 if (!CD->isInvalidDecl())
10200 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010201 break;
10202 }
Alexis Huntf91729462011-05-12 22:46:25 +000010203
Alexis Huntc9a55732011-05-14 05:23:28 +000010204 case CXXCopyAssignment: {
10205 CheckExplicitlyDefaultedCopyAssignment(MD);
10206 if (!MD->isInvalidDecl())
10207 DefineImplicitCopyAssignment(DefaultLoc, MD);
10208 break;
10209 }
10210
Alexis Huntf91729462011-05-12 22:46:25 +000010211 case CXXDestructor: {
10212 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10213 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010214 if (!DD->isInvalidDecl())
10215 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +000010216 break;
10217 }
10218
Sebastian Redl22653ba2011-08-30 19:58:05 +000010219 case CXXMoveConstructor: {
10220 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10221 CheckExplicitlyDefaultedMoveConstructor(CD);
10222 if (!CD->isInvalidDecl())
10223 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +000010224 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010225 }
Alexis Hunt119c10e2011-05-25 23:16:36 +000010226
Sebastian Redl22653ba2011-08-30 19:58:05 +000010227 case CXXMoveAssignment: {
10228 CheckExplicitlyDefaultedMoveAssignment(MD);
10229 if (!MD->isInvalidDecl())
10230 DefineImplicitMoveAssignment(DefaultLoc, MD);
10231 break;
10232 }
10233
10234 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000010235 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010236 }
10237 } else {
10238 Diag(DefaultLoc, diag::err_default_special_members);
10239 }
10240}
10241
Sebastian Redl4c018662009-04-27 21:33:24 +000010242static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000010243 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000010244 Stmt *SubStmt = *CI;
10245 if (!SubStmt)
10246 continue;
10247 if (isa<ReturnStmt>(SubStmt))
10248 Self.Diag(SubStmt->getSourceRange().getBegin(),
10249 diag::err_return_in_constructor_handler);
10250 if (!isa<Expr>(SubStmt))
10251 SearchForReturnInStmt(Self, SubStmt);
10252 }
10253}
10254
10255void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10256 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10257 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10258 SearchForReturnInStmt(*this, Handler);
10259 }
10260}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010261
Mike Stump11289f42009-09-09 15:08:12 +000010262bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010263 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000010264 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10265 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010266
Chandler Carruth284bb2e2010-02-15 11:53:20 +000010267 if (Context.hasSameType(NewTy, OldTy) ||
10268 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010269 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010270
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010271 // Check if the return types are covariant
10272 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000010273
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010274 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010275 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10276 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010277 NewClassTy = NewPT->getPointeeType();
10278 OldClassTy = OldPT->getPointeeType();
10279 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010280 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10281 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10282 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10283 NewClassTy = NewRT->getPointeeType();
10284 OldClassTy = OldRT->getPointeeType();
10285 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010286 }
10287 }
Mike Stump11289f42009-09-09 15:08:12 +000010288
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010289 // The return types aren't either both pointers or references to a class type.
10290 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000010291 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010292 diag::err_different_return_type_for_overriding_virtual_function)
10293 << New->getDeclName() << NewTy << OldTy;
10294 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000010295
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010296 return true;
10297 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010298
Anders Carlssone60365b2009-12-31 18:34:24 +000010299 // C++ [class.virtual]p6:
10300 // If the return type of D::f differs from the return type of B::f, the
10301 // class type in the return type of D::f shall be complete at the point of
10302 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010303 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10304 if (!RT->isBeingDefined() &&
10305 RequireCompleteType(New->getLocation(), NewClassTy,
10306 PDiag(diag::err_covariant_return_incomplete)
10307 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000010308 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010309 }
Anders Carlssone60365b2009-12-31 18:34:24 +000010310
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000010311 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010312 // Check if the new class derives from the old class.
10313 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10314 Diag(New->getLocation(),
10315 diag::err_covariant_return_not_derived)
10316 << New->getDeclName() << NewTy << OldTy;
10317 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10318 return true;
10319 }
Mike Stump11289f42009-09-09 15:08:12 +000010320
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010321 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000010322 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000010323 diag::err_covariant_return_inaccessible_base,
10324 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10325 // FIXME: Should this point to the return type?
10326 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000010327 // FIXME: this note won't trigger for delayed access control
10328 // diagnostics, and it's impossible to get an undelayed error
10329 // here from access control during the original parse because
10330 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010331 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10332 return true;
10333 }
10334 }
Mike Stump11289f42009-09-09 15:08:12 +000010335
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010336 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010337 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010338 Diag(New->getLocation(),
10339 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010340 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010341 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10342 return true;
10343 };
Mike Stump11289f42009-09-09 15:08:12 +000010344
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010345
10346 // The new class type must have the same or less qualifiers as the old type.
10347 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10348 Diag(New->getLocation(),
10349 diag::err_covariant_return_type_class_type_more_qualified)
10350 << New->getDeclName() << NewTy << OldTy;
10351 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10352 return true;
10353 };
Mike Stump11289f42009-09-09 15:08:12 +000010354
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010355 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010356}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010357
Douglas Gregor21920e372009-12-01 17:24:26 +000010358/// \brief Mark the given method pure.
10359///
10360/// \param Method the method to be marked pure.
10361///
10362/// \param InitRange the source range that covers the "0" initializer.
10363bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010364 SourceLocation EndLoc = InitRange.getEnd();
10365 if (EndLoc.isValid())
10366 Method->setRangeEnd(EndLoc);
10367
Douglas Gregor21920e372009-12-01 17:24:26 +000010368 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10369 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000010370 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010371 }
Douglas Gregor21920e372009-12-01 17:24:26 +000010372
10373 if (!Method->isInvalidDecl())
10374 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10375 << Method->getDeclName() << InitRange;
10376 return true;
10377}
10378
John McCall1f4ee7b2009-12-19 09:28:58 +000010379/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10380/// an initializer for the out-of-line declaration 'Dcl'. The scope
10381/// is a fresh scope pushed for just this purpose.
10382///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010383/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10384/// static data member of class X, names should be looked up in the scope of
10385/// class X.
John McCall48871652010-08-21 09:40:31 +000010386void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010387 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010388 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010389
John McCall1f4ee7b2009-12-19 09:28:58 +000010390 // We should only get called for declarations with scope specifiers, like:
10391 // int foo::bar;
10392 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010393 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010394}
10395
10396/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000010397/// initializer for the out-of-line declaration 'D'.
10398void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010399 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010400 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010401
John McCall1f4ee7b2009-12-19 09:28:58 +000010402 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010403 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010404}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010405
10406/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10407/// C++ if/switch/while/for statement.
10408/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000010409DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010410 // C++ 6.4p2:
10411 // The declarator shall not specify a function or an array.
10412 // The type-specifier-seq shall not contain typedef and shall not declare a
10413 // new class or enumeration.
10414 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10415 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010416
10417 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010418 if (!Dcl)
10419 return true;
10420
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010421 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10422 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010423 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010424 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010425 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010426
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010427 return Dcl;
10428}
Anders Carlssonf98849e2009-12-02 17:15:43 +000010429
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010430void Sema::LoadExternalVTableUses() {
10431 if (!ExternalSource)
10432 return;
10433
10434 SmallVector<ExternalVTableUse, 4> VTables;
10435 ExternalSource->ReadUsedVTables(VTables);
10436 SmallVector<VTableUse, 4> NewUses;
10437 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10438 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10439 = VTablesUsed.find(VTables[I].Record);
10440 // Even if a definition wasn't required before, it may be required now.
10441 if (Pos != VTablesUsed.end()) {
10442 if (!Pos->second && VTables[I].DefinitionRequired)
10443 Pos->second = true;
10444 continue;
10445 }
10446
10447 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10448 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10449 }
10450
10451 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10452}
10453
Douglas Gregor88d292c2010-05-13 16:44:06 +000010454void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10455 bool DefinitionRequired) {
10456 // Ignore any vtable uses in unevaluated operands or for classes that do
10457 // not have a vtable.
10458 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10459 CurContext->isDependentContext() ||
10460 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +000010461 return;
10462
Douglas Gregor88d292c2010-05-13 16:44:06 +000010463 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010464 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010465 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10466 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10467 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10468 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000010469 // If we already had an entry, check to see if we are promoting this vtable
10470 // to required a definition. If so, we need to reappend to the VTableUses
10471 // list, since we may have already processed the first entry.
10472 if (DefinitionRequired && !Pos.first->second) {
10473 Pos.first->second = true;
10474 } else {
10475 // Otherwise, we can early exit.
10476 return;
10477 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010478 }
10479
10480 // Local classes need to have their virtual members marked
10481 // immediately. For all other classes, we mark their virtual members
10482 // at the end of the translation unit.
10483 if (Class->isLocalClass())
10484 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000010485 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000010486 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000010487}
10488
Douglas Gregor88d292c2010-05-13 16:44:06 +000010489bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010490 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010491 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000010492 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000010493
Douglas Gregor88d292c2010-05-13 16:44:06 +000010494 // Note: The VTableUses vector could grow as a result of marking
10495 // the members of a class as "used", so we check the size each
10496 // time through the loop and prefer indices (with are stable) to
10497 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000010498 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010499 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000010500 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010501 if (!Class)
10502 continue;
10503
10504 SourceLocation Loc = VTableUses[I].second;
10505
10506 // If this class has a key function, but that key function is
10507 // defined in another translation unit, we don't need to emit the
10508 // vtable even though we're using it.
10509 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010510 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000010511 switch (KeyFunction->getTemplateSpecializationKind()) {
10512 case TSK_Undeclared:
10513 case TSK_ExplicitSpecialization:
10514 case TSK_ExplicitInstantiationDeclaration:
10515 // The key function is in another translation unit.
10516 continue;
10517
10518 case TSK_ExplicitInstantiationDefinition:
10519 case TSK_ImplicitInstantiation:
10520 // We will be instantiating the key function.
10521 break;
10522 }
10523 } else if (!KeyFunction) {
10524 // If we have a class with no key function that is the subject
10525 // of an explicit instantiation declaration, suppress the
10526 // vtable; it will live with the explicit instantiation
10527 // definition.
10528 bool IsExplicitInstantiationDeclaration
10529 = Class->getTemplateSpecializationKind()
10530 == TSK_ExplicitInstantiationDeclaration;
10531 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10532 REnd = Class->redecls_end();
10533 R != REnd; ++R) {
10534 TemplateSpecializationKind TSK
10535 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10536 if (TSK == TSK_ExplicitInstantiationDeclaration)
10537 IsExplicitInstantiationDeclaration = true;
10538 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10539 IsExplicitInstantiationDeclaration = false;
10540 break;
10541 }
10542 }
10543
10544 if (IsExplicitInstantiationDeclaration)
10545 continue;
10546 }
10547
10548 // Mark all of the virtual members of this class as referenced, so
10549 // that we can build a vtable. Then, tell the AST consumer that a
10550 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000010551 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010552 MarkVirtualMembersReferenced(Loc, Class);
10553 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10554 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10555
10556 // Optionally warn if we're emitting a weak vtable.
10557 if (Class->getLinkage() == ExternalLinkage &&
10558 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000010559 const FunctionDecl *KeyFunctionDef = 0;
10560 if (!KeyFunction ||
10561 (KeyFunction->hasBody(KeyFunctionDef) &&
10562 KeyFunctionDef->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +000010563 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10564 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000010565 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010566 VTableUses.clear();
10567
Douglas Gregor97509692011-04-22 22:25:37 +000010568 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000010569}
Anders Carlsson82fccd02009-12-07 08:24:59 +000010570
Rafael Espindola5b334082010-03-26 00:36:59 +000010571void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10572 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +000010573 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10574 e = RD->method_end(); i != e; ++i) {
10575 CXXMethodDecl *MD = *i;
10576
10577 // C++ [basic.def.odr]p2:
10578 // [...] A virtual member function is used if it is not pure. [...]
10579 if (MD->isVirtual() && !MD->isPure())
10580 MarkDeclarationReferenced(Loc, MD);
10581 }
Rafael Espindola5b334082010-03-26 00:36:59 +000010582
10583 // Only classes that have virtual bases need a VTT.
10584 if (RD->getNumVBases() == 0)
10585 return;
10586
10587 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10588 e = RD->bases_end(); i != e; ++i) {
10589 const CXXRecordDecl *Base =
10590 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000010591 if (Base->getNumVBases() == 0)
10592 continue;
10593 MarkVirtualMembersReferenced(Loc, Base);
10594 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000010595}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010596
10597/// SetIvarInitializers - This routine builds initialization ASTs for the
10598/// Objective-C implementation whose ivars need be initialized.
10599void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10600 if (!getLangOptions().CPlusPlus)
10601 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000010602 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010603 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010604 CollectIvarsToConstructOrDestruct(OID, ivars);
10605 if (ivars.empty())
10606 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010607 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010608 for (unsigned i = 0; i < ivars.size(); i++) {
10609 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000010610 if (Field->isInvalidDecl())
10611 continue;
10612
Alexis Hunt1d792652011-01-08 20:30:50 +000010613 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010614 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10615 InitializationKind InitKind =
10616 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10617
10618 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +000010619 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +000010620 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +000010621 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010622 // Note, MemberInit could actually come back empty if no initialization
10623 // is required (e.g., because it would call a trivial default constructor)
10624 if (!MemberInit.get() || MemberInit.isInvalid())
10625 continue;
John McCallacf0ee52010-10-08 02:01:28 +000010626
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010627 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000010628 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10629 SourceLocation(),
10630 MemberInit.takeAs<Expr>(),
10631 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010632 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000010633
10634 // Be sure that the destructor is accessible and is marked as referenced.
10635 if (const RecordType *RecordTy
10636 = Context.getBaseElementType(Field->getType())
10637 ->getAs<RecordType>()) {
10638 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000010639 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +000010640 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10641 CheckDestructorAccess(Field->getLocation(), Destructor,
10642 PDiag(diag::err_access_dtor_ivar)
10643 << Context.getBaseElementType(Field->getType()));
10644 }
10645 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010646 }
10647 ObjCImplementation->setIvarInitializers(Context,
10648 AllToInit.data(), AllToInit.size());
10649 }
10650}
Alexis Hunt6118d662011-05-04 05:57:24 +000010651
Alexis Hunt27a761d2011-05-04 23:29:54 +000010652static
10653void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10654 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10655 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10656 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10657 Sema &S) {
10658 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10659 CE = Current.end();
10660 if (Ctor->isInvalidDecl())
10661 return;
10662
10663 const FunctionDecl *FNTarget = 0;
10664 CXXConstructorDecl *Target;
10665
10666 // We ignore the result here since if we don't have a body, Target will be
10667 // null below.
10668 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10669 Target
10670= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10671
10672 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10673 // Avoid dereferencing a null pointer here.
10674 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10675
10676 if (!Current.insert(Canonical))
10677 return;
10678
10679 // We know that beyond here, we aren't chaining into a cycle.
10680 if (!Target || !Target->isDelegatingConstructor() ||
10681 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10682 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10683 Valid.insert(*CI);
10684 Current.clear();
10685 // We've hit a cycle.
10686 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10687 Current.count(TCanonical)) {
10688 // If we haven't diagnosed this cycle yet, do so now.
10689 if (!Invalid.count(TCanonical)) {
10690 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000010691 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000010692 << Ctor;
10693
10694 // Don't add a note for a function delegating directo to itself.
10695 if (TCanonical != Canonical)
10696 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10697
10698 CXXConstructorDecl *C = Target;
10699 while (C->getCanonicalDecl() != Canonical) {
10700 (void)C->getTargetConstructor()->hasBody(FNTarget);
10701 assert(FNTarget && "Ctor cycle through bodiless function");
10702
10703 C
10704 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10705 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10706 }
10707 }
10708
10709 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10710 Invalid.insert(*CI);
10711 Current.clear();
10712 } else {
10713 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10714 }
10715}
10716
10717
Alexis Hunt6118d662011-05-04 05:57:24 +000010718void Sema::CheckDelegatingCtorCycles() {
10719 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10720
Alexis Hunt27a761d2011-05-04 23:29:54 +000010721 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10722 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000010723
Douglas Gregorbae31202011-07-27 21:57:17 +000010724 for (DelegatingCtorDeclsType::iterator
10725 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000010726 E = DelegatingCtorDecls.end();
10727 I != E; ++I) {
10728 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +000010729 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000010730
10731 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10732 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000010733}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010734
10735/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10736Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10737 // Implicitly declared functions (e.g. copy constructors) are
10738 // __host__ __device__
10739 if (D->isImplicit())
10740 return CFT_HostDevice;
10741
10742 if (D->hasAttr<CUDAGlobalAttr>())
10743 return CFT_Global;
10744
10745 if (D->hasAttr<CUDADeviceAttr>()) {
10746 if (D->hasAttr<CUDAHostAttr>())
10747 return CFT_HostDevice;
10748 else
10749 return CFT_Device;
10750 }
10751
10752 return CFT_Host;
10753}
10754
10755bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10756 CUDAFunctionTarget CalleeTarget) {
10757 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10758 // Callable from the device only."
10759 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10760 return true;
10761
10762 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10763 // Callable from the host only."
10764 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10765 // Callable from the host only."
10766 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10767 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10768 return true;
10769
10770 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10771 return true;
10772
10773 return false;
10774}