blob: 539ed0eac56526b5ad8651bc15c2f9428f46864e [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000027#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000028#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000029#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000030#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000031#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000032#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000036#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000037#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000039#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000040#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000041
42using namespace clang;
43
Chris Lattner8123a952008-04-10 02:22:51 +000044//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
Chris Lattner9e979552008-04-12 23:52:44 +000048namespace {
49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50 /// the default argument of a parameter to determine whether it
51 /// contains any ill-formed subexpressions. For example, this will
52 /// diagnose the use of local variables or parameters within the
53 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000054 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000055 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000056 Expr *DefaultArg;
57 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 public:
Mike Stump1eb44332009-09-09 15:08:12 +000060 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000061 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 bool VisitExpr(Expr *Node);
64 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000065 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000066 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000067 };
Chris Lattner8123a952008-04-10 02:22:51 +000068
Chris Lattner9e979552008-04-12 23:52:44 +000069 /// VisitExpr - Visit all of the children of this expression.
70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000072 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000073 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000074 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000075 }
76
Chris Lattner9e979552008-04-12 23:52:44 +000077 /// VisitDeclRefExpr - Visit a reference to a declaration, to
78 /// determine whether this declaration can be used in the default
79 /// argument expression.
80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000081 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000082 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83 // C++ [dcl.fct.default]p9
84 // Default arguments are evaluated each time the function is
85 // called. The order of evaluation of function arguments is
86 // unspecified. Consequently, parameters of a function shall not
87 // be used in default argument expressions, even if they are not
88 // evaluated. Parameters of a function declared before a default
89 // argument expression are in scope and can hide namespace and
90 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000091 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000094 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000095 // C++ [dcl.fct.default]p7
96 // Local variables shall not be used in default argument
97 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000098 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000099 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000101 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103
Douglas Gregor3996f232008-11-04 13:41:56 +0000104 return false;
105 }
Chris Lattner9e979552008-04-12 23:52:44 +0000106
Douglas Gregor796da182008-11-04 14:32:21 +0000107 /// VisitCXXThisExpr - Visit a C++ "this" expression.
108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109 // C++ [dcl.fct.default]p8:
110 // The keyword this shall not be used in a default argument of a
111 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000112 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000113 diag::err_param_default_argument_references_this)
114 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000115 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000116
117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118 // C++11 [expr.lambda.prim]p13:
119 // A lambda-expression appearing in a default argument shall not
120 // implicitly or explicitly capture any entity.
121 if (Lambda->capture_begin() == Lambda->capture_end())
122 return false;
123
124 return S->Diag(Lambda->getLocStart(),
125 diag::err_lambda_capture_default_arg);
126 }
Chris Lattner8123a952008-04-10 02:22:51 +0000127}
128
Richard Smithe6975e92012-04-17 00:58:00 +0000129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000131 // If we have an MSAny spec already, don't bother.
132 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000133 return;
134
135 const FunctionProtoType *Proto
136 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138 if (!Proto)
139 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000140
141 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000144 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000145 ClearExceptions();
146 ComputedEST = EST;
147 return;
148 }
149
Richard Smith7a614d82011-06-11 17:19:42 +0000150 // FIXME: If the call to this decl is using any of its default arguments, we
151 // need to search them for potentially-throwing calls.
152
Sean Hunt001cad92011-05-10 00:49:42 +0000153 // If this function has a basic noexcept, it doesn't affect the outcome.
154 if (EST == EST_BasicNoexcept)
155 return;
156
157 // If we have a throw-all spec at this point, ignore the function.
158 if (ComputedEST == EST_None)
159 return;
160
161 // If we're still at noexcept(true) and there's a nothrow() callee,
162 // change to that specification.
163 if (EST == EST_DynamicNone) {
164 if (ComputedEST == EST_BasicNoexcept)
165 ComputedEST = EST_DynamicNone;
166 return;
167 }
168
169 // Check out noexcept specs.
170 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000171 FunctionProtoType::NoexceptResult NR =
172 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000173 assert(NR != FunctionProtoType::NR_NoNoexcept &&
174 "Must have noexcept result for EST_ComputedNoexcept.");
175 assert(NR != FunctionProtoType::NR_Dependent &&
176 "Should not generate implicit declarations for dependent cases, "
177 "and don't know how to handle them anyway.");
178
179 // noexcept(false) -> no spec on the new function
180 if (NR == FunctionProtoType::NR_Throw) {
181 ClearExceptions();
182 ComputedEST = EST_None;
183 }
184 // noexcept(true) won't change anything either.
185 return;
186 }
187
188 assert(EST == EST_Dynamic && "EST case not considered earlier.");
189 assert(ComputedEST != EST_None &&
190 "Shouldn't collect exceptions when throw-all is guaranteed.");
191 ComputedEST = EST_Dynamic;
192 // Record the exceptions in this function's exception specification.
193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194 EEnd = Proto->exception_end();
195 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000197 Exceptions.push_back(*E);
198}
199
Richard Smith7a614d82011-06-11 17:19:42 +0000200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000201 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000202 return;
203
204 // FIXME:
205 //
206 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000207 // [An] implicit exception-specification specifies the type-id T if and
208 // only if T is allowed by the exception-specification of a function directly
209 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000210 // function it directly invokes allows all exceptions, and f shall allow no
211 // exceptions if every function it directly invokes allows no exceptions.
212 //
213 // Note in particular that if an implicit exception-specification is generated
214 // for a function containing a throw-expression, that specification can still
215 // be noexcept(true).
216 //
217 // Note also that 'directly invoked' is not defined in the standard, and there
218 // is no indication that we should only consider potentially-evaluated calls.
219 //
220 // Ultimately we should implement the intent of the standard: the exception
221 // specification should be the set of exceptions which can be thrown by the
222 // implicit definition. For now, we assume that any non-nothrow expression can
223 // throw any exception.
224
Richard Smithe6975e92012-04-17 00:58:00 +0000225 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000226 ComputedEST = EST_None;
227}
228
Anders Carlssoned961f92009-08-25 02:29:20 +0000229bool
John McCall9ae2f072010-08-23 23:25:46 +0000230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000231 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000232 if (RequireCompleteType(Param->getLocation(), Param->getType(),
233 diag::err_typecheck_decl_incomplete_type)) {
234 Param->setInvalidDecl();
235 return true;
236 }
237
Anders Carlssoned961f92009-08-25 02:29:20 +0000238 // C++ [dcl.fct.default]p5
239 // A default argument expression is implicitly converted (clause
240 // 4) to the parameter type. The default argument expression has
241 // the same semantic constraints as the initializer expression in
242 // a declaration of a variable of the parameter type, using the
243 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000250 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000251 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000252 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000253 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000254
John McCallb4eb64d2010-10-08 02:01:28 +0000255 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000256 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
271 }
272
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000274}
275
Chris Lattner8123a952008-04-10 02:22:51 +0000276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000279void
John McCalld226f652010-08-21 09:40:31 +0000280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000281 Expr *DefaultArg) {
282 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000283 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
John McCalld226f652010-08-21 09:40:31 +0000285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000286 UnparsedDefaultArgLocs.erase(Param);
287
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000289 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000292 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293 return;
294 }
295
Douglas Gregor6f526752010-12-16 08:48:57 +0000296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
299 return;
300 }
301
Anders Carlsson66e30672009-08-25 01:02:06 +0000302 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000305 Param->setInvalidDecl();
306 return;
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
John McCall9ae2f072010-08-23 23:25:46 +0000309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000310}
311
Douglas Gregor61366e92008-12-24 00:01:03 +0000312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000319 if (!param)
320 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000321
John McCalld226f652010-08-21 09:40:31 +0000322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000323 if (Param)
324 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Anders Carlsson5e300d12009-06-12 16:51:40 +0000326 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000327}
328
Douglas Gregor72b505b2008-12-16 21:30:33 +0000329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000332 if (!param)
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
John McCalld226f652010-08-21 09:40:31 +0000335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Anders Carlsson5e300d12009-06-12 16:51:40 +0000339 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000340}
341
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000356 DeclaratorChunk &chunk = D.getTypeObject(i);
357 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 if (Param->hasUnparsedDefaultArg()) {
362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365 delete Toks;
366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000367 } else if (Param->getDefaultArg()) {
368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369 << Param->getDefaultArg()->getSourceRange();
370 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000371 }
372 }
373 }
374 }
375}
376
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377// MergeCXXFunctionDecl - Merge two declarations of the same C++
378// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000379// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 bool Invalid = false;
384
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 // For non-template functions, default arguments can be added in
387 // later declarations of a function in the same
388 // scope. Declarations in different scopes have completely
389 // distinct sets of default arguments. That is, declarations in
390 // inner scopes do not acquire default arguments from
391 // declarations in outer scopes, and vice versa. In a given
392 // function declaration, all parameters subsequent to a
393 // parameter with a default argument shall have default
394 // arguments supplied in this or previous declarations. A
395 // default argument shall not be redefined by a later
396 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000397 //
398 // C++ [dcl.fct.default]p6:
399 // Except for member functions of class templates, the default arguments
400 // in a member function definition that appears outside of the class
401 // definition are added to the set of default arguments provided by the
402 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404 ParmVarDecl *OldParam = Old->getParamDecl(p);
405 ParmVarDecl *NewParam = New->getParamDecl(p);
406
James Molloy9cda03f2012-03-13 08:55:35 +0000407 bool OldParamHasDfl = OldParam->hasDefaultArg();
408 bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410 NamedDecl *ND = Old;
411 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412 // Ignore default parameters of old decl if they are not in
413 // the same scope.
414 OldParamHasDfl = false;
415
416 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000417
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 unsigned DiagDefaultParamID =
419 diag::err_param_default_argument_redefinition;
420
421 // MSVC accepts that default parameters be redefined for member functions
422 // of template class. The new default parameter's value is ignored.
423 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000424 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000427 // Merge the old default argument into the new parameter.
428 NewParam->setHasInheritedDefaultArg();
429 if (OldParam->hasUninstantiatedDefaultArg())
430 NewParam->setUninstantiatedDefaultArg(
431 OldParam->getUninstantiatedDefaultArg());
432 else
433 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000435 Invalid = false;
436 }
437 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438
Francois Pichet8cf90492011-04-10 04:58:30 +0000439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440 // hint here. Alternatively, we could walk the type-source information
441 // for NewParam to find the last source location in the type... but it
442 // isn't worth the effort right now. This is the kind of test case that
443 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000444 // int f(int);
445 // void g(int (*fp)(int) = f);
446 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000447 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000448 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449
450 // Look for the function declaration where the default argument was
451 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000452 for (FunctionDecl *Older = Old->getPreviousDecl();
453 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000454 if (!Older->getParamDecl(p)->hasDefaultArg())
455 break;
456
457 OldParam = Older->getParamDecl(p);
458 }
459
460 Diag(OldParam->getLocation(), diag::note_previous_definition)
461 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000462 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000463 // Merge the old default argument into the new parameter.
464 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000465 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000466 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000467 if (OldParam->hasUninstantiatedDefaultArg())
468 NewParam->setUninstantiatedDefaultArg(
469 OldParam->getUninstantiatedDefaultArg());
470 else
John McCall3d6c1782010-05-04 01:53:42 +0000471 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000472 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000473 if (New->getDescribedFunctionTemplate()) {
474 // Paragraph 4, quoted above, only applies to non-template functions.
475 Diag(NewParam->getLocation(),
476 diag::err_param_default_argument_template_redecl)
477 << NewParam->getDefaultArgRange();
478 Diag(Old->getLocation(), diag::note_template_prev_declaration)
479 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000480 } else if (New->getTemplateSpecializationKind()
481 != TSK_ImplicitInstantiation &&
482 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483 // C++ [temp.expr.spec]p21:
484 // Default function arguments shall not be specified in a declaration
485 // or a definition for one of the following explicit specializations:
486 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000487 // - the explicit specialization of a member function template;
488 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000489 // template where the class template specialization to which the
490 // member function specialization belongs is implicitly
491 // instantiated.
492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494 << New->getDeclName()
495 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 } else if (New->getDeclContext()->isDependentContext()) {
497 // C++ [dcl.fct.default]p6 (DR217):
498 // Default arguments for a member function of a class template shall
499 // be specified on the initial declaration of the member function
500 // within the class template.
501 //
502 // Reading the tea leaves a bit in DR217 and its reference to DR205
503 // leads me to the conclusion that one cannot add default function
504 // arguments for an out-of-line definition of a member function of a
505 // dependent type.
506 int WhichKind = 2;
507 if (CXXRecordDecl *Record
508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509 if (Record->getDescribedClassTemplate())
510 WhichKind = 0;
511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512 WhichKind = 1;
513 else
514 WhichKind = 2;
515 }
516
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_member_template_redecl)
519 << WhichKind
520 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000521 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
522 CXXSpecialMember NewSM = getSpecialMember(Ctor),
523 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
524 if (NewSM != OldSM) {
525 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
526 << NewParam->getDefaultArgRange() << NewSM;
527 Diag(Old->getLocation(), diag::note_previous_declaration_special)
528 << OldSM;
529 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000530 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000531 }
532 }
533
Richard Smithff234882012-02-20 23:28:05 +0000534 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000535 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000536 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000537 if (New->isConstexpr() != Old->isConstexpr()) {
538 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
539 << New << New->isConstexpr();
540 Diag(Old->getLocation(), diag::note_previous_declaration);
541 Invalid = true;
542 }
543
Douglas Gregore13ad832010-02-12 07:32:17 +0000544 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000545 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000546
Douglas Gregorcda9c672009-02-16 17:45:42 +0000547 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000548}
549
Sebastian Redl60618fa2011-03-12 11:50:43 +0000550/// \brief Merge the exception specifications of two variable declarations.
551///
552/// This is called when there's a redeclaration of a VarDecl. The function
553/// checks if the redeclaration might have an exception specification and
554/// validates compatibility and merges the specs if necessary.
555void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
556 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000557 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000558 return;
559
560 assert(Context.hasSameType(New->getType(), Old->getType()) &&
561 "Should only be called if types are otherwise the same.");
562
563 QualType NewType = New->getType();
564 QualType OldType = Old->getType();
565
566 // We're only interested in pointers and references to functions, as well
567 // as pointers to member functions.
568 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
569 NewType = R->getPointeeType();
570 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
571 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
572 NewType = P->getPointeeType();
573 OldType = OldType->getAs<PointerType>()->getPointeeType();
574 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
575 NewType = M->getPointeeType();
576 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
577 }
578
579 if (!NewType->isFunctionProtoType())
580 return;
581
582 // There's lots of special cases for functions. For function pointers, system
583 // libraries are hopefully not as broken so that we don't need these
584 // workarounds.
585 if (CheckEquivalentExceptionSpec(
586 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
587 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
588 New->setInvalidDecl();
589 }
590}
591
Chris Lattner3d1cee32008-04-08 05:04:30 +0000592/// CheckCXXDefaultArguments - Verify that the default arguments for a
593/// function declaration are well-formed according to C++
594/// [dcl.fct.default].
595void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
596 unsigned NumParams = FD->getNumParams();
597 unsigned p;
598
Douglas Gregorc6889e72012-02-14 22:28:59 +0000599 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
600 isa<CXXMethodDecl>(FD) &&
601 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
602
Chris Lattner3d1cee32008-04-08 05:04:30 +0000603 // Find first parameter with a default argument
604 for (p = 0; p < NumParams; ++p) {
605 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000606 if (Param->hasDefaultArg()) {
607 // C++11 [expr.prim.lambda]p5:
608 // [...] Default arguments (8.3.6) shall not be specified in the
609 // parameter-declaration-clause of a lambda-declarator.
610 //
611 // FIXME: Core issue 974 strikes this sentence, we only provide an
612 // extension warning.
613 if (IsLambda)
614 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
615 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000616 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000617 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000618 }
619
620 // C++ [dcl.fct.default]p4:
621 // In a given function declaration, all parameters
622 // subsequent to a parameter with a default argument shall
623 // have default arguments supplied in this or previous
624 // declarations. A default argument shall not be redefined
625 // by a later declaration (not even to the same value).
626 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000627 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000628 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000629 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000630 if (Param->isInvalidDecl())
631 /* We already complained about this parameter. */;
632 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000633 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000634 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000635 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000636 else
Mike Stump1eb44332009-09-09 15:08:12 +0000637 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000638 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Chris Lattner3d1cee32008-04-08 05:04:30 +0000640 LastMissingDefaultArg = p;
641 }
642 }
643
644 if (LastMissingDefaultArg > 0) {
645 // Some default arguments were missing. Clear out all of the
646 // default arguments up to (and including) the last missing
647 // default argument, so that we leave the function parameters
648 // in a semantically valid state.
649 for (p = 0; p <= LastMissingDefaultArg; ++p) {
650 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000651 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000652 Param->setDefaultArg(0);
653 }
654 }
655 }
656}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000657
Richard Smith9f569cc2011-10-01 02:31:28 +0000658// CheckConstexprParameterTypes - Check whether a function's parameter types
659// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000660// diagnostic and return false.
661static bool CheckConstexprParameterTypes(Sema &SemaRef,
662 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000663 unsigned ArgIndex = 0;
664 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
665 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
666 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
667 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
668 SourceLocation ParamLoc = PD->getLocation();
669 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000670 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000671 diag::err_constexpr_non_literal_param,
672 ArgIndex+1, PD->getSourceRange(),
673 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000674 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000675 }
676 return true;
677}
678
679// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000680// the requirements of a constexpr function definition or a constexpr
681// constructor definition. If so, return true. If not, produce appropriate
682// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000683//
Richard Smith86c3ae42012-02-13 03:54:03 +0000684// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
685bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000686 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
687 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000688 // C++11 [dcl.constexpr]p4:
689 // The definition of a constexpr constructor shall satisfy the following
690 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000691 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000692 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000693 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000694 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
695 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
696 << RD->getNumVBases();
697 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
698 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000699 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000700 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000701 return false;
702 }
Richard Smith35340502012-01-13 04:54:00 +0000703 }
704
705 if (!isa<CXXConstructorDecl>(NewFD)) {
706 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000707 // The definition of a constexpr function shall satisfy the following
708 // constraints:
709 // - it shall not be virtual;
710 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
711 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000712 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000713
Richard Smith86c3ae42012-02-13 03:54:03 +0000714 // If it's not obvious why this function is virtual, find an overridden
715 // function which uses the 'virtual' keyword.
716 const CXXMethodDecl *WrittenVirtual = Method;
717 while (!WrittenVirtual->isVirtualAsWritten())
718 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
719 if (WrittenVirtual != Method)
720 Diag(WrittenVirtual->getLocation(),
721 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000722 return false;
723 }
724
725 // - its return type shall be a literal type;
726 QualType RT = NewFD->getResultType();
727 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000728 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000729 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000731 }
732
Richard Smith35340502012-01-13 04:54:00 +0000733 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000734 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000735 return false;
736
Richard Smith9f569cc2011-10-01 02:31:28 +0000737 return true;
738}
739
740/// Check the given declaration statement is legal within a constexpr function
741/// body. C++0x [dcl.constexpr]p3,p4.
742///
743/// \return true if the body is OK, false if we have diagnosed a problem.
744static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
745 DeclStmt *DS) {
746 // C++0x [dcl.constexpr]p3 and p4:
747 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
748 // contain only
749 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
750 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
751 switch ((*DclIt)->getKind()) {
752 case Decl::StaticAssert:
753 case Decl::Using:
754 case Decl::UsingShadow:
755 case Decl::UsingDirective:
756 case Decl::UnresolvedUsingTypename:
757 // - static_assert-declarations
758 // - using-declarations,
759 // - using-directives,
760 continue;
761
762 case Decl::Typedef:
763 case Decl::TypeAlias: {
764 // - typedef declarations and alias-declarations that do not define
765 // classes or enumerations,
766 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
767 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
768 // Don't allow variably-modified types in constexpr functions.
769 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
770 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
771 << TL.getSourceRange() << TL.getType()
772 << isa<CXXConstructorDecl>(Dcl);
773 return false;
774 }
775 continue;
776 }
777
778 case Decl::Enum:
779 case Decl::CXXRecord:
780 // As an extension, we allow the declaration (but not the definition) of
781 // classes and enumerations in all declarations, not just in typedef and
782 // alias declarations.
783 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
784 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
785 << isa<CXXConstructorDecl>(Dcl);
786 return false;
787 }
788 continue;
789
790 case Decl::Var:
791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
792 << isa<CXXConstructorDecl>(Dcl);
793 return false;
794
795 default:
796 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
797 << isa<CXXConstructorDecl>(Dcl);
798 return false;
799 }
800 }
801
802 return true;
803}
804
805/// Check that the given field is initialized within a constexpr constructor.
806///
807/// \param Dcl The constexpr constructor being checked.
808/// \param Field The field being checked. This may be a member of an anonymous
809/// struct or union nested within the class being checked.
810/// \param Inits All declarations, including anonymous struct/union members and
811/// indirect members, for which any initialization was provided.
812/// \param Diagnosed Set to true if an error is produced.
813static void CheckConstexprCtorInitializer(Sema &SemaRef,
814 const FunctionDecl *Dcl,
815 FieldDecl *Field,
816 llvm::SmallSet<Decl*, 16> &Inits,
817 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000818 if (Field->isUnnamedBitfield())
819 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000820
821 if (Field->isAnonymousStructOrUnion() &&
822 Field->getType()->getAsCXXRecordDecl()->isEmpty())
823 return;
824
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 if (!Inits.count(Field)) {
826 if (!Diagnosed) {
827 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
828 Diagnosed = true;
829 }
830 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
831 } else if (Field->isAnonymousStructOrUnion()) {
832 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
833 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
834 I != E; ++I)
835 // If an anonymous union contains an anonymous struct of which any member
836 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000837 if (!RD->isUnion() || Inits.count(*I))
838 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000839 }
840}
841
842/// Check the body for the given constexpr function declaration only contains
843/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
844///
845/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000846bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000847 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000848 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 // The definition of a constexpr function shall satisfy the following
850 // constraints: [...]
851 // - its function-body shall be = delete, = default, or a
852 // compound-statement
853 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000854 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000855 // In the definition of a constexpr constructor, [...]
856 // - its function-body shall not be a function-try-block;
857 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
858 << isa<CXXConstructorDecl>(Dcl);
859 return false;
860 }
861
862 // - its function-body shall be [...] a compound-statement that contains only
863 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
864
865 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
866 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
867 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
868 switch ((*BodyIt)->getStmtClass()) {
869 case Stmt::NullStmtClass:
870 // - null statements,
871 continue;
872
873 case Stmt::DeclStmtClass:
874 // - static_assert-declarations
875 // - using-declarations,
876 // - using-directives,
877 // - typedef declarations and alias-declarations that do not define
878 // classes or enumerations,
879 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
880 return false;
881 continue;
882
883 case Stmt::ReturnStmtClass:
884 // - and exactly one return statement;
885 if (isa<CXXConstructorDecl>(Dcl))
886 break;
887
888 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000889 continue;
890
891 default:
892 break;
893 }
894
895 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
896 << isa<CXXConstructorDecl>(Dcl);
897 return false;
898 }
899
900 if (const CXXConstructorDecl *Constructor
901 = dyn_cast<CXXConstructorDecl>(Dcl)) {
902 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000903 // DR1359:
904 // - every non-variant non-static data member and base class sub-object
905 // shall be initialized;
906 // - if the class is a non-empty union, or for each non-empty anonymous
907 // union member of a non-union class, exactly one non-static data member
908 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000909 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000910 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000911 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
912 return false;
913 }
Richard Smith6e433752011-10-10 16:38:04 +0000914 } else if (!Constructor->isDependentContext() &&
915 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000916 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
917
918 // Skip detailed checking if we have enough initializers, and we would
919 // allow at most one initializer per member.
920 bool AnyAnonStructUnionMembers = false;
921 unsigned Fields = 0;
922 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
923 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000924 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000925 AnyAnonStructUnionMembers = true;
926 break;
927 }
928 }
929 if (AnyAnonStructUnionMembers ||
930 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
931 // Check initialization of non-static data members. Base classes are
932 // always initialized so do not need to be checked. Dependent bases
933 // might not have initializers in the member initializer list.
934 llvm::SmallSet<Decl*, 16> Inits;
935 for (CXXConstructorDecl::init_const_iterator
936 I = Constructor->init_begin(), E = Constructor->init_end();
937 I != E; ++I) {
938 if (FieldDecl *FD = (*I)->getMember())
939 Inits.insert(FD);
940 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
941 Inits.insert(ID->chain_begin(), ID->chain_end());
942 }
943
944 bool Diagnosed = false;
945 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
946 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000947 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000948 if (Diagnosed)
949 return false;
950 }
951 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000952 } else {
953 if (ReturnStmts.empty()) {
954 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
955 return false;
956 }
957 if (ReturnStmts.size() > 1) {
958 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
959 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
960 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
961 return false;
962 }
963 }
964
Richard Smith5ba73e12012-02-04 00:33:54 +0000965 // C++11 [dcl.constexpr]p5:
966 // if no function argument values exist such that the function invocation
967 // substitution would produce a constant expression, the program is
968 // ill-formed; no diagnostic required.
969 // C++11 [dcl.constexpr]p3:
970 // - every constructor call and implicit conversion used in initializing the
971 // return value shall be one of those allowed in a constant expression.
972 // C++11 [dcl.constexpr]p4:
973 // - every constructor involved in initializing non-static data members and
974 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000975 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000976 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000977 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
978 << isa<CXXConstructorDecl>(Dcl);
979 for (size_t I = 0, N = Diags.size(); I != N; ++I)
980 Diag(Diags[I].first, Diags[I].second);
981 return false;
982 }
983
Richard Smith9f569cc2011-10-01 02:31:28 +0000984 return true;
985}
986
Douglas Gregorb48fe382008-10-31 09:07:45 +0000987/// isCurrentClassName - Determine whether the identifier II is the
988/// name of the class type currently being defined. In the case of
989/// nested classes, this will only return true if II is the name of
990/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000991bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
992 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000993 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000994
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000995 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000996 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000997 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000998 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
999 } else
1000 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1001
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001002 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001003 return &II == CurDecl->getIdentifier();
1004 else
1005 return false;
1006}
1007
Mike Stump1eb44332009-09-09 15:08:12 +00001008/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001009///
1010/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1011/// and returns NULL otherwise.
1012CXXBaseSpecifier *
1013Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1014 SourceRange SpecifierRange,
1015 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001016 TypeSourceInfo *TInfo,
1017 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001018 QualType BaseType = TInfo->getType();
1019
Douglas Gregor2943aed2009-03-03 04:44:36 +00001020 // C++ [class.union]p1:
1021 // A union shall not have base classes.
1022 if (Class->isUnion()) {
1023 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1024 << SpecifierRange;
1025 return 0;
1026 }
1027
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001028 if (EllipsisLoc.isValid() &&
1029 !TInfo->getType()->containsUnexpandedParameterPack()) {
1030 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1031 << TInfo->getTypeLoc().getSourceRange();
1032 EllipsisLoc = SourceLocation();
1033 }
1034
Douglas Gregor2943aed2009-03-03 04:44:36 +00001035 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001036 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001037 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001038 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001039
1040 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001041
1042 // Base specifiers must be record types.
1043 if (!BaseType->isRecordType()) {
1044 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1045 return 0;
1046 }
1047
1048 // C++ [class.union]p1:
1049 // A union shall not be used as a base class.
1050 if (BaseType->isUnionType()) {
1051 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1052 return 0;
1053 }
1054
1055 // C++ [class.derived]p2:
1056 // The class-name in a base-specifier shall not be an incompletely
1057 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001058 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001059 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001060 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001061 return 0;
John McCall572fc622010-08-17 07:23:57 +00001062 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001063
Eli Friedman1d954f62009-08-15 21:55:26 +00001064 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001065 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001066 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001067 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001068 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001069 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1070 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001071
Anders Carlsson1d209272011-03-25 14:55:14 +00001072 // C++ [class]p3:
1073 // If a class is marked final and it appears as a base-type-specifier in
1074 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001075 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001076 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1077 << CXXBaseDecl->getDeclName();
1078 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1079 << CXXBaseDecl->getDeclName();
1080 return 0;
1081 }
1082
John McCall572fc622010-08-17 07:23:57 +00001083 if (BaseDecl->isInvalidDecl())
1084 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001085
1086 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001087 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001088 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001089 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001090}
1091
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001092/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1093/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001094/// example:
1095/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001096/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001097BaseResult
John McCalld226f652010-08-21 09:40:31 +00001098Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001099 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001100 ParsedType basetype, SourceLocation BaseLoc,
1101 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001102 if (!classdecl)
1103 return true;
1104
Douglas Gregor40808ce2009-03-09 23:48:35 +00001105 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001106 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001107 if (!Class)
1108 return true;
1109
Nick Lewycky56062202010-07-26 16:56:01 +00001110 TypeSourceInfo *TInfo = 0;
1111 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001112
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001113 if (EllipsisLoc.isInvalid() &&
1114 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001115 UPPC_BaseType))
1116 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001117
Douglas Gregor2943aed2009-03-03 04:44:36 +00001118 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001119 Virtual, Access, TInfo,
1120 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001121 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001122 else
1123 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Douglas Gregor2943aed2009-03-03 04:44:36 +00001125 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001126}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001127
Douglas Gregor2943aed2009-03-03 04:44:36 +00001128/// \brief Performs the actual work of attaching the given base class
1129/// specifiers to a C++ class.
1130bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1131 unsigned NumBases) {
1132 if (NumBases == 0)
1133 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001134
1135 // Used to keep track of which base types we have already seen, so
1136 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001137 // that the key is always the unqualified canonical type of the base
1138 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001139 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1140
1141 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001142 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001143 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001144 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001145 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001146 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001147 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001148
1149 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1150 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001151 // C++ [class.mi]p3:
1152 // A class shall not be specified as a direct base class of a
1153 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001154 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001155 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001156 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001157 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001158
1159 // Delete the duplicate base class specifier; we're going to
1160 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001161 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001162
1163 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001164 } else {
1165 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001166 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001167 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001168 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001169 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1170 if (RD->hasAttr<WeakAttr>())
1171 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001172 }
1173 }
1174
1175 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001176 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001177
1178 // Delete the remaining (good) base class specifiers, since their
1179 // data has been copied into the CXXRecordDecl.
1180 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001181 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001182
1183 return Invalid;
1184}
1185
1186/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1187/// class, after checking whether there are any duplicate base
1188/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001189void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001190 unsigned NumBases) {
1191 if (!ClassDecl || !Bases || !NumBases)
1192 return;
1193
1194 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001195 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001196 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001197}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001198
John McCall3cb0ebd2010-03-10 03:28:59 +00001199static CXXRecordDecl *GetClassForType(QualType T) {
1200 if (const RecordType *RT = T->getAs<RecordType>())
1201 return cast<CXXRecordDecl>(RT->getDecl());
1202 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1203 return ICT->getDecl();
1204 else
1205 return 0;
1206}
1207
Douglas Gregora8f32e02009-10-06 17:59:45 +00001208/// \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) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001211 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001212 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001213
1214 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1215 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001216 return false;
1217
John McCall3cb0ebd2010-03-10 03:28:59 +00001218 CXXRecordDecl *BaseRD = GetClassForType(Base);
1219 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001220 return false;
1221
John McCall86ff3082010-02-04 22:26:26 +00001222 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1223 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001224}
1225
1226/// \brief Determine whether the type \p Derived is a C++ class that is
1227/// derived from the type \p Base.
1228bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001229 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001230 return false;
1231
John McCall3cb0ebd2010-03-10 03:28:59 +00001232 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1233 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001234 return false;
1235
John McCall3cb0ebd2010-03-10 03:28:59 +00001236 CXXRecordDecl *BaseRD = GetClassForType(Base);
1237 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001238 return false;
1239
Douglas Gregora8f32e02009-10-06 17:59:45 +00001240 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1241}
1242
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001243void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001244 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001245 assert(BasePathArray.empty() && "Base path array must be empty!");
1246 assert(Paths.isRecordingPaths() && "Must record paths!");
1247
1248 const CXXBasePath &Path = Paths.front();
1249
1250 // We first go backward and check if we have a virtual base.
1251 // FIXME: It would be better if CXXBasePath had the base specifier for
1252 // the nearest virtual base.
1253 unsigned Start = 0;
1254 for (unsigned I = Path.size(); I != 0; --I) {
1255 if (Path[I - 1].Base->isVirtual()) {
1256 Start = I - 1;
1257 break;
1258 }
1259 }
1260
1261 // Now add all bases.
1262 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001263 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001264}
1265
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001266/// \brief Determine whether the given base path includes a virtual
1267/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001268bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1269 for (CXXCastPath::const_iterator B = BasePath.begin(),
1270 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001271 B != BEnd; ++B)
1272 if ((*B)->isVirtual())
1273 return true;
1274
1275 return false;
1276}
1277
Douglas Gregora8f32e02009-10-06 17:59:45 +00001278/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1279/// conversion (where Derived and Base are class types) is
1280/// well-formed, meaning that the conversion is unambiguous (and
1281/// that all of the base classes are accessible). Returns true
1282/// and emits a diagnostic if the code is ill-formed, returns false
1283/// otherwise. Loc is the location where this routine should point to
1284/// if there is an error, and Range is the source range to highlight
1285/// if there is an error.
1286bool
1287Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001288 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001289 unsigned AmbigiousBaseConvID,
1290 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001291 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001292 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001293 // First, determine whether the path from Derived to Base is
1294 // ambiguous. This is slightly more expensive than checking whether
1295 // the Derived to Base conversion exists, because here we need to
1296 // explore multiple paths to determine if there is an ambiguity.
1297 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1298 /*DetectVirtual=*/false);
1299 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1300 assert(DerivationOkay &&
1301 "Can only be used with a derived-to-base conversion");
1302 (void)DerivationOkay;
1303
1304 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001305 if (InaccessibleBaseID) {
1306 // Check that the base class can be accessed.
1307 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1308 InaccessibleBaseID)) {
1309 case AR_inaccessible:
1310 return true;
1311 case AR_accessible:
1312 case AR_dependent:
1313 case AR_delayed:
1314 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001315 }
John McCall6b2accb2010-02-10 09:31:12 +00001316 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001317
1318 // Build a base path if necessary.
1319 if (BasePath)
1320 BuildBasePathArray(Paths, *BasePath);
1321 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001322 }
1323
1324 // We know that the derived-to-base conversion is ambiguous, and
1325 // we're going to produce a diagnostic. Perform the derived-to-base
1326 // search just one more time to compute all of the possible paths so
1327 // that we can print them out. This is more expensive than any of
1328 // the previous derived-to-base checks we've done, but at this point
1329 // performance isn't as much of an issue.
1330 Paths.clear();
1331 Paths.setRecordingPaths(true);
1332 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1333 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1334 (void)StillOkay;
1335
1336 // Build up a textual representation of the ambiguous paths, e.g.,
1337 // D -> B -> A, that will be used to illustrate the ambiguous
1338 // conversions in the diagnostic. We only print one of the paths
1339 // to each base class subobject.
1340 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1341
1342 Diag(Loc, AmbigiousBaseConvID)
1343 << Derived << Base << PathDisplayStr << Range << Name;
1344 return true;
1345}
1346
1347bool
1348Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001349 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001350 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001351 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001352 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001353 IgnoreAccess ? 0
1354 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001355 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001356 Loc, Range, DeclarationName(),
1357 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001358}
1359
1360
1361/// @brief Builds a string representing ambiguous paths from a
1362/// specific derived class to different subobjects of the same base
1363/// class.
1364///
1365/// This function builds a string that can be used in error messages
1366/// to show the different paths that one can take through the
1367/// inheritance hierarchy to go from the derived class to different
1368/// subobjects of a base class. The result looks something like this:
1369/// @code
1370/// struct D -> struct B -> struct A
1371/// struct D -> struct C -> struct A
1372/// @endcode
1373std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1374 std::string PathDisplayStr;
1375 std::set<unsigned> DisplayedPaths;
1376 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1377 Path != Paths.end(); ++Path) {
1378 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1379 // We haven't displayed a path to this particular base
1380 // class subobject yet.
1381 PathDisplayStr += "\n ";
1382 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1383 for (CXXBasePath::const_iterator Element = Path->begin();
1384 Element != Path->end(); ++Element)
1385 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1386 }
1387 }
1388
1389 return PathDisplayStr;
1390}
1391
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001392//===----------------------------------------------------------------------===//
1393// C++ class member Handling
1394//===----------------------------------------------------------------------===//
1395
Abramo Bagnara6206d532010-06-05 05:09:32 +00001396/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001397bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1398 SourceLocation ASLoc,
1399 SourceLocation ColonLoc,
1400 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001401 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001402 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001403 ASLoc, ColonLoc);
1404 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001405 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001406}
1407
Richard Smitha4b39652012-08-06 03:25:17 +00001408/// CheckOverrideControl - Check C++11 override control semantics.
1409void Sema::CheckOverrideControl(Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001410 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001411
Richard Smitha4b39652012-08-06 03:25:17 +00001412 // Do we know which functions this declaration might be overriding?
1413 bool OverridesAreKnown = !MD ||
1414 (!MD->getParent()->hasAnyDependentBases() &&
1415 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001416
Richard Smitha4b39652012-08-06 03:25:17 +00001417 if (!MD || !MD->isVirtual()) {
1418 if (OverridesAreKnown) {
1419 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1420 Diag(OA->getLocation(),
1421 diag::override_keyword_only_allowed_on_virtual_member_functions)
1422 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1423 D->dropAttr<OverrideAttr>();
1424 }
1425 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1426 Diag(FA->getLocation(),
1427 diag::override_keyword_only_allowed_on_virtual_member_functions)
1428 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1429 D->dropAttr<FinalAttr>();
1430 }
1431 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001432 return;
1433 }
Richard Smitha4b39652012-08-06 03:25:17 +00001434
1435 if (!OverridesAreKnown)
1436 return;
1437
1438 // C++11 [class.virtual]p5:
1439 // If a virtual function is marked with the virt-specifier override and
1440 // does not override a member function of a base class, the program is
1441 // ill-formed.
1442 bool HasOverriddenMethods =
1443 MD->begin_overridden_methods() != MD->end_overridden_methods();
1444 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1445 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1446 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001447}
1448
Richard Smitha4b39652012-08-06 03:25:17 +00001449/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001450/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001451/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001452bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1453 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001454 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001455 return false;
1456
1457 Diag(New->getLocation(), diag::err_final_function_overridden)
1458 << New->getDeclName();
1459 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1460 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001461}
1462
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001463static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001464 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1465 // FIXME: Destruction of ObjC lifetime types has side-effects.
1466 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1467 return !RD->isCompleteDefinition() ||
1468 !RD->hasTrivialDefaultConstructor() ||
1469 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001470 return false;
1471}
1472
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001473/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1474/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001475/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001476/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1477/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001478Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001479Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001480 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001481 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001482 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001483 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001484 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1485 DeclarationName Name = NameInfo.getName();
1486 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001487
1488 // For anonymous bitfields, the location should point to the type.
1489 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001490 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001491
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001492 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001493
John McCall4bde1e12010-06-04 08:34:12 +00001494 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001495 assert(!DS.isFriendSpecified());
1496
Richard Smith1ab0d902011-06-25 02:28:38 +00001497 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001498
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001499 // C++ 9.2p6: A member shall not be declared to have automatic storage
1500 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001501 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1502 // data members and cannot be applied to names declared const or static,
1503 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001504 switch (DS.getStorageClassSpec()) {
1505 case DeclSpec::SCS_unspecified:
1506 case DeclSpec::SCS_typedef:
1507 case DeclSpec::SCS_static:
1508 // FALL THROUGH.
1509 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001510 case DeclSpec::SCS_mutable:
1511 if (isFunc) {
1512 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001513 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001514 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001515 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Sebastian Redla11f42f2008-11-17 23:24:37 +00001517 // FIXME: It would be nicer if the keyword was ignored only for this
1518 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001519 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001520 }
1521 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001522 default:
1523 if (DS.getStorageClassSpecLoc().isValid())
1524 Diag(DS.getStorageClassSpecLoc(),
1525 diag::err_storageclass_invalid_for_member);
1526 else
1527 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1528 D.getMutableDeclSpec().ClearStorageClassSpecs();
1529 }
1530
Sebastian Redl669d5d72008-11-14 23:42:31 +00001531 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1532 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001533 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001534
1535 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001536 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001537 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001538
1539 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001540 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001541 Diag(Loc, diag::err_bad_variable_name)
1542 << Name;
1543 return 0;
1544 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001545
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001546 IdentifierInfo *II = Name.getAsIdentifierInfo();
1547
Douglas Gregorf2503652011-09-21 14:40:46 +00001548 // Member field could not be with "template" keyword.
1549 // So TemplateParameterLists should be empty in this case.
1550 if (TemplateParameterLists.size()) {
1551 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1552 if (TemplateParams->size()) {
1553 // There is no such thing as a member field template.
1554 Diag(D.getIdentifierLoc(), diag::err_template_member)
1555 << II
1556 << SourceRange(TemplateParams->getTemplateLoc(),
1557 TemplateParams->getRAngleLoc());
1558 } else {
1559 // There is an extraneous 'template<>' for this member.
1560 Diag(TemplateParams->getTemplateLoc(),
1561 diag::err_template_member_noparams)
1562 << II
1563 << SourceRange(TemplateParams->getTemplateLoc(),
1564 TemplateParams->getRAngleLoc());
1565 }
1566 return 0;
1567 }
1568
Douglas Gregor922fff22010-10-13 22:19:53 +00001569 if (SS.isSet() && !SS.isInvalid()) {
1570 // The user provided a superfluous scope specifier inside a class
1571 // definition:
1572 //
1573 // class X {
1574 // int X::member;
1575 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001576 if (DeclContext *DC = computeDeclContext(SS, false))
1577 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001578 else
1579 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1580 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001581
Douglas Gregor922fff22010-10-13 22:19:53 +00001582 SS.clear();
1583 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001584
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001585 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001586 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001587 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001588 } else {
Richard Smithca523302012-06-10 03:12:00 +00001589 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001590
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001591 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001592 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001593 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001594 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001595
1596 // Non-instance-fields can't have a bitfield.
1597 if (BitWidth) {
1598 if (Member->isInvalidDecl()) {
1599 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001600 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001601 // C++ 9.6p3: A bit-field shall not be a static member.
1602 // "static member 'A' cannot be a bit-field"
1603 Diag(Loc, diag::err_static_not_bitfield)
1604 << Name << BitWidth->getSourceRange();
1605 } else if (isa<TypedefDecl>(Member)) {
1606 // "typedef member 'x' cannot be a bit-field"
1607 Diag(Loc, diag::err_typedef_not_bitfield)
1608 << Name << BitWidth->getSourceRange();
1609 } else {
1610 // A function typedef ("typedef int f(); f a;").
1611 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1612 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001613 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001614 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001615 }
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Chris Lattner8b963ef2009-03-05 23:01:03 +00001617 BitWidth = 0;
1618 Member->setInvalidDecl();
1619 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001620
1621 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Douglas Gregor37b372b2009-08-20 22:52:58 +00001623 // If we have declared a member function template, set the access of the
1624 // templated declaration as well.
1625 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1626 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001627 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001628
Richard Smitha4b39652012-08-06 03:25:17 +00001629 if (VS.isOverrideSpecified())
1630 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1631 if (VS.isFinalSpecified())
1632 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001633
Douglas Gregorf5251602011-03-08 17:10:18 +00001634 if (VS.getLastLocation().isValid()) {
1635 // Update the end location of a method that has a virt-specifiers.
1636 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1637 MD->setRangeEnd(VS.getLastLocation());
1638 }
Richard Smitha4b39652012-08-06 03:25:17 +00001639
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001640 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001641
Douglas Gregor10bd3682008-11-17 22:58:34 +00001642 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001643
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001644 if (isInstField) {
1645 FieldDecl *FD = cast<FieldDecl>(Member);
1646 FieldCollector->Add(FD);
1647
1648 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1649 FD->getLocation())
1650 != DiagnosticsEngine::Ignored) {
1651 // Remember all explicit private FieldDecls that have a name, no side
1652 // effects and are not part of a dependent type declaration.
1653 if (!FD->isImplicit() && FD->getDeclName() &&
1654 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001655 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001656 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001657 !InitializationHasSideEffects(*FD))
1658 UnusedPrivateFields.insert(FD);
1659 }
1660 }
1661
John McCalld226f652010-08-21 09:40:31 +00001662 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001663}
1664
Richard Smith7a614d82011-06-11 17:19:42 +00001665/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001666/// in-class initializer for a non-static C++ class member, and after
1667/// instantiating an in-class initializer in a class template. Such actions
1668/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001669void
Richard Smithca523302012-06-10 03:12:00 +00001670Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001671 Expr *InitExpr) {
1672 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001673 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1674 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001675
1676 if (!InitExpr) {
1677 FD->setInvalidDecl();
1678 FD->removeInClassInitializer();
1679 return;
1680 }
1681
Peter Collingbournefef21892011-10-23 18:59:44 +00001682 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1683 FD->setInvalidDecl();
1684 FD->removeInClassInitializer();
1685 return;
1686 }
1687
Richard Smith7a614d82011-06-11 17:19:42 +00001688 ExprResult Init = InitExpr;
1689 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001690 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001691 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001692 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1693 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001694 Expr **Inits = &InitExpr;
1695 unsigned NumInits = 1;
1696 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001697 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001698 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001699 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001700 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1701 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001702 if (Init.isInvalid()) {
1703 FD->setInvalidDecl();
1704 return;
1705 }
1706
Richard Smithca523302012-06-10 03:12:00 +00001707 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001708 }
1709
1710 // C++0x [class.base.init]p7:
1711 // The initialization of each base and member constitutes a
1712 // full-expression.
1713 Init = MaybeCreateExprWithCleanups(Init);
1714 if (Init.isInvalid()) {
1715 FD->setInvalidDecl();
1716 return;
1717 }
1718
1719 InitExpr = Init.release();
1720
1721 FD->setInClassInitializer(InitExpr);
1722}
1723
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001724/// \brief Find the direct and/or virtual base specifiers that
1725/// correspond to the given base type, for use in base initialization
1726/// within a constructor.
1727static bool FindBaseInitializer(Sema &SemaRef,
1728 CXXRecordDecl *ClassDecl,
1729 QualType BaseType,
1730 const CXXBaseSpecifier *&DirectBaseSpec,
1731 const CXXBaseSpecifier *&VirtualBaseSpec) {
1732 // First, check for a direct base class.
1733 DirectBaseSpec = 0;
1734 for (CXXRecordDecl::base_class_const_iterator Base
1735 = ClassDecl->bases_begin();
1736 Base != ClassDecl->bases_end(); ++Base) {
1737 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1738 // We found a direct base of this type. That's what we're
1739 // initializing.
1740 DirectBaseSpec = &*Base;
1741 break;
1742 }
1743 }
1744
1745 // Check for a virtual base class.
1746 // FIXME: We might be able to short-circuit this if we know in advance that
1747 // there are no virtual bases.
1748 VirtualBaseSpec = 0;
1749 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1750 // We haven't found a base yet; search the class hierarchy for a
1751 // virtual base class.
1752 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1753 /*DetectVirtual=*/false);
1754 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1755 BaseType, Paths)) {
1756 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1757 Path != Paths.end(); ++Path) {
1758 if (Path->back().Base->isVirtual()) {
1759 VirtualBaseSpec = Path->back().Base;
1760 break;
1761 }
1762 }
1763 }
1764 }
1765
1766 return DirectBaseSpec || VirtualBaseSpec;
1767}
1768
Sebastian Redl6df65482011-09-24 17:48:25 +00001769/// \brief Handle a C++ member initializer using braced-init-list syntax.
1770MemInitResult
1771Sema::ActOnMemInitializer(Decl *ConstructorD,
1772 Scope *S,
1773 CXXScopeSpec &SS,
1774 IdentifierInfo *MemberOrBase,
1775 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001776 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001777 SourceLocation IdLoc,
1778 Expr *InitList,
1779 SourceLocation EllipsisLoc) {
1780 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001781 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001782 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001783}
1784
1785/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001786MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001787Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001788 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001789 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001790 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001791 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001792 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001793 SourceLocation IdLoc,
1794 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001795 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001796 SourceLocation RParenLoc,
1797 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001798 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1799 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001800 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001801 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001802}
1803
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001804namespace {
1805
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001806// Callback to only accept typo corrections that can be a valid C++ member
1807// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001808class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1809 public:
1810 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1811 : ClassDecl(ClassDecl) {}
1812
1813 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1814 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1815 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1816 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1817 else
1818 return isa<TypeDecl>(ND);
1819 }
1820 return false;
1821 }
1822
1823 private:
1824 CXXRecordDecl *ClassDecl;
1825};
1826
1827}
1828
Sebastian Redl6df65482011-09-24 17:48:25 +00001829/// \brief Handle a C++ member initializer.
1830MemInitResult
1831Sema::BuildMemInitializer(Decl *ConstructorD,
1832 Scope *S,
1833 CXXScopeSpec &SS,
1834 IdentifierInfo *MemberOrBase,
1835 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001836 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001837 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001838 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001839 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001840 if (!ConstructorD)
1841 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001843 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
1845 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001846 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001847 if (!Constructor) {
1848 // The user wrote a constructor initializer on a function that is
1849 // not a C++ constructor. Ignore the error for now, because we may
1850 // have more member initializers coming; we'll diagnose it just
1851 // once in ActOnMemInitializers.
1852 return true;
1853 }
1854
1855 CXXRecordDecl *ClassDecl = Constructor->getParent();
1856
1857 // C++ [class.base.init]p2:
1858 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001859 // constructor's class and, if not found in that scope, are looked
1860 // up in the scope containing the constructor's definition.
1861 // [Note: if the constructor's class contains a member with the
1862 // same name as a direct or virtual base class of the class, a
1863 // mem-initializer-id naming the member or base class and composed
1864 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001865 // mem-initializer-id for the hidden base class may be specified
1866 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001867 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001868 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001869 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001870 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001871 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001872 ValueDecl *Member;
1873 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1874 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001875 if (EllipsisLoc.isValid())
1876 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001877 << MemberOrBase
1878 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001879
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001880 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001881 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001882 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001883 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001884 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001885 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001886 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001887
1888 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001889 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001890 } else if (DS.getTypeSpecType() == TST_decltype) {
1891 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001892 } else {
1893 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1894 LookupParsedName(R, S, &SS);
1895
1896 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1897 if (!TyD) {
1898 if (R.isAmbiguous()) return true;
1899
John McCallfd225442010-04-09 19:01:14 +00001900 // We don't want access-control diagnostics here.
1901 R.suppressDiagnostics();
1902
Douglas Gregor7a886e12010-01-19 06:46:48 +00001903 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1904 bool NotUnknownSpecialization = false;
1905 DeclContext *DC = computeDeclContext(SS, false);
1906 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1907 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1908
1909 if (!NotUnknownSpecialization) {
1910 // When the scope specifier can refer to a member of an unknown
1911 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001912 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1913 SS.getWithLocInContext(Context),
1914 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001915 if (BaseType.isNull())
1916 return true;
1917
Douglas Gregor7a886e12010-01-19 06:46:48 +00001918 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001919 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001920 }
1921 }
1922
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001923 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001924 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001925 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001926 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001927 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001928 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001929 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1930 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001931 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001932 // We have found a non-static data member with a similar
1933 // name to what was typed; complain and initialize that
1934 // member.
1935 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1936 << MemberOrBase << true << CorrectedQuotedStr
1937 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1938 Diag(Member->getLocation(), diag::note_previous_decl)
1939 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001940
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001941 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001942 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001943 const CXXBaseSpecifier *DirectBaseSpec;
1944 const CXXBaseSpecifier *VirtualBaseSpec;
1945 if (FindBaseInitializer(*this, ClassDecl,
1946 Context.getTypeDeclType(Type),
1947 DirectBaseSpec, VirtualBaseSpec)) {
1948 // We have found a direct or virtual base class with a
1949 // similar name to what was typed; complain and initialize
1950 // that base class.
1951 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001952 << MemberOrBase << false << CorrectedQuotedStr
1953 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001954
1955 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1956 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001957 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001958 diag::note_base_class_specified_here)
1959 << BaseSpec->getType()
1960 << BaseSpec->getSourceRange();
1961
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001962 TyD = Type;
1963 }
1964 }
1965 }
1966
Douglas Gregor7a886e12010-01-19 06:46:48 +00001967 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001968 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001969 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001970 return true;
1971 }
John McCall2b194412009-12-21 10:41:20 +00001972 }
1973
Douglas Gregor7a886e12010-01-19 06:46:48 +00001974 if (BaseType.isNull()) {
1975 BaseType = Context.getTypeDeclType(TyD);
1976 if (SS.isSet()) {
1977 NestedNameSpecifier *Qualifier =
1978 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001979
Douglas Gregor7a886e12010-01-19 06:46:48 +00001980 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001981 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001982 }
John McCall2b194412009-12-21 10:41:20 +00001983 }
1984 }
Mike Stump1eb44332009-09-09 15:08:12 +00001985
John McCalla93c9342009-12-07 02:54:59 +00001986 if (!TInfo)
1987 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001988
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001989 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001990}
1991
Chandler Carruth81c64772011-09-03 01:14:15 +00001992/// Checks a member initializer expression for cases where reference (or
1993/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001994static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1995 Expr *Init,
1996 SourceLocation IdLoc) {
1997 QualType MemberTy = Member->getType();
1998
1999 // We only handle pointers and references currently.
2000 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2001 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2002 return;
2003
2004 const bool IsPointer = MemberTy->isPointerType();
2005 if (IsPointer) {
2006 if (const UnaryOperator *Op
2007 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2008 // The only case we're worried about with pointers requires taking the
2009 // address.
2010 if (Op->getOpcode() != UO_AddrOf)
2011 return;
2012
2013 Init = Op->getSubExpr();
2014 } else {
2015 // We only handle address-of expression initializers for pointers.
2016 return;
2017 }
2018 }
2019
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002020 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2021 // Taking the address of a temporary will be diagnosed as a hard error.
2022 if (IsPointer)
2023 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002024
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002025 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2026 << Member << Init->getSourceRange();
2027 } else if (const DeclRefExpr *DRE
2028 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2029 // We only warn when referring to a non-reference parameter declaration.
2030 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2031 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002032 return;
2033
2034 S.Diag(Init->getExprLoc(),
2035 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2036 : diag::warn_bind_ref_member_to_parameter)
2037 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002038 } else {
2039 // Other initializers are fine.
2040 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002041 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002042
2043 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2044 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002045}
2046
Richard Trieude5e75c2012-06-14 23:11:34 +00002047namespace {
2048 class UninitializedFieldVisitor
2049 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2050 Sema &S;
2051 ValueDecl *VD;
2052 public:
2053 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2054 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2055 S(S), VD(VD) {
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002056 }
2057
Richard Trieude5e75c2012-06-14 23:11:34 +00002058 void HandleExpr(Expr *E) {
2059 if (!E) return;
2060
2061 // Expressions like x(x) sometimes lack the surrounding expressions
2062 // but need to be checked anyways.
2063 HandleValue(E);
2064 Visit(E);
2065 }
2066
2067 void HandleValue(Expr *E) {
2068 E = E->IgnoreParens();
2069
Richard Trieue0991252012-06-14 23:18:09 +00002070 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieude5e75c2012-06-14 23:11:34 +00002071 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2072 return;
Richard Trieue0991252012-06-14 23:18:09 +00002073 Expr *Base = E;
Richard Trieude5e75c2012-06-14 23:11:34 +00002074 while (isa<MemberExpr>(Base)) {
2075 ME = dyn_cast<MemberExpr>(Base);
2076 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2077 if (VarD->hasGlobalStorage())
2078 return;
2079 Base = ME->getBase();
2080 }
2081
2082 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2083 S.Diag(ME->getExprLoc(), diag::warn_field_is_uninit);
2084 return;
2085 }
John McCallb4190042009-11-04 23:02:40 +00002086 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002087
2088 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2089 HandleValue(CO->getTrueExpr());
2090 HandleValue(CO->getFalseExpr());
2091 return;
2092 }
2093
2094 if (BinaryConditionalOperator *BCO =
2095 dyn_cast<BinaryConditionalOperator>(E)) {
2096 HandleValue(BCO->getCommon());
2097 HandleValue(BCO->getFalseExpr());
2098 return;
2099 }
2100
2101 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2102 switch (BO->getOpcode()) {
2103 default:
2104 return;
2105 case(BO_PtrMemD):
2106 case(BO_PtrMemI):
2107 HandleValue(BO->getLHS());
2108 return;
2109 case(BO_Comma):
2110 HandleValue(BO->getRHS());
2111 return;
2112 }
2113 }
John McCallb4190042009-11-04 23:02:40 +00002114 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002115
2116 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2117 if (E->getCastKind() == CK_LValueToRValue)
2118 HandleValue(E->getSubExpr());
2119
2120 Inherited::VisitImplicitCastExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002121 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002122
2123 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2124 Expr *Callee = E->getCallee();
2125 if (isa<MemberExpr>(Callee))
2126 HandleValue(Callee);
2127
2128 Inherited::VisitCXXMemberCallExpr(E);
2129 }
2130 };
2131 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2132 ValueDecl *VD) {
2133 UninitializedFieldVisitor(S, VD).HandleExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002134 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002135} // namespace
John McCallb4190042009-11-04 23:02:40 +00002136
John McCallf312b1e2010-08-26 23:41:50 +00002137MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002138Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002139 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002140 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2141 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2142 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002143 "Member must be a FieldDecl or IndirectFieldDecl");
2144
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002145 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002146 return true;
2147
Douglas Gregor464b2f02010-11-05 22:21:31 +00002148 if (Member->isInvalidDecl())
2149 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002150
John McCallb4190042009-11-04 23:02:40 +00002151 // Diagnose value-uses of fields to initialize themselves, e.g.
2152 // foo(foo)
2153 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002154 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002155 Expr **Args;
2156 unsigned NumArgs;
2157 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2158 Args = ParenList->getExprs();
2159 NumArgs = ParenList->getNumExprs();
2160 } else {
2161 InitListExpr *InitList = cast<InitListExpr>(Init);
2162 Args = InitList->getInits();
2163 NumArgs = InitList->getNumInits();
2164 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002165
Richard Trieude5e75c2012-06-14 23:11:34 +00002166 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2167 != DiagnosticsEngine::Ignored)
2168 for (unsigned i = 0; i < NumArgs; ++i)
2169 // FIXME: Warn about the case when other fields are used before being
John McCallb4190042009-11-04 23:02:40 +00002170 // uninitialized. For example, let this field be the i'th field. When
2171 // initializing the i'th field, throw a warning if any of the >= i'th
2172 // fields are used, as they are not yet initialized.
2173 // Right now we are only handling the case where the i'th field uses
2174 // itself in its initializer.
Richard Trieude5e75c2012-06-14 23:11:34 +00002175 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002176
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002177 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002178
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002179 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002180 // Can't check initialization for a member of dependent type or when
2181 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002182 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002183 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002184 bool InitList = false;
2185 if (isa<InitListExpr>(Init)) {
2186 InitList = true;
2187 Args = &Init;
2188 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002189
2190 if (isStdInitializerList(Member->getType(), 0)) {
2191 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2192 << /*at end of ctor*/1 << InitRange;
2193 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002194 }
2195
Chandler Carruth894aed92010-12-06 09:23:57 +00002196 // Initialize the member.
2197 InitializedEntity MemberEntity =
2198 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2199 : InitializedEntity::InitializeMember(IndirectMember, 0);
2200 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002201 InitList ? InitializationKind::CreateDirectList(IdLoc)
2202 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2203 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002204
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002205 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2206 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2207 MultiExprArg(*this, Args, NumArgs),
2208 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002209 if (MemberInit.isInvalid())
2210 return true;
2211
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002212 CheckImplicitConversions(MemberInit.get(),
2213 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002214
2215 // C++0x [class.base.init]p7:
2216 // The initialization of each base and member constitutes a
2217 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002218 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002219 if (MemberInit.isInvalid())
2220 return true;
2221
2222 // If we are in a dependent context, template instantiation will
2223 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002224 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002225 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2226 // of the information that we have about the member
2227 // initializer. However, deconstructing the ASTs is a dicey process,
2228 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002229 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002230 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002231 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002232 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002233 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2234 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002235 }
2236
Chandler Carruth894aed92010-12-06 09:23:57 +00002237 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002238 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2239 InitRange.getBegin(), Init,
2240 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002241 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002242 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2243 InitRange.getBegin(), Init,
2244 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002245 }
Eli Friedman59c04372009-07-29 19:44:27 +00002246}
2247
John McCallf312b1e2010-08-26 23:41:50 +00002248MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002249Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002250 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002251 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002252 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002253 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002254 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002255 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002256
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002257 bool InitList = true;
2258 Expr **Args = &Init;
2259 unsigned NumArgs = 1;
2260 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2261 InitList = false;
2262 Args = ParenList->getExprs();
2263 NumArgs = ParenList->getNumExprs();
2264 }
2265
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002266 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002267 // Initialize the object.
2268 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2269 QualType(ClassDecl->getTypeForDecl(), 0));
2270 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002271 InitList ? InitializationKind::CreateDirectList(NameLoc)
2272 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2273 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002274 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2275 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2276 MultiExprArg(*this, Args,NumArgs),
2277 0);
Sean Hunt41717662011-02-26 19:13:13 +00002278 if (DelegationInit.isInvalid())
2279 return true;
2280
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002281 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2282 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002283
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002284 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002285
2286 // C++0x [class.base.init]p7:
2287 // The initialization of each base and member constitutes a
2288 // full-expression.
2289 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2290 if (DelegationInit.isInvalid())
2291 return true;
2292
Eli Friedmand21016f2012-05-19 23:35:23 +00002293 // If we are in a dependent context, template instantiation will
2294 // perform this type-checking again. Just save the arguments that we
2295 // received in a ParenListExpr.
2296 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2297 // of the information that we have about the base
2298 // initializer. However, deconstructing the ASTs is a dicey process,
2299 // and this approach is far more likely to get the corner cases right.
2300 if (CurContext->isDependentContext())
2301 DelegationInit = Owned(Init);
2302
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002303 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002304 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002305 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002306}
2307
2308MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002309Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002310 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002311 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002312 SourceLocation BaseLoc
2313 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002314
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002315 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2316 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2317 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2318
2319 // C++ [class.base.init]p2:
2320 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002321 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002322 // of that class, the mem-initializer is ill-formed. A
2323 // mem-initializer-list can initialize a base class using any
2324 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002325 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002326
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002327 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002328 if (EllipsisLoc.isValid()) {
2329 // This is a pack expansion.
2330 if (!BaseType->containsUnexpandedParameterPack()) {
2331 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002332 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002333
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002334 EllipsisLoc = SourceLocation();
2335 }
2336 } else {
2337 // Check for any unexpanded parameter packs.
2338 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2339 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002340
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002341 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002342 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002343 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002344
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002345 // Check for direct and virtual base classes.
2346 const CXXBaseSpecifier *DirectBaseSpec = 0;
2347 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2348 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002349 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2350 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002351 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002352
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002353 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2354 VirtualBaseSpec);
2355
2356 // C++ [base.class.init]p2:
2357 // Unless the mem-initializer-id names a nonstatic data member of the
2358 // constructor's class or a direct or virtual base of that class, the
2359 // mem-initializer is ill-formed.
2360 if (!DirectBaseSpec && !VirtualBaseSpec) {
2361 // If the class has any dependent bases, then it's possible that
2362 // one of those types will resolve to the same type as
2363 // BaseType. Therefore, just treat this as a dependent base
2364 // class initialization. FIXME: Should we try to check the
2365 // initialization anyway? It seems odd.
2366 if (ClassDecl->hasAnyDependentBases())
2367 Dependent = true;
2368 else
2369 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2370 << BaseType << Context.getTypeDeclType(ClassDecl)
2371 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2372 }
2373 }
2374
2375 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002376 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Sebastian Redl6df65482011-09-24 17:48:25 +00002378 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2379 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002380 InitRange.getBegin(), Init,
2381 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002382 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002383
2384 // C++ [base.class.init]p2:
2385 // If a mem-initializer-id is ambiguous because it designates both
2386 // a direct non-virtual base class and an inherited virtual base
2387 // class, the mem-initializer is ill-formed.
2388 if (DirectBaseSpec && VirtualBaseSpec)
2389 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002390 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002391
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002392 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002393 if (!BaseSpec)
2394 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2395
2396 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002397 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002398 Expr **Args = &Init;
2399 unsigned NumArgs = 1;
2400 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002401 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002402 Args = ParenList->getExprs();
2403 NumArgs = ParenList->getNumExprs();
2404 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002405
2406 InitializedEntity BaseEntity =
2407 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2408 InitializationKind Kind =
2409 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2410 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2411 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002412 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2413 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2414 MultiExprArg(*this, Args, NumArgs),
2415 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002416 if (BaseInit.isInvalid())
2417 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002418
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002419 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002420
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002421 // C++0x [class.base.init]p7:
2422 // The initialization of each base and member constitutes a
2423 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002424 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002425 if (BaseInit.isInvalid())
2426 return true;
2427
2428 // If we are in a dependent context, template instantiation will
2429 // perform this type-checking again. Just save the arguments that we
2430 // received in a ParenListExpr.
2431 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2432 // of the information that we have about the base
2433 // initializer. However, deconstructing the ASTs is a dicey process,
2434 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002435 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002436 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002437
Sean Huntcbb67482011-01-08 20:30:50 +00002438 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002439 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002440 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002441 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002442 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002443}
2444
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002445// Create a static_cast\<T&&>(expr).
2446static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2447 QualType ExprType = E->getType();
2448 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2449 SourceLocation ExprLoc = E->getLocStart();
2450 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2451 TargetType, ExprLoc);
2452
2453 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2454 SourceRange(ExprLoc, ExprLoc),
2455 E->getSourceRange()).take();
2456}
2457
Anders Carlssone5ef7402010-04-23 03:10:23 +00002458/// ImplicitInitializerKind - How an implicit base or member initializer should
2459/// initialize its base or member.
2460enum ImplicitInitializerKind {
2461 IIK_Default,
2462 IIK_Copy,
2463 IIK_Move
2464};
2465
Anders Carlssondefefd22010-04-23 02:00:02 +00002466static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002467BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002468 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002469 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002470 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002471 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002472 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002473 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2474 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002475
John McCall60d7b3a2010-08-24 06:29:42 +00002476 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002477
2478 switch (ImplicitInitKind) {
2479 case IIK_Default: {
2480 InitializationKind InitKind
2481 = InitializationKind::CreateDefault(Constructor->getLocation());
2482 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2483 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002484 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002485 break;
2486 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002487
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002488 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002489 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002490 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002491 ParmVarDecl *Param = Constructor->getParamDecl(0);
2492 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002493
Anders Carlssone5ef7402010-04-23 03:10:23 +00002494 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002495 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002496 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002497 Constructor->getLocation(), ParamType,
2498 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002499
Eli Friedman5f2987c2012-02-02 03:46:19 +00002500 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2501
Anders Carlssonc7957502010-04-24 22:02:54 +00002502 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002503 QualType ArgTy =
2504 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2505 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002506
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002507 if (Moving) {
2508 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2509 }
2510
John McCallf871d0c2010-08-07 06:22:56 +00002511 CXXCastPath BasePath;
2512 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002513 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2514 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002515 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002516 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002517
Anders Carlssone5ef7402010-04-23 03:10:23 +00002518 InitializationKind InitKind
2519 = InitializationKind::CreateDirect(Constructor->getLocation(),
2520 SourceLocation(), SourceLocation());
2521 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2522 &CopyCtorArg, 1);
2523 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002524 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002525 break;
2526 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002527 }
John McCall9ae2f072010-08-23 23:25:46 +00002528
Douglas Gregor53c374f2010-12-07 00:41:46 +00002529 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002530 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002531 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002532
Anders Carlssondefefd22010-04-23 02:00:02 +00002533 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002534 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002535 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2536 SourceLocation()),
2537 BaseSpec->isVirtual(),
2538 SourceLocation(),
2539 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002540 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002541 SourceLocation());
2542
Anders Carlssondefefd22010-04-23 02:00:02 +00002543 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002544}
2545
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002546static bool RefersToRValueRef(Expr *MemRef) {
2547 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2548 return Referenced->getType()->isRValueReferenceType();
2549}
2550
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002551static bool
2552BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002553 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002554 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002555 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002556 if (Field->isInvalidDecl())
2557 return true;
2558
Chandler Carruthf186b542010-06-29 23:50:44 +00002559 SourceLocation Loc = Constructor->getLocation();
2560
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002561 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2562 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002563 ParmVarDecl *Param = Constructor->getParamDecl(0);
2564 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002565
2566 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002567 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2568 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002569
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002570 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002571 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002572 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002573 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002574
Eli Friedman5f2987c2012-02-02 03:46:19 +00002575 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2576
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002577 if (Moving) {
2578 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2579 }
2580
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002581 // Build a reference to this field within the parameter.
2582 CXXScopeSpec SS;
2583 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2584 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002585 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2586 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002587 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002588 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002589 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002590 ParamType, Loc,
2591 /*IsArrow=*/false,
2592 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002593 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002594 /*FirstQualifierInScope=*/0,
2595 MemberLookup,
2596 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002597 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002598 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002599
2600 // C++11 [class.copy]p15:
2601 // - if a member m has rvalue reference type T&&, it is direct-initialized
2602 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002603 if (RefersToRValueRef(CtorArg.get())) {
2604 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002605 }
2606
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002607 // When the field we are copying is an array, create index variables for
2608 // each dimension of the array. We use these index variables to subscript
2609 // the source array, and other clients (e.g., CodeGen) will perform the
2610 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002611 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002612 QualType BaseType = Field->getType();
2613 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002614 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002615 while (const ConstantArrayType *Array
2616 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002617 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002618 // Create the iteration variable for this array index.
2619 IdentifierInfo *IterationVarName = 0;
2620 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002621 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002622 llvm::raw_svector_ostream OS(Str);
2623 OS << "__i" << IndexVariables.size();
2624 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2625 }
2626 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002627 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002628 IterationVarName, SizeType,
2629 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002630 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002631 IndexVariables.push_back(IterationVar);
2632
2633 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002634 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002635 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002636 assert(!IterationVarRef.isInvalid() &&
2637 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002638 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2639 assert(!IterationVarRef.isInvalid() &&
2640 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002641
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002642 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002643 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002644 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002645 Loc);
2646 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002647 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002648
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002649 BaseType = Array->getElementType();
2650 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002651
2652 // The array subscript expression is an lvalue, which is wrong for moving.
2653 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002654 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002655
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002656 // Construct the entity that we will be initializing. For an array, this
2657 // will be first element in the array, which may require several levels
2658 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002659 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002660 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002661 if (Indirect)
2662 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2663 else
2664 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002665 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2666 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2667 0,
2668 Entities.back()));
2669
2670 // Direct-initialize to use the copy constructor.
2671 InitializationKind InitKind =
2672 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2673
Sebastian Redl74e611a2011-09-04 18:14:28 +00002674 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002675 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002676 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002677
John McCall60d7b3a2010-08-24 06:29:42 +00002678 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002679 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002680 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002681 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002682 if (MemberInit.isInvalid())
2683 return true;
2684
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002685 if (Indirect) {
2686 assert(IndexVariables.size() == 0 &&
2687 "Indirect field improperly initialized");
2688 CXXMemberInit
2689 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2690 Loc, Loc,
2691 MemberInit.takeAs<Expr>(),
2692 Loc);
2693 } else
2694 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2695 Loc, MemberInit.takeAs<Expr>(),
2696 Loc,
2697 IndexVariables.data(),
2698 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002699 return false;
2700 }
2701
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002702 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2703
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002704 QualType FieldBaseElementType =
2705 SemaRef.Context.getBaseElementType(Field->getType());
2706
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002707 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002708 InitializedEntity InitEntity
2709 = Indirect? InitializedEntity::InitializeMember(Indirect)
2710 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002711 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002712 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002713
2714 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002715 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002716 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002717
Douglas Gregor53c374f2010-12-07 00:41:46 +00002718 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002719 if (MemberInit.isInvalid())
2720 return true;
2721
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002722 if (Indirect)
2723 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2724 Indirect, Loc,
2725 Loc,
2726 MemberInit.get(),
2727 Loc);
2728 else
2729 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2730 Field, Loc, Loc,
2731 MemberInit.get(),
2732 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002733 return false;
2734 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002735
Sean Hunt1f2f3842011-05-17 00:19:05 +00002736 if (!Field->getParent()->isUnion()) {
2737 if (FieldBaseElementType->isReferenceType()) {
2738 SemaRef.Diag(Constructor->getLocation(),
2739 diag::err_uninitialized_member_in_ctor)
2740 << (int)Constructor->isImplicit()
2741 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2742 << 0 << Field->getDeclName();
2743 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2744 return true;
2745 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002746
Sean Hunt1f2f3842011-05-17 00:19:05 +00002747 if (FieldBaseElementType.isConstQualified()) {
2748 SemaRef.Diag(Constructor->getLocation(),
2749 diag::err_uninitialized_member_in_ctor)
2750 << (int)Constructor->isImplicit()
2751 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2752 << 1 << Field->getDeclName();
2753 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2754 return true;
2755 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002756 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002757
David Blaikie4e4d0842012-03-11 07:00:24 +00002758 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002759 FieldBaseElementType->isObjCRetainableType() &&
2760 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2761 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002762 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002763 // Default-initialize Objective-C pointers to NULL.
2764 CXXMemberInit
2765 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2766 Loc, Loc,
2767 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2768 Loc);
2769 return false;
2770 }
2771
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002772 // Nothing to initialize.
2773 CXXMemberInit = 0;
2774 return false;
2775}
John McCallf1860e52010-05-20 23:23:51 +00002776
2777namespace {
2778struct BaseAndFieldInfo {
2779 Sema &S;
2780 CXXConstructorDecl *Ctor;
2781 bool AnyErrorsInInits;
2782 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002783 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002784 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002785
2786 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2787 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002788 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2789 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002790 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002791 else if (Generated && Ctor->isMoveConstructor())
2792 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002793 else
2794 IIK = IIK_Default;
2795 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002796
2797 bool isImplicitCopyOrMove() const {
2798 switch (IIK) {
2799 case IIK_Copy:
2800 case IIK_Move:
2801 return true;
2802
2803 case IIK_Default:
2804 return false;
2805 }
David Blaikie30263482012-01-20 21:50:17 +00002806
2807 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002808 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002809
2810 bool addFieldInitializer(CXXCtorInitializer *Init) {
2811 AllToInit.push_back(Init);
2812
2813 // Check whether this initializer makes the field "used".
2814 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2815 S.UnusedPrivateFields.remove(Init->getAnyMember());
2816
2817 return false;
2818 }
John McCallf1860e52010-05-20 23:23:51 +00002819};
2820}
2821
Richard Smitha4950662011-09-19 13:34:43 +00002822/// \brief Determine whether the given indirect field declaration is somewhere
2823/// within an anonymous union.
2824static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2825 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2826 CEnd = F->chain_end();
2827 C != CEnd; ++C)
2828 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2829 if (Record->isUnion())
2830 return true;
2831
2832 return false;
2833}
2834
Douglas Gregorddb21472011-11-02 23:04:16 +00002835/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2836/// array type.
2837static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2838 if (T->isIncompleteArrayType())
2839 return true;
2840
2841 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2842 if (!ArrayT->getSize())
2843 return true;
2844
2845 T = ArrayT->getElementType();
2846 }
2847
2848 return false;
2849}
2850
Richard Smith7a614d82011-06-11 17:19:42 +00002851static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002852 FieldDecl *Field,
2853 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002854
Chandler Carruthe861c602010-06-30 02:59:29 +00002855 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00002856 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2857 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002858
Richard Smith0b8220a2012-08-07 21:30:42 +00002859 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00002860 // has a brace-or-equal-initializer, the entity is initialized as specified
2861 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002862 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002863 CXXCtorInitializer *Init;
2864 if (Indirect)
2865 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2866 SourceLocation(),
2867 SourceLocation(), 0,
2868 SourceLocation());
2869 else
2870 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2871 SourceLocation(),
2872 SourceLocation(), 0,
2873 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00002874 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002875 }
2876
Richard Smithc115f632011-09-18 11:14:50 +00002877 // Don't build an implicit initializer for union members if none was
2878 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002879 if (Field->getParent()->isUnion() ||
2880 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002881 return false;
2882
Douglas Gregorddb21472011-11-02 23:04:16 +00002883 // Don't initialize incomplete or zero-length arrays.
2884 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2885 return false;
2886
John McCallf1860e52010-05-20 23:23:51 +00002887 // Don't try to build an implicit initializer if there were semantic
2888 // errors in any of the initializers (and therefore we might be
2889 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002890 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002891 return false;
2892
Sean Huntcbb67482011-01-08 20:30:50 +00002893 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002894 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2895 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002896 return true;
John McCallf1860e52010-05-20 23:23:51 +00002897
Richard Smith0b8220a2012-08-07 21:30:42 +00002898 if (!Init)
2899 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00002900
Richard Smith0b8220a2012-08-07 21:30:42 +00002901 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002902}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002903
2904bool
2905Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2906 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002907 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002908 Constructor->setNumCtorInitializers(1);
2909 CXXCtorInitializer **initializer =
2910 new (Context) CXXCtorInitializer*[1];
2911 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2912 Constructor->setCtorInitializers(initializer);
2913
Sean Huntb76af9c2011-05-03 23:05:34 +00002914 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002915 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002916 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2917 }
2918
Sean Huntc1598702011-05-05 00:05:47 +00002919 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002920
Sean Hunt059ce0d2011-05-01 07:04:31 +00002921 return false;
2922}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002923
John McCallb77115d2011-06-17 00:18:42 +00002924bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2925 CXXCtorInitializer **Initializers,
2926 unsigned NumInitializers,
2927 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002928 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002929 // Just store the initializers as written, they will be checked during
2930 // instantiation.
2931 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002932 Constructor->setNumCtorInitializers(NumInitializers);
2933 CXXCtorInitializer **baseOrMemberInitializers =
2934 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002935 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002936 NumInitializers * sizeof(CXXCtorInitializer*));
2937 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002938 }
2939
2940 return false;
2941 }
2942
John McCallf1860e52010-05-20 23:23:51 +00002943 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002944
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002945 // We need to build the initializer AST according to order of construction
2946 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002947 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002948 if (!ClassDecl)
2949 return true;
2950
Eli Friedman80c30da2009-11-09 19:20:36 +00002951 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002952
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002953 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002954 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002955
2956 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002957 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002958 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002959 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002960 }
2961
Anders Carlsson711f34a2010-04-21 19:52:01 +00002962 // Keep track of the direct virtual bases.
2963 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2964 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2965 E = ClassDecl->bases_end(); I != E; ++I) {
2966 if (I->isVirtual())
2967 DirectVBases.insert(I);
2968 }
2969
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002970 // Push virtual bases before others.
2971 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2972 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2973
Sean Huntcbb67482011-01-08 20:30:50 +00002974 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002975 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2976 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002977 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002978 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002979 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002980 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002981 VBase, IsInheritedVirtualBase,
2982 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002983 HadError = true;
2984 continue;
2985 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002986
John McCallf1860e52010-05-20 23:23:51 +00002987 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002988 }
2989 }
Mike Stump1eb44332009-09-09 15:08:12 +00002990
John McCallf1860e52010-05-20 23:23:51 +00002991 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002992 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2993 E = ClassDecl->bases_end(); Base != E; ++Base) {
2994 // Virtuals are in the virtual base list and already constructed.
2995 if (Base->isVirtual())
2996 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002997
Sean Huntcbb67482011-01-08 20:30:50 +00002998 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002999 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3000 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003001 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003002 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003003 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003004 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003005 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003006 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003007 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003008 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003009
John McCallf1860e52010-05-20 23:23:51 +00003010 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003011 }
3012 }
Mike Stump1eb44332009-09-09 15:08:12 +00003013
John McCallf1860e52010-05-20 23:23:51 +00003014 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003015 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3016 MemEnd = ClassDecl->decls_end();
3017 Mem != MemEnd; ++Mem) {
3018 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003019 // C++ [class.bit]p2:
3020 // A declaration for a bit-field that omits the identifier declares an
3021 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3022 // initialized.
3023 if (F->isUnnamedBitfield())
3024 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003025
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003026 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003027 // handle anonymous struct/union fields based on their individual
3028 // indirect fields.
3029 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3030 continue;
3031
3032 if (CollectFieldInitializer(*this, Info, F))
3033 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003034 continue;
3035 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003036
3037 // Beyond this point, we only consider default initialization.
3038 if (Info.IIK != IIK_Default)
3039 continue;
3040
3041 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3042 if (F->getType()->isIncompleteArrayType()) {
3043 assert(ClassDecl->hasFlexibleArrayMember() &&
3044 "Incomplete array type is not valid");
3045 continue;
3046 }
3047
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003048 // Initialize each field of an anonymous struct individually.
3049 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3050 HadError = true;
3051
3052 continue;
3053 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003054 }
Mike Stump1eb44332009-09-09 15:08:12 +00003055
John McCallf1860e52010-05-20 23:23:51 +00003056 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003057 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003058 Constructor->setNumCtorInitializers(NumInitializers);
3059 CXXCtorInitializer **baseOrMemberInitializers =
3060 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003061 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003062 NumInitializers * sizeof(CXXCtorInitializer*));
3063 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003064
John McCallef027fe2010-03-16 21:39:52 +00003065 // Constructors implicitly reference the base and member
3066 // destructors.
3067 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3068 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003069 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003070
3071 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003072}
3073
Eli Friedman6347f422009-07-21 19:28:10 +00003074static void *GetKeyForTopLevelField(FieldDecl *Field) {
3075 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003076 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003077 if (RT->getDecl()->isAnonymousStructOrUnion())
3078 return static_cast<void *>(RT->getDecl());
3079 }
3080 return static_cast<void *>(Field);
3081}
3082
Anders Carlssonea356fb2010-04-02 05:42:15 +00003083static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003084 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003085}
3086
Anders Carlssonea356fb2010-04-02 05:42:15 +00003087static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003088 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003089 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003090 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003091
Eli Friedman6347f422009-07-21 19:28:10 +00003092 // For fields injected into the class via declaration of an anonymous union,
3093 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003094 FieldDecl *Field = Member->getAnyMember();
3095
John McCall3c3ccdb2010-04-10 09:28:51 +00003096 // If the field is a member of an anonymous struct or union, our key
3097 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003098 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003099 if (RD->isAnonymousStructOrUnion()) {
3100 while (true) {
3101 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3102 if (Parent->isAnonymousStructOrUnion())
3103 RD = Parent;
3104 else
3105 break;
3106 }
3107
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003108 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003109 }
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003111 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003112}
3113
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003114static void
3115DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003116 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003117 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003118 unsigned NumInits) {
3119 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003120 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003121
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003122 // Don't check initializers order unless the warning is enabled at the
3123 // location of at least one initializer.
3124 bool ShouldCheckOrder = false;
3125 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003126 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003127 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3128 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003129 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003130 ShouldCheckOrder = true;
3131 break;
3132 }
3133 }
3134 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003135 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003136
John McCalld6ca8da2010-04-10 07:37:23 +00003137 // Build the list of bases and members in the order that they'll
3138 // actually be initialized. The explicit initializers should be in
3139 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003140 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Anders Carlsson071d6102010-04-02 03:38:04 +00003142 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3143
John McCalld6ca8da2010-04-10 07:37:23 +00003144 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003145 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003146 ClassDecl->vbases_begin(),
3147 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003148 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003149
John McCalld6ca8da2010-04-10 07:37:23 +00003150 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003151 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003152 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003153 if (Base->isVirtual())
3154 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003155 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003156 }
Mike Stump1eb44332009-09-09 15:08:12 +00003157
John McCalld6ca8da2010-04-10 07:37:23 +00003158 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003159 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003160 E = ClassDecl->field_end(); Field != E; ++Field) {
3161 if (Field->isUnnamedBitfield())
3162 continue;
3163
David Blaikie581deb32012-06-06 20:45:41 +00003164 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003165 }
3166
John McCalld6ca8da2010-04-10 07:37:23 +00003167 unsigned NumIdealInits = IdealInitKeys.size();
3168 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003169
Sean Huntcbb67482011-01-08 20:30:50 +00003170 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003171 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003172 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003173 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003174
3175 // Scan forward to try to find this initializer in the idealized
3176 // initializers list.
3177 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3178 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003179 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003180
3181 // If we didn't find this initializer, it must be because we
3182 // scanned past it on a previous iteration. That can only
3183 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003184 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003185 Sema::SemaDiagnosticBuilder D =
3186 SemaRef.Diag(PrevInit->getSourceLocation(),
3187 diag::warn_initializer_out_of_order);
3188
Francois Pichet00eb3f92010-12-04 09:14:42 +00003189 if (PrevInit->isAnyMemberInitializer())
3190 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003191 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003192 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003193
Francois Pichet00eb3f92010-12-04 09:14:42 +00003194 if (Init->isAnyMemberInitializer())
3195 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003196 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003197 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003198
3199 // Move back to the initializer's location in the ideal list.
3200 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3201 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003202 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003203
3204 assert(IdealIndex != NumIdealInits &&
3205 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003206 }
John McCalld6ca8da2010-04-10 07:37:23 +00003207
3208 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003209 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003210}
3211
John McCall3c3ccdb2010-04-10 09:28:51 +00003212namespace {
3213bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003214 CXXCtorInitializer *Init,
3215 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003216 if (!PrevInit) {
3217 PrevInit = Init;
3218 return false;
3219 }
3220
3221 if (FieldDecl *Field = Init->getMember())
3222 S.Diag(Init->getSourceLocation(),
3223 diag::err_multiple_mem_initialization)
3224 << Field->getDeclName()
3225 << Init->getSourceRange();
3226 else {
John McCallf4c73712011-01-19 06:33:43 +00003227 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003228 assert(BaseClass && "neither field nor base");
3229 S.Diag(Init->getSourceLocation(),
3230 diag::err_multiple_base_initialization)
3231 << QualType(BaseClass, 0)
3232 << Init->getSourceRange();
3233 }
3234 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3235 << 0 << PrevInit->getSourceRange();
3236
3237 return true;
3238}
3239
Sean Huntcbb67482011-01-08 20:30:50 +00003240typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003241typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3242
3243bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003244 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003245 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003246 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003247 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003248 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003249
3250 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003251 if (Parent->isUnion()) {
3252 UnionEntry &En = Unions[Parent];
3253 if (En.first && En.first != Child) {
3254 S.Diag(Init->getSourceLocation(),
3255 diag::err_multiple_mem_union_initialization)
3256 << Field->getDeclName()
3257 << Init->getSourceRange();
3258 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3259 << 0 << En.second->getSourceRange();
3260 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003261 }
3262 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003263 En.first = Child;
3264 En.second = Init;
3265 }
David Blaikie6fe29652011-11-17 06:01:57 +00003266 if (!Parent->isAnonymousStructOrUnion())
3267 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003268 }
3269
3270 Child = Parent;
3271 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003272 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003273
3274 return false;
3275}
3276}
3277
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003278/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003279void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003280 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003281 CXXCtorInitializer **meminits,
3282 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003283 bool AnyErrors) {
3284 if (!ConstructorDecl)
3285 return;
3286
3287 AdjustDeclIfTemplate(ConstructorDecl);
3288
3289 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003290 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003291
3292 if (!Constructor) {
3293 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3294 return;
3295 }
3296
Sean Huntcbb67482011-01-08 20:30:50 +00003297 CXXCtorInitializer **MemInits =
3298 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003299
3300 // Mapping for the duplicate initializers check.
3301 // For member initializers, this is keyed with a FieldDecl*.
3302 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003303 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003304
3305 // Mapping for the inconsistent anonymous-union initializers check.
3306 RedundantUnionMap MemberUnions;
3307
Anders Carlssonea356fb2010-04-02 05:42:15 +00003308 bool HadError = false;
3309 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003310 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003311
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003312 // Set the source order index.
3313 Init->setSourceOrder(i);
3314
Francois Pichet00eb3f92010-12-04 09:14:42 +00003315 if (Init->isAnyMemberInitializer()) {
3316 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003317 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3318 CheckRedundantUnionInit(*this, Init, MemberUnions))
3319 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003320 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003321 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3322 if (CheckRedundantInit(*this, Init, Members[Key]))
3323 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003324 } else {
3325 assert(Init->isDelegatingInitializer());
3326 // This must be the only initializer
3327 if (i != 0 || NumMemInits > 1) {
3328 Diag(MemInits[0]->getSourceLocation(),
3329 diag::err_delegating_initializer_alone)
3330 << MemInits[0]->getSourceRange();
3331 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003332 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003333 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003334 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003335 // Return immediately as the initializer is set.
3336 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003337 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003338 }
3339
Anders Carlssonea356fb2010-04-02 05:42:15 +00003340 if (HadError)
3341 return;
3342
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003343 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003344
Sean Huntcbb67482011-01-08 20:30:50 +00003345 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003346}
3347
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003348void
John McCallef027fe2010-03-16 21:39:52 +00003349Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3350 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003351 // Ignore dependent contexts. Also ignore unions, since their members never
3352 // have destructors implicitly called.
3353 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003354 return;
John McCall58e6f342010-03-16 05:22:47 +00003355
3356 // FIXME: all the access-control diagnostics are positioned on the
3357 // field/base declaration. That's probably good; that said, the
3358 // user might reasonably want to know why the destructor is being
3359 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003360
Anders Carlsson9f853df2009-11-17 04:44:12 +00003361 // Non-static data members.
3362 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3363 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003364 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003365 if (Field->isInvalidDecl())
3366 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003367
3368 // Don't destroy incomplete or zero-length arrays.
3369 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3370 continue;
3371
Anders Carlsson9f853df2009-11-17 04:44:12 +00003372 QualType FieldType = Context.getBaseElementType(Field->getType());
3373
3374 const RecordType* RT = FieldType->getAs<RecordType>();
3375 if (!RT)
3376 continue;
3377
3378 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003379 if (FieldClassDecl->isInvalidDecl())
3380 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003381 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003382 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003383 // The destructor for an implicit anonymous union member is never invoked.
3384 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3385 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003386
Douglas Gregordb89f282010-07-01 22:47:18 +00003387 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003388 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003389 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003390 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003391 << Field->getDeclName()
3392 << FieldType);
3393
Eli Friedman5f2987c2012-02-02 03:46:19 +00003394 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003395 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003396 }
3397
John McCall58e6f342010-03-16 05:22:47 +00003398 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3399
Anders Carlsson9f853df2009-11-17 04:44:12 +00003400 // Bases.
3401 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3402 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003403 // Bases are always records in a well-formed non-dependent class.
3404 const RecordType *RT = Base->getType()->getAs<RecordType>();
3405
3406 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003407 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003408 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003409
John McCall58e6f342010-03-16 05:22:47 +00003410 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003411 // If our base class is invalid, we probably can't get its dtor anyway.
3412 if (BaseClassDecl->isInvalidDecl())
3413 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003414 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003415 continue;
John McCall58e6f342010-03-16 05:22:47 +00003416
Douglas Gregordb89f282010-07-01 22:47:18 +00003417 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003418 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003419
3420 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003421 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003422 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003423 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003424 << Base->getSourceRange(),
3425 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003426
Eli Friedman5f2987c2012-02-02 03:46:19 +00003427 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003428 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003429 }
3430
3431 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003432 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3433 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003434
3435 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003436 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003437
3438 // Ignore direct virtual bases.
3439 if (DirectVirtualBases.count(RT))
3440 continue;
3441
John McCall58e6f342010-03-16 05:22:47 +00003442 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003443 // If our base class is invalid, we probably can't get its dtor anyway.
3444 if (BaseClassDecl->isInvalidDecl())
3445 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003446 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003447 continue;
John McCall58e6f342010-03-16 05:22:47 +00003448
Douglas Gregordb89f282010-07-01 22:47:18 +00003449 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003450 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003451 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003452 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003453 << VBase->getType(),
3454 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003455
Eli Friedman5f2987c2012-02-02 03:46:19 +00003456 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003457 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003458 }
3459}
3460
John McCalld226f652010-08-21 09:40:31 +00003461void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003462 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003463 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Mike Stump1eb44332009-09-09 15:08:12 +00003465 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003466 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003467 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003468}
3469
Mike Stump1eb44332009-09-09 15:08:12 +00003470bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003471 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003472 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3473 unsigned DiagID;
3474 AbstractDiagSelID SelID;
3475
3476 public:
3477 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3478 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3479
3480 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3481 if (SelID == -1)
3482 S.Diag(Loc, DiagID) << T;
3483 else
3484 S.Diag(Loc, DiagID) << SelID << T;
3485 }
3486 } Diagnoser(DiagID, SelID);
3487
3488 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003489}
3490
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003491bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003492 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003493 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003494 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003495
Anders Carlsson11f21a02009-03-23 19:10:31 +00003496 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003497 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003498
Ted Kremenek6217b802009-07-29 21:53:49 +00003499 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003500 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003501 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003502 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003504 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003505 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003506 }
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Ted Kremenek6217b802009-07-29 21:53:49 +00003508 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003509 if (!RT)
3510 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003511
John McCall86ff3082010-02-04 22:26:26 +00003512 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003513
John McCall94c3b562010-08-18 09:41:07 +00003514 // We can't answer whether something is abstract until it has a
3515 // definition. If it's currently being defined, we'll walk back
3516 // over all the declarations when we have a full definition.
3517 const CXXRecordDecl *Def = RD->getDefinition();
3518 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003519 return false;
3520
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003521 if (!RD->isAbstract())
3522 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003523
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003524 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003525 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003526
John McCall94c3b562010-08-18 09:41:07 +00003527 return true;
3528}
3529
3530void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3531 // Check if we've already emitted the list of pure virtual functions
3532 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003533 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003534 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003535
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003536 CXXFinalOverriderMap FinalOverriders;
3537 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003538
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003539 // Keep a set of seen pure methods so we won't diagnose the same method
3540 // more than once.
3541 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3542
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003543 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3544 MEnd = FinalOverriders.end();
3545 M != MEnd;
3546 ++M) {
3547 for (OverridingMethods::iterator SO = M->second.begin(),
3548 SOEnd = M->second.end();
3549 SO != SOEnd; ++SO) {
3550 // C++ [class.abstract]p4:
3551 // A class is abstract if it contains or inherits at least one
3552 // pure virtual function for which the final overrider is pure
3553 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003554
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003555 //
3556 if (SO->second.size() != 1)
3557 continue;
3558
3559 if (!SO->second.front().Method->isPure())
3560 continue;
3561
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003562 if (!SeenPureMethods.insert(SO->second.front().Method))
3563 continue;
3564
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003565 Diag(SO->second.front().Method->getLocation(),
3566 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003567 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003568 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003569 }
3570
3571 if (!PureVirtualClassDiagSet)
3572 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3573 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003574}
3575
Anders Carlsson8211eff2009-03-24 01:19:16 +00003576namespace {
John McCall94c3b562010-08-18 09:41:07 +00003577struct AbstractUsageInfo {
3578 Sema &S;
3579 CXXRecordDecl *Record;
3580 CanQualType AbstractType;
3581 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003582
John McCall94c3b562010-08-18 09:41:07 +00003583 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3584 : S(S), Record(Record),
3585 AbstractType(S.Context.getCanonicalType(
3586 S.Context.getTypeDeclType(Record))),
3587 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003588
John McCall94c3b562010-08-18 09:41:07 +00003589 void DiagnoseAbstractType() {
3590 if (Invalid) return;
3591 S.DiagnoseAbstractType(Record);
3592 Invalid = true;
3593 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003594
John McCall94c3b562010-08-18 09:41:07 +00003595 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3596};
3597
3598struct CheckAbstractUsage {
3599 AbstractUsageInfo &Info;
3600 const NamedDecl *Ctx;
3601
3602 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3603 : Info(Info), Ctx(Ctx) {}
3604
3605 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3606 switch (TL.getTypeLocClass()) {
3607#define ABSTRACT_TYPELOC(CLASS, PARENT)
3608#define TYPELOC(CLASS, PARENT) \
3609 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3610#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003611 }
John McCall94c3b562010-08-18 09:41:07 +00003612 }
Mike Stump1eb44332009-09-09 15:08:12 +00003613
John McCall94c3b562010-08-18 09:41:07 +00003614 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3615 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3616 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003617 if (!TL.getArg(I))
3618 continue;
3619
John McCall94c3b562010-08-18 09:41:07 +00003620 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3621 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003622 }
John McCall94c3b562010-08-18 09:41:07 +00003623 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003624
John McCall94c3b562010-08-18 09:41:07 +00003625 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3626 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3627 }
Mike Stump1eb44332009-09-09 15:08:12 +00003628
John McCall94c3b562010-08-18 09:41:07 +00003629 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3630 // Visit the type parameters from a permissive context.
3631 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3632 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3633 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3634 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3635 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3636 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003637 }
John McCall94c3b562010-08-18 09:41:07 +00003638 }
Mike Stump1eb44332009-09-09 15:08:12 +00003639
John McCall94c3b562010-08-18 09:41:07 +00003640 // Visit pointee types from a permissive context.
3641#define CheckPolymorphic(Type) \
3642 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3643 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3644 }
3645 CheckPolymorphic(PointerTypeLoc)
3646 CheckPolymorphic(ReferenceTypeLoc)
3647 CheckPolymorphic(MemberPointerTypeLoc)
3648 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003649 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003650
John McCall94c3b562010-08-18 09:41:07 +00003651 /// Handle all the types we haven't given a more specific
3652 /// implementation for above.
3653 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3654 // Every other kind of type that we haven't called out already
3655 // that has an inner type is either (1) sugar or (2) contains that
3656 // inner type in some way as a subobject.
3657 if (TypeLoc Next = TL.getNextTypeLoc())
3658 return Visit(Next, Sel);
3659
3660 // If there's no inner type and we're in a permissive context,
3661 // don't diagnose.
3662 if (Sel == Sema::AbstractNone) return;
3663
3664 // Check whether the type matches the abstract type.
3665 QualType T = TL.getType();
3666 if (T->isArrayType()) {
3667 Sel = Sema::AbstractArrayType;
3668 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003669 }
John McCall94c3b562010-08-18 09:41:07 +00003670 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3671 if (CT != Info.AbstractType) return;
3672
3673 // It matched; do some magic.
3674 if (Sel == Sema::AbstractArrayType) {
3675 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3676 << T << TL.getSourceRange();
3677 } else {
3678 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3679 << Sel << T << TL.getSourceRange();
3680 }
3681 Info.DiagnoseAbstractType();
3682 }
3683};
3684
3685void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3686 Sema::AbstractDiagSelID Sel) {
3687 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3688}
3689
3690}
3691
3692/// Check for invalid uses of an abstract type in a method declaration.
3693static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3694 CXXMethodDecl *MD) {
3695 // No need to do the check on definitions, which require that
3696 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003697 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003698 return;
3699
3700 // For safety's sake, just ignore it if we don't have type source
3701 // information. This should never happen for non-implicit methods,
3702 // but...
3703 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3704 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3705}
3706
3707/// Check for invalid uses of an abstract type within a class definition.
3708static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3709 CXXRecordDecl *RD) {
3710 for (CXXRecordDecl::decl_iterator
3711 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3712 Decl *D = *I;
3713 if (D->isImplicit()) continue;
3714
3715 // Methods and method templates.
3716 if (isa<CXXMethodDecl>(D)) {
3717 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3718 } else if (isa<FunctionTemplateDecl>(D)) {
3719 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3720 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3721
3722 // Fields and static variables.
3723 } else if (isa<FieldDecl>(D)) {
3724 FieldDecl *FD = cast<FieldDecl>(D);
3725 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3726 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3727 } else if (isa<VarDecl>(D)) {
3728 VarDecl *VD = cast<VarDecl>(D);
3729 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3730 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3731
3732 // Nested classes and class templates.
3733 } else if (isa<CXXRecordDecl>(D)) {
3734 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3735 } else if (isa<ClassTemplateDecl>(D)) {
3736 CheckAbstractClassUsage(Info,
3737 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3738 }
3739 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003740}
3741
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003742/// \brief Perform semantic checks on a class definition that has been
3743/// completing, introducing implicitly-declared members, checking for
3744/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003745void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003746 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003747 return;
3748
John McCall94c3b562010-08-18 09:41:07 +00003749 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3750 AbstractUsageInfo Info(*this, Record);
3751 CheckAbstractClassUsage(Info, Record);
3752 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003753
3754 // If this is not an aggregate type and has no user-declared constructor,
3755 // complain about any non-static data members of reference or const scalar
3756 // type, since they will never get initializers.
3757 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003758 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3759 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003760 bool Complained = false;
3761 for (RecordDecl::field_iterator F = Record->field_begin(),
3762 FEnd = Record->field_end();
3763 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003764 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003765 continue;
3766
Douglas Gregor325e5932010-04-15 00:00:53 +00003767 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003768 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003769 if (!Complained) {
3770 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3771 << Record->getTagKind() << Record;
3772 Complained = true;
3773 }
3774
3775 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3776 << F->getType()->isReferenceType()
3777 << F->getDeclName();
3778 }
3779 }
3780 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003781
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003782 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003783 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003784
3785 if (Record->getIdentifier()) {
3786 // C++ [class.mem]p13:
3787 // If T is the name of a class, then each of the following shall have a
3788 // name different from T:
3789 // - every member of every anonymous union that is a member of class T.
3790 //
3791 // C++ [class.mem]p14:
3792 // In addition, if class T has a user-declared constructor (12.1), every
3793 // non-static data member of class T shall have a name different from T.
3794 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003795 R.first != R.second; ++R.first) {
3796 NamedDecl *D = *R.first;
3797 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3798 isa<IndirectFieldDecl>(D)) {
3799 Diag(D->getLocation(), diag::err_member_name_of_class)
3800 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003801 break;
3802 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003803 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003804 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003805
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003806 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003807 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003808 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003809 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003810 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3811 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3812 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003813
3814 // See if a method overloads virtual methods in a base
3815 /// class without overriding any.
3816 if (!Record->isDependentType()) {
3817 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3818 MEnd = Record->method_end();
3819 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003820 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003821 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003822 }
3823 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003824
Richard Smith9f569cc2011-10-01 02:31:28 +00003825 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3826 // function that is not a constructor declares that member function to be
3827 // const. [...] The class of which that function is a member shall be
3828 // a literal type.
3829 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003830 // If the class has virtual bases, any constexpr members will already have
3831 // been diagnosed by the checks performed on the member declaration, so
3832 // suppress this (less useful) diagnostic.
3833 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3834 !Record->isLiteral() && !Record->getNumVBases()) {
3835 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3836 MEnd = Record->method_end();
3837 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003838 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003839 switch (Record->getTemplateSpecializationKind()) {
3840 case TSK_ImplicitInstantiation:
3841 case TSK_ExplicitInstantiationDeclaration:
3842 case TSK_ExplicitInstantiationDefinition:
3843 // If a template instantiates to a non-literal type, but its members
3844 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003845 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003846 continue;
3847
3848 case TSK_Undeclared:
3849 case TSK_ExplicitSpecialization:
David Blaikie262bc182012-04-30 02:36:29 +00003850 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
Douglas Gregorf502d8e2012-05-04 16:48:41 +00003851 diag::err_constexpr_method_non_literal);
Richard Smith9f569cc2011-10-01 02:31:28 +00003852 break;
3853 }
3854
3855 // Only produce one error per class.
3856 break;
3857 }
3858 }
3859 }
3860
Sebastian Redlf677ea32011-02-05 19:23:19 +00003861 // Declare inherited constructors. We do this eagerly here because:
3862 // - The standard requires an eager diagnostic for conflicting inherited
3863 // constructors from different classes.
3864 // - The lazy declaration of the other implicit constructors is so as to not
3865 // waste space and performance on classes that are not meant to be
3866 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3867 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003868 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003869}
3870
3871void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003872 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3873 ME = Record->method_end();
Richard Smith3003e1d2012-05-15 04:39:51 +00003874 MI != ME; ++MI)
3875 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00003876 CheckExplicitlyDefaultedSpecialMember(*MI);
Sean Hunt001cad92011-05-10 00:49:42 +00003877}
3878
Richard Smith7756afa2012-06-10 05:43:50 +00003879/// Is the special member function which would be selected to perform the
3880/// specified operation on the specified class type a constexpr constructor?
3881static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3882 Sema::CXXSpecialMember CSM,
3883 bool ConstArg) {
3884 Sema::SpecialMemberOverloadResult *SMOR =
3885 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3886 false, false, false, false);
3887 if (!SMOR || !SMOR->getMethod())
3888 // A constructor we wouldn't select can't be "involved in initializing"
3889 // anything.
3890 return true;
3891 return SMOR->getMethod()->isConstexpr();
3892}
3893
3894/// Determine whether the specified special member function would be constexpr
3895/// if it were implicitly defined.
3896static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3897 Sema::CXXSpecialMember CSM,
3898 bool ConstArg) {
3899 if (!S.getLangOpts().CPlusPlus0x)
3900 return false;
3901
3902 // C++11 [dcl.constexpr]p4:
3903 // In the definition of a constexpr constructor [...]
3904 switch (CSM) {
3905 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003906 // Since default constructor lookup is essentially trivial (and cannot
3907 // involve, for instance, template instantiation), we compute whether a
3908 // defaulted default constructor is constexpr directly within CXXRecordDecl.
3909 //
3910 // This is important for performance; we need to know whether the default
3911 // constructor is constexpr to determine whether the type is a literal type.
3912 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3913
Richard Smith7756afa2012-06-10 05:43:50 +00003914 case Sema::CXXCopyConstructor:
3915 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003916 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00003917 break;
3918
3919 case Sema::CXXCopyAssignment:
3920 case Sema::CXXMoveAssignment:
3921 case Sema::CXXDestructor:
3922 case Sema::CXXInvalid:
3923 return false;
3924 }
3925
3926 // -- if the class is a non-empty union, or for each non-empty anonymous
3927 // union member of a non-union class, exactly one non-static data member
3928 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00003929 //
3930 // If we squint, this is guaranteed, since exactly one non-static data member
3931 // will be initialized (if the constructor isn't deleted), we just don't know
3932 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00003933 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00003934 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00003935
3936 // -- the class shall not have any virtual base classes;
3937 if (ClassDecl->getNumVBases())
3938 return false;
3939
3940 // -- every constructor involved in initializing [...] base class
3941 // sub-objects shall be a constexpr constructor;
3942 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3943 BEnd = ClassDecl->bases_end();
3944 B != BEnd; ++B) {
3945 const RecordType *BaseType = B->getType()->getAs<RecordType>();
3946 if (!BaseType) continue;
3947
3948 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3949 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3950 return false;
3951 }
3952
3953 // -- every constructor involved in initializing non-static data members
3954 // [...] shall be a constexpr constructor;
3955 // -- every non-static data member and base class sub-object shall be
3956 // initialized
3957 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3958 FEnd = ClassDecl->field_end();
3959 F != FEnd; ++F) {
3960 if (F->isInvalidDecl())
3961 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00003962 if (const RecordType *RecordTy =
3963 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00003964 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3965 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3966 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00003967 }
3968 }
3969
3970 // All OK, it's constexpr!
3971 return true;
3972}
3973
Richard Smithb9d0b762012-07-27 04:22:15 +00003974static Sema::ImplicitExceptionSpecification
3975computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
3976 switch (S.getSpecialMember(MD)) {
3977 case Sema::CXXDefaultConstructor:
3978 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
3979 case Sema::CXXCopyConstructor:
3980 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
3981 case Sema::CXXCopyAssignment:
3982 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
3983 case Sema::CXXMoveConstructor:
3984 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
3985 case Sema::CXXMoveAssignment:
3986 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
3987 case Sema::CXXDestructor:
3988 return S.ComputeDefaultedDtorExceptionSpec(MD);
3989 case Sema::CXXInvalid:
3990 break;
3991 }
3992 llvm_unreachable("only special members have implicit exception specs");
3993}
3994
Richard Smithdd25e802012-07-30 23:48:14 +00003995static void
3996updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
3997 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
3998 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3999 ExceptSpec.getEPI(EPI);
4000 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4001 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4002 FPT->getNumArgs(), EPI));
4003 FD->setType(QualType(NewFPT, 0));
4004}
4005
Richard Smithb9d0b762012-07-27 04:22:15 +00004006void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4007 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4008 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4009 return;
4010
Richard Smithdd25e802012-07-30 23:48:14 +00004011 // Evaluate the exception specification.
4012 ImplicitExceptionSpecification ExceptSpec =
4013 computeImplicitExceptionSpec(*this, Loc, MD);
4014
4015 // Update the type of the special member to use it.
4016 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4017
4018 // A user-provided destructor can be defined outside the class. When that
4019 // happens, be sure to update the exception specification on both
4020 // declarations.
4021 const FunctionProtoType *CanonicalFPT =
4022 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4023 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4024 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4025 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004026}
4027
4028static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4029static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4030
Richard Smith3003e1d2012-05-15 04:39:51 +00004031void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4032 CXXRecordDecl *RD = MD->getParent();
4033 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004034
Richard Smith3003e1d2012-05-15 04:39:51 +00004035 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4036 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004037
4038 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004039 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004040 bool First = MD == MD->getCanonicalDecl();
4041
4042 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004043
4044 // C++11 [dcl.fct.def.default]p1:
4045 // A function that is explicitly defaulted shall
4046 // -- be a special member function (checked elsewhere),
4047 // -- have the same type (except for ref-qualifiers, and except that a
4048 // copy operation can take a non-const reference) as an implicit
4049 // declaration, and
4050 // -- not have default arguments.
4051 unsigned ExpectedParams = 1;
4052 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4053 ExpectedParams = 0;
4054 if (MD->getNumParams() != ExpectedParams) {
4055 // This also checks for default arguments: a copy or move constructor with a
4056 // default argument is classified as a default constructor, and assignment
4057 // operations and destructors can't have default arguments.
4058 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4059 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004060 HadError = true;
4061 }
4062
Richard Smith3003e1d2012-05-15 04:39:51 +00004063 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004064
Richard Smithb9d0b762012-07-27 04:22:15 +00004065 // Compute argument constness, constexpr, and triviality.
Richard Smith7756afa2012-06-10 05:43:50 +00004066 bool CanHaveConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004067 bool Trivial;
4068 switch (CSM) {
4069 case CXXDefaultConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004070 Trivial = RD->hasTrivialDefaultConstructor();
4071 break;
4072 case CXXCopyConstructor:
Richard Smithb9d0b762012-07-27 04:22:15 +00004073 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004074 Trivial = RD->hasTrivialCopyConstructor();
4075 break;
4076 case CXXCopyAssignment:
Richard Smithb9d0b762012-07-27 04:22:15 +00004077 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004078 Trivial = RD->hasTrivialCopyAssignment();
4079 break;
4080 case CXXMoveConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004081 Trivial = RD->hasTrivialMoveConstructor();
4082 break;
4083 case CXXMoveAssignment:
Richard Smith3003e1d2012-05-15 04:39:51 +00004084 Trivial = RD->hasTrivialMoveAssignment();
4085 break;
4086 case CXXDestructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004087 Trivial = RD->hasTrivialDestructor();
4088 break;
4089 case CXXInvalid:
4090 llvm_unreachable("non-special member explicitly defaulted!");
4091 }
Sean Hunt2b188082011-05-14 05:23:28 +00004092
Richard Smith3003e1d2012-05-15 04:39:51 +00004093 QualType ReturnType = Context.VoidTy;
4094 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4095 // Check for return type matching.
4096 ReturnType = Type->getResultType();
4097 QualType ExpectedReturnType =
4098 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4099 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4100 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4101 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4102 HadError = true;
4103 }
4104
4105 // A defaulted special member cannot have cv-qualifiers.
4106 if (Type->getTypeQuals()) {
4107 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4108 << (CSM == CXXMoveAssignment);
4109 HadError = true;
4110 }
4111 }
4112
4113 // Check for parameter type matching.
4114 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004115 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004116 if (ExpectedParams && ArgType->isReferenceType()) {
4117 // Argument must be reference to possibly-const T.
4118 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004119 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004120
4121 if (ReferentType.isVolatileQualified()) {
4122 Diag(MD->getLocation(),
4123 diag::err_defaulted_special_member_volatile_param) << CSM;
4124 HadError = true;
4125 }
4126
Richard Smith7756afa2012-06-10 05:43:50 +00004127 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004128 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4129 Diag(MD->getLocation(),
4130 diag::err_defaulted_special_member_copy_const_param)
4131 << (CSM == CXXCopyAssignment);
4132 // FIXME: Explain why this special member can't be const.
4133 } else {
4134 Diag(MD->getLocation(),
4135 diag::err_defaulted_special_member_move_const_param)
4136 << (CSM == CXXMoveAssignment);
4137 }
4138 HadError = true;
4139 }
4140
4141 // If a function is explicitly defaulted on its first declaration, it shall
4142 // have the same parameter type as if it had been implicitly declared.
4143 // (Presumably this is to prevent it from being trivial?)
Richard Smith7756afa2012-06-10 05:43:50 +00004144 if (!HasConstParam && CanHaveConstParam && First)
Richard Smith3003e1d2012-05-15 04:39:51 +00004145 Diag(MD->getLocation(),
4146 diag::err_defaulted_special_member_copy_non_const_param)
4147 << (CSM == CXXCopyAssignment);
4148 } else if (ExpectedParams) {
4149 // A copy assignment operator can take its argument by value, but a
4150 // defaulted one cannot.
4151 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004152 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004153 HadError = true;
4154 }
Sean Huntbe631222011-05-17 20:44:43 +00004155
Richard Smithb9d0b762012-07-27 04:22:15 +00004156 // Rebuild the type with the implicit exception specification added, if we
4157 // are going to need it.
4158 const FunctionProtoType *ImplicitType = 0;
4159 if (First || Type->hasExceptionSpec()) {
4160 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4161 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4162 ImplicitType = cast<FunctionProtoType>(
4163 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4164 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004165
Richard Smith61802452011-12-22 02:22:31 +00004166 // C++11 [dcl.fct.def.default]p2:
4167 // An explicitly-defaulted function may be declared constexpr only if it
4168 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004169 // Do not apply this rule to members of class templates, since core issue 1358
4170 // makes such functions always instantiate to constexpr functions. For
4171 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004172 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4173 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004174 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4175 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4176 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004177 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004178 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004179 }
4180 // and may have an explicit exception-specification only if it is compatible
4181 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004182 if (Type->hasExceptionSpec() &&
4183 CheckEquivalentExceptionSpec(
4184 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4185 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4186 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004187
4188 // If a function is explicitly defaulted on its first declaration,
4189 if (First) {
4190 // -- it is implicitly considered to be constexpr if the implicit
4191 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004192 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004193
Richard Smith3003e1d2012-05-15 04:39:51 +00004194 // -- it is implicitly considered to have the same exception-specification
4195 // as if it had been implicitly declared,
4196 MD->setType(QualType(ImplicitType, 0));
Richard Smithe653ba22012-02-26 00:31:33 +00004197
4198 // Such a function is also trivial if the implicitly-declared function
4199 // would have been.
Richard Smith3003e1d2012-05-15 04:39:51 +00004200 MD->setTrivial(Trivial);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004201 }
4202
Richard Smith3003e1d2012-05-15 04:39:51 +00004203 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004204 if (First) {
4205 MD->setDeletedAsWritten();
4206 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004207 // C++11 [dcl.fct.def.default]p4:
4208 // [For a] user-provided explicitly-defaulted function [...] if such a
4209 // function is implicitly defined as deleted, the program is ill-formed.
4210 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4211 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004212 }
4213 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004214
Richard Smith3003e1d2012-05-15 04:39:51 +00004215 if (HadError)
4216 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004217}
4218
Richard Smith7d5088a2012-02-18 02:02:13 +00004219namespace {
4220struct SpecialMemberDeletionInfo {
4221 Sema &S;
4222 CXXMethodDecl *MD;
4223 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004224 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004225
4226 // Properties of the special member, computed for convenience.
4227 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4228 SourceLocation Loc;
4229
4230 bool AllFieldsAreConst;
4231
4232 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004233 Sema::CXXSpecialMember CSM, bool Diagnose)
4234 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004235 IsConstructor(false), IsAssignment(false), IsMove(false),
4236 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4237 AllFieldsAreConst(true) {
4238 switch (CSM) {
4239 case Sema::CXXDefaultConstructor:
4240 case Sema::CXXCopyConstructor:
4241 IsConstructor = true;
4242 break;
4243 case Sema::CXXMoveConstructor:
4244 IsConstructor = true;
4245 IsMove = true;
4246 break;
4247 case Sema::CXXCopyAssignment:
4248 IsAssignment = true;
4249 break;
4250 case Sema::CXXMoveAssignment:
4251 IsAssignment = true;
4252 IsMove = true;
4253 break;
4254 case Sema::CXXDestructor:
4255 break;
4256 case Sema::CXXInvalid:
4257 llvm_unreachable("invalid special member kind");
4258 }
4259
4260 if (MD->getNumParams()) {
4261 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4262 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4263 }
4264 }
4265
4266 bool inUnion() const { return MD->getParent()->isUnion(); }
4267
4268 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004269 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4270 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004271 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004272 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4273 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4274 Quals = 0;
4275 return S.LookupSpecialMember(Class, CSM,
4276 ConstArg || (Quals & Qualifiers::Const),
4277 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004278 MD->getRefQualifier() == RQ_RValue,
4279 TQ & Qualifiers::Const,
4280 TQ & Qualifiers::Volatile);
4281 }
4282
Richard Smith6c4c36c2012-03-30 20:53:28 +00004283 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004284
Richard Smith6c4c36c2012-03-30 20:53:28 +00004285 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004286 bool shouldDeleteForField(FieldDecl *FD);
4287 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004288
Richard Smith517bb842012-07-18 03:51:16 +00004289 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4290 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004291 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4292 Sema::SpecialMemberOverloadResult *SMOR,
4293 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004294
4295 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004296};
4297}
4298
John McCall12d8d802012-04-09 20:53:23 +00004299/// Is the given special member inaccessible when used on the given
4300/// sub-object.
4301bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4302 CXXMethodDecl *target) {
4303 /// If we're operating on a base class, the object type is the
4304 /// type of this special member.
4305 QualType objectTy;
4306 AccessSpecifier access = target->getAccess();;
4307 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4308 objectTy = S.Context.getTypeDeclType(MD->getParent());
4309 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4310
4311 // If we're operating on a field, the object type is the type of the field.
4312 } else {
4313 objectTy = S.Context.getTypeDeclType(target->getParent());
4314 }
4315
4316 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4317}
4318
Richard Smith6c4c36c2012-03-30 20:53:28 +00004319/// Check whether we should delete a special member due to the implicit
4320/// definition containing a call to a special member of a subobject.
4321bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4322 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4323 bool IsDtorCallInCtor) {
4324 CXXMethodDecl *Decl = SMOR->getMethod();
4325 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4326
4327 int DiagKind = -1;
4328
4329 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4330 DiagKind = !Decl ? 0 : 1;
4331 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4332 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004333 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004334 DiagKind = 3;
4335 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4336 !Decl->isTrivial()) {
4337 // A member of a union must have a trivial corresponding special member.
4338 // As a weird special case, a destructor call from a union's constructor
4339 // must be accessible and non-deleted, but need not be trivial. Such a
4340 // destructor is never actually called, but is semantically checked as
4341 // if it were.
4342 DiagKind = 4;
4343 }
4344
4345 if (DiagKind == -1)
4346 return false;
4347
4348 if (Diagnose) {
4349 if (Field) {
4350 S.Diag(Field->getLocation(),
4351 diag::note_deleted_special_member_class_subobject)
4352 << CSM << MD->getParent() << /*IsField*/true
4353 << Field << DiagKind << IsDtorCallInCtor;
4354 } else {
4355 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4356 S.Diag(Base->getLocStart(),
4357 diag::note_deleted_special_member_class_subobject)
4358 << CSM << MD->getParent() << /*IsField*/false
4359 << Base->getType() << DiagKind << IsDtorCallInCtor;
4360 }
4361
4362 if (DiagKind == 1)
4363 S.NoteDeletedFunction(Decl);
4364 // FIXME: Explain inaccessibility if DiagKind == 3.
4365 }
4366
4367 return true;
4368}
4369
Richard Smith9a561d52012-02-26 09:11:52 +00004370/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004371/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004372bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004373 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004374 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004375
4376 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004377 // -- any direct or virtual base class, or non-static data member with no
4378 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004379 // either M has no default constructor or overload resolution as applied
4380 // to M's default constructor results in an ambiguity or in a function
4381 // that is deleted or inaccessible
4382 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4383 // -- a direct or virtual base class B that cannot be copied/moved because
4384 // overload resolution, as applied to B's corresponding special member,
4385 // results in an ambiguity or a function that is deleted or inaccessible
4386 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004387 // C++11 [class.dtor]p5:
4388 // -- any direct or virtual base class [...] has a type with a destructor
4389 // that is deleted or inaccessible
4390 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004391 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004392 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004393 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004394
Richard Smith6c4c36c2012-03-30 20:53:28 +00004395 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4396 // -- any direct or virtual base class or non-static data member has a
4397 // type with a destructor that is deleted or inaccessible
4398 if (IsConstructor) {
4399 Sema::SpecialMemberOverloadResult *SMOR =
4400 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4401 false, false, false, false, false);
4402 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4403 return true;
4404 }
4405
Richard Smith9a561d52012-02-26 09:11:52 +00004406 return false;
4407}
4408
4409/// Check whether we should delete a special member function due to the class
4410/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004411bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004412 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004413 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004414}
4415
4416/// Check whether we should delete a special member function due to the class
4417/// having a particular non-static data member.
4418bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4419 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4420 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4421
4422 if (CSM == Sema::CXXDefaultConstructor) {
4423 // For a default constructor, all references must be initialized in-class
4424 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004425 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4426 if (Diagnose)
4427 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4428 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004429 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004430 }
Richard Smith79363f52012-02-27 06:07:25 +00004431 // C++11 [class.ctor]p5: any non-variant non-static data member of
4432 // const-qualified type (or array thereof) with no
4433 // brace-or-equal-initializer does not have a user-provided default
4434 // constructor.
4435 if (!inUnion() && FieldType.isConstQualified() &&
4436 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004437 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4438 if (Diagnose)
4439 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004440 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004441 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004442 }
4443
4444 if (inUnion() && !FieldType.isConstQualified())
4445 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004446 } else if (CSM == Sema::CXXCopyConstructor) {
4447 // For a copy constructor, data members must not be of rvalue reference
4448 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004449 if (FieldType->isRValueReferenceType()) {
4450 if (Diagnose)
4451 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4452 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004453 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004454 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004455 } else if (IsAssignment) {
4456 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004457 if (FieldType->isReferenceType()) {
4458 if (Diagnose)
4459 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4460 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004461 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004462 }
4463 if (!FieldRecord && FieldType.isConstQualified()) {
4464 // C++11 [class.copy]p23:
4465 // -- a non-static data member of const non-class type (or array thereof)
4466 if (Diagnose)
4467 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004468 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004469 return true;
4470 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004471 }
4472
4473 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004474 // Some additional restrictions exist on the variant members.
4475 if (!inUnion() && FieldRecord->isUnion() &&
4476 FieldRecord->isAnonymousStructOrUnion()) {
4477 bool AllVariantFieldsAreConst = true;
4478
Richard Smithdf8dc862012-03-29 19:00:10 +00004479 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004480 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4481 UE = FieldRecord->field_end();
4482 UI != UE; ++UI) {
4483 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004484
4485 if (!UnionFieldType.isConstQualified())
4486 AllVariantFieldsAreConst = false;
4487
Richard Smith9a561d52012-02-26 09:11:52 +00004488 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4489 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004490 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4491 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004492 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004493 }
4494
4495 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004496 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004497 FieldRecord->field_begin() != FieldRecord->field_end()) {
4498 if (Diagnose)
4499 S.Diag(FieldRecord->getLocation(),
4500 diag::note_deleted_default_ctor_all_const)
4501 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004502 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004503 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004504
Richard Smithdf8dc862012-03-29 19:00:10 +00004505 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004506 // This is technically non-conformant, but sanity demands it.
4507 return false;
4508 }
4509
Richard Smith517bb842012-07-18 03:51:16 +00004510 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4511 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004512 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004513 }
4514
4515 return false;
4516}
4517
4518/// C++11 [class.ctor] p5:
4519/// A defaulted default constructor for a class X is defined as deleted if
4520/// X is a union and all of its variant members are of const-qualified type.
4521bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004522 // This is a silly definition, because it gives an empty union a deleted
4523 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004524 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4525 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4526 if (Diagnose)
4527 S.Diag(MD->getParent()->getLocation(),
4528 diag::note_deleted_default_ctor_all_const)
4529 << MD->getParent() << /*not anonymous union*/0;
4530 return true;
4531 }
4532 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004533}
4534
4535/// Determine whether a defaulted special member function should be defined as
4536/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4537/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004538bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4539 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004540 if (MD->isInvalidDecl())
4541 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004542 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004543 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004544 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004545 return false;
4546
Richard Smith7d5088a2012-02-18 02:02:13 +00004547 // C++11 [expr.lambda.prim]p19:
4548 // The closure type associated with a lambda-expression has a
4549 // deleted (8.4.3) default constructor and a deleted copy
4550 // assignment operator.
4551 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004552 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4553 if (Diagnose)
4554 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004555 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004556 }
4557
Richard Smith5bdaac52012-04-02 20:59:25 +00004558 // For an anonymous struct or union, the copy and assignment special members
4559 // will never be used, so skip the check. For an anonymous union declared at
4560 // namespace scope, the constructor and destructor are used.
4561 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4562 RD->isAnonymousStructOrUnion())
4563 return false;
4564
Richard Smith6c4c36c2012-03-30 20:53:28 +00004565 // C++11 [class.copy]p7, p18:
4566 // If the class definition declares a move constructor or move assignment
4567 // operator, an implicitly declared copy constructor or copy assignment
4568 // operator is defined as deleted.
4569 if (MD->isImplicit() &&
4570 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4571 CXXMethodDecl *UserDeclaredMove = 0;
4572
4573 // In Microsoft mode, a user-declared move only causes the deletion of the
4574 // corresponding copy operation, not both copy operations.
4575 if (RD->hasUserDeclaredMoveConstructor() &&
4576 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4577 if (!Diagnose) return true;
4578 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004579 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004580 } else if (RD->hasUserDeclaredMoveAssignment() &&
4581 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4582 if (!Diagnose) return true;
4583 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004584 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004585 }
4586
4587 if (UserDeclaredMove) {
4588 Diag(UserDeclaredMove->getLocation(),
4589 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004590 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004591 << UserDeclaredMove->isMoveAssignmentOperator();
4592 return true;
4593 }
4594 }
Sean Hunte16da072011-10-10 06:18:57 +00004595
Richard Smith5bdaac52012-04-02 20:59:25 +00004596 // Do access control from the special member function
4597 ContextRAII MethodContext(*this, MD);
4598
Richard Smith9a561d52012-02-26 09:11:52 +00004599 // C++11 [class.dtor]p5:
4600 // -- for a virtual destructor, lookup of the non-array deallocation function
4601 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004602 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004603 FunctionDecl *OperatorDelete = 0;
4604 DeclarationName Name =
4605 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4606 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004607 OperatorDelete, false)) {
4608 if (Diagnose)
4609 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004610 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004611 }
Richard Smith9a561d52012-02-26 09:11:52 +00004612 }
4613
Richard Smith6c4c36c2012-03-30 20:53:28 +00004614 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004615
Sean Huntcdee3fe2011-05-11 22:34:38 +00004616 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004617 BE = RD->bases_end(); BI != BE; ++BI)
4618 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004619 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004620 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004621
4622 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004623 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004624 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004625 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004626
4627 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004628 FE = RD->field_end(); FI != FE; ++FI)
4629 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004630 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004631 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004632
Richard Smith7d5088a2012-02-18 02:02:13 +00004633 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004634 return true;
4635
4636 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004637}
4638
4639/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004640namespace {
4641 struct FindHiddenVirtualMethodData {
4642 Sema *S;
4643 CXXMethodDecl *Method;
4644 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004645 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004646 };
4647}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004648
4649/// \brief Member lookup function that determines whether a given C++
4650/// method overloads virtual methods in a base class without overriding any,
4651/// to be used with CXXRecordDecl::lookupInBases().
4652static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4653 CXXBasePath &Path,
4654 void *UserData) {
4655 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4656
4657 FindHiddenVirtualMethodData &Data
4658 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4659
4660 DeclarationName Name = Data.Method->getDeclName();
4661 assert(Name.getNameKind() == DeclarationName::Identifier);
4662
4663 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004664 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004665 for (Path.Decls = BaseRecord->lookup(Name);
4666 Path.Decls.first != Path.Decls.second;
4667 ++Path.Decls.first) {
4668 NamedDecl *D = *Path.Decls.first;
4669 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004670 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004671 foundSameNameMethod = true;
4672 // Interested only in hidden virtual methods.
4673 if (!MD->isVirtual())
4674 continue;
4675 // If the method we are checking overrides a method from its base
4676 // don't warn about the other overloaded methods.
4677 if (!Data.S->IsOverload(Data.Method, MD, false))
4678 return true;
4679 // Collect the overload only if its hidden.
4680 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4681 overloadedMethods.push_back(MD);
4682 }
4683 }
4684
4685 if (foundSameNameMethod)
4686 Data.OverloadedMethods.append(overloadedMethods.begin(),
4687 overloadedMethods.end());
4688 return foundSameNameMethod;
4689}
4690
4691/// \brief See if a method overloads virtual methods in a base class without
4692/// overriding any.
4693void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4694 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004695 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004696 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00004697 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004698 return;
4699
4700 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4701 /*bool RecordPaths=*/false,
4702 /*bool DetectVirtual=*/false);
4703 FindHiddenVirtualMethodData Data;
4704 Data.Method = MD;
4705 Data.S = this;
4706
4707 // Keep the base methods that were overriden or introduced in the subclass
4708 // by 'using' in a set. A base method not in this set is hidden.
4709 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4710 res.first != res.second; ++res.first) {
4711 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4712 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4713 E = MD->end_overridden_methods();
4714 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004715 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004716 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4717 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004718 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004719 }
4720
4721 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4722 !Data.OverloadedMethods.empty()) {
4723 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4724 << MD << (Data.OverloadedMethods.size() > 1);
4725
4726 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4727 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4728 Diag(overloadedMD->getLocation(),
4729 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4730 }
4731 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004732}
4733
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004734void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004735 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004736 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004737 SourceLocation RBrac,
4738 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004739 if (!TagDecl)
4740 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004741
Douglas Gregor42af25f2009-05-11 19:58:34 +00004742 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004743
Rafael Espindolaf729ce02012-07-12 04:32:30 +00004744 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4745 if (l->getKind() != AttributeList::AT_Visibility)
4746 continue;
4747 l->setInvalid();
4748 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4749 l->getName();
4750 }
4751
David Blaikie77b6de02011-09-22 02:58:26 +00004752 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004753 // strict aliasing violation!
4754 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004755 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004756
Douglas Gregor23c94db2010-07-02 17:43:08 +00004757 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004758 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004759}
4760
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004761/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4762/// special functions, such as the default constructor, copy
4763/// constructor, or destructor, to the given C++ class (C++
4764/// [special]p1). This routine can only be executed just before the
4765/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004766void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004767 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004768 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004769
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004770 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004771 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004772
David Blaikie4e4d0842012-03-11 07:00:24 +00004773 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004774 ++ASTContext::NumImplicitMoveConstructors;
4775
Douglas Gregora376d102010-07-02 21:50:04 +00004776 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4777 ++ASTContext::NumImplicitCopyAssignmentOperators;
4778
4779 // If we have a dynamic class, then the copy assignment operator may be
4780 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4781 // it shows up in the right place in the vtable and that we diagnose
4782 // problems with the implicit exception specification.
4783 if (ClassDecl->isDynamicClass())
4784 DeclareImplicitCopyAssignment(ClassDecl);
4785 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004786
Richard Smith1c931be2012-04-02 18:40:40 +00004787 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004788 ++ASTContext::NumImplicitMoveAssignmentOperators;
4789
4790 // Likewise for the move assignment operator.
4791 if (ClassDecl->isDynamicClass())
4792 DeclareImplicitMoveAssignment(ClassDecl);
4793 }
4794
Douglas Gregor4923aa22010-07-02 20:37:36 +00004795 if (!ClassDecl->hasUserDeclaredDestructor()) {
4796 ++ASTContext::NumImplicitDestructors;
4797
4798 // If we have a dynamic class, then the destructor may be virtual, so we
4799 // have to declare the destructor immediately. This ensures that, e.g., it
4800 // shows up in the right place in the vtable and that we diagnose problems
4801 // with the implicit exception specification.
4802 if (ClassDecl->isDynamicClass())
4803 DeclareImplicitDestructor(ClassDecl);
4804 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004805}
4806
Francois Pichet8387e2a2011-04-22 22:18:13 +00004807void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4808 if (!D)
4809 return;
4810
4811 int NumParamList = D->getNumTemplateParameterLists();
4812 for (int i = 0; i < NumParamList; i++) {
4813 TemplateParameterList* Params = D->getTemplateParameterList(i);
4814 for (TemplateParameterList::iterator Param = Params->begin(),
4815 ParamEnd = Params->end();
4816 Param != ParamEnd; ++Param) {
4817 NamedDecl *Named = cast<NamedDecl>(*Param);
4818 if (Named->getDeclName()) {
4819 S->AddDecl(Named);
4820 IdResolver.AddDecl(Named);
4821 }
4822 }
4823 }
4824}
4825
John McCalld226f652010-08-21 09:40:31 +00004826void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004827 if (!D)
4828 return;
4829
4830 TemplateParameterList *Params = 0;
4831 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4832 Params = Template->getTemplateParameters();
4833 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4834 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4835 Params = PartialSpec->getTemplateParameters();
4836 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004837 return;
4838
Douglas Gregor6569d682009-05-27 23:11:45 +00004839 for (TemplateParameterList::iterator Param = Params->begin(),
4840 ParamEnd = Params->end();
4841 Param != ParamEnd; ++Param) {
4842 NamedDecl *Named = cast<NamedDecl>(*Param);
4843 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004844 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004845 IdResolver.AddDecl(Named);
4846 }
4847 }
4848}
4849
John McCalld226f652010-08-21 09:40:31 +00004850void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004851 if (!RecordD) return;
4852 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004853 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004854 PushDeclContext(S, Record);
4855}
4856
John McCalld226f652010-08-21 09:40:31 +00004857void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004858 if (!RecordD) return;
4859 PopDeclContext();
4860}
4861
Douglas Gregor72b505b2008-12-16 21:30:33 +00004862/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4863/// parsing a top-level (non-nested) C++ class, and we are now
4864/// parsing those parts of the given Method declaration that could
4865/// not be parsed earlier (C++ [class.mem]p2), such as default
4866/// arguments. This action should enter the scope of the given
4867/// Method declaration as if we had just parsed the qualified method
4868/// name. However, it should not bring the parameters into scope;
4869/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004870void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004871}
4872
4873/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4874/// C++ method declaration. We're (re-)introducing the given
4875/// function parameter into scope for use in parsing later parts of
4876/// the method declaration. For example, we could see an
4877/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004878void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004879 if (!ParamD)
4880 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004881
John McCalld226f652010-08-21 09:40:31 +00004882 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004883
4884 // If this parameter has an unparsed default argument, clear it out
4885 // to make way for the parsed default argument.
4886 if (Param->hasUnparsedDefaultArg())
4887 Param->setDefaultArg(0);
4888
John McCalld226f652010-08-21 09:40:31 +00004889 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004890 if (Param->getDeclName())
4891 IdResolver.AddDecl(Param);
4892}
4893
4894/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4895/// processing the delayed method declaration for Method. The method
4896/// declaration is now considered finished. There may be a separate
4897/// ActOnStartOfFunctionDef action later (not necessarily
4898/// immediately!) for this method, if it was also defined inside the
4899/// class body.
John McCalld226f652010-08-21 09:40:31 +00004900void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004901 if (!MethodD)
4902 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004903
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004904 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004905
John McCalld226f652010-08-21 09:40:31 +00004906 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004907
4908 // Now that we have our default arguments, check the constructor
4909 // again. It could produce additional diagnostics or affect whether
4910 // the class has implicitly-declared destructors, among other
4911 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004912 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4913 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004914
4915 // Check the default arguments, which we may have added.
4916 if (!Method->isInvalidDecl())
4917 CheckCXXDefaultArguments(Method);
4918}
4919
Douglas Gregor42a552f2008-11-05 20:51:48 +00004920/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004921/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004922/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004923/// emit diagnostics and set the invalid bit to true. In any case, the type
4924/// will be updated to reflect a well-formed type for the constructor and
4925/// returned.
4926QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004927 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004928 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004929
4930 // C++ [class.ctor]p3:
4931 // A constructor shall not be virtual (10.3) or static (9.4). A
4932 // constructor can be invoked for a const, volatile or const
4933 // volatile object. A constructor shall not be declared const,
4934 // volatile, or const volatile (9.3.2).
4935 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004936 if (!D.isInvalidType())
4937 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4938 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4939 << SourceRange(D.getIdentifierLoc());
4940 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004941 }
John McCalld931b082010-08-26 03:08:43 +00004942 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004943 if (!D.isInvalidType())
4944 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4945 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4946 << SourceRange(D.getIdentifierLoc());
4947 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004948 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004949 }
Mike Stump1eb44332009-09-09 15:08:12 +00004950
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004951 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004952 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004953 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004954 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4955 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004956 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004957 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4958 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004959 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004960 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4961 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004962 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004963 }
Mike Stump1eb44332009-09-09 15:08:12 +00004964
Douglas Gregorc938c162011-01-26 05:01:58 +00004965 // C++0x [class.ctor]p4:
4966 // A constructor shall not be declared with a ref-qualifier.
4967 if (FTI.hasRefQualifier()) {
4968 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4969 << FTI.RefQualifierIsLValueRef
4970 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4971 D.setInvalidType();
4972 }
4973
Douglas Gregor42a552f2008-11-05 20:51:48 +00004974 // Rebuild the function type "R" without any type qualifiers (in
4975 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004976 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004977 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004978 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4979 return R;
4980
4981 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4982 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004983 EPI.RefQualifier = RQ_None;
4984
Chris Lattner65401802009-04-25 08:28:21 +00004985 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004986 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004987}
4988
Douglas Gregor72b505b2008-12-16 21:30:33 +00004989/// CheckConstructor - Checks a fully-formed constructor for
4990/// well-formedness, issuing any diagnostics required. Returns true if
4991/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004992void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004993 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004994 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4995 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004996 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004997
4998 // C++ [class.copy]p3:
4999 // A declaration of a constructor for a class X is ill-formed if
5000 // its first parameter is of type (optionally cv-qualified) X and
5001 // either there are no other parameters or else all other
5002 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005003 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005004 ((Constructor->getNumParams() == 1) ||
5005 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005006 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5007 Constructor->getTemplateSpecializationKind()
5008 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005009 QualType ParamType = Constructor->getParamDecl(0)->getType();
5010 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5011 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005012 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005013 const char *ConstRef
5014 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5015 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005016 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005017 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005018
5019 // FIXME: Rather that making the constructor invalid, we should endeavor
5020 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005021 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005022 }
5023 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005024}
5025
John McCall15442822010-08-04 01:04:25 +00005026/// CheckDestructor - Checks a fully-formed destructor definition for
5027/// well-formedness, issuing any diagnostics required. Returns true
5028/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005029bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005030 CXXRecordDecl *RD = Destructor->getParent();
5031
5032 if (Destructor->isVirtual()) {
5033 SourceLocation Loc;
5034
5035 if (!Destructor->isImplicit())
5036 Loc = Destructor->getLocation();
5037 else
5038 Loc = RD->getLocation();
5039
5040 // If we have a virtual destructor, look up the deallocation function
5041 FunctionDecl *OperatorDelete = 0;
5042 DeclarationName Name =
5043 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005044 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005045 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005046
Eli Friedman5f2987c2012-02-02 03:46:19 +00005047 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005048
5049 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005050 }
Anders Carlsson37909802009-11-30 21:24:50 +00005051
5052 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005053}
5054
Mike Stump1eb44332009-09-09 15:08:12 +00005055static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005056FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5057 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5058 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005059 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005060}
5061
Douglas Gregor42a552f2008-11-05 20:51:48 +00005062/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5063/// the well-formednes of the destructor declarator @p D with type @p
5064/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005065/// emit diagnostics and set the declarator to invalid. Even if this happens,
5066/// will be updated to reflect a well-formed type for the destructor and
5067/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005068QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005069 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005070 // C++ [class.dtor]p1:
5071 // [...] A typedef-name that names a class is a class-name
5072 // (7.1.3); however, a typedef-name that names a class shall not
5073 // be used as the identifier in the declarator for a destructor
5074 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005075 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005076 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005077 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005078 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005079 else if (const TemplateSpecializationType *TST =
5080 DeclaratorType->getAs<TemplateSpecializationType>())
5081 if (TST->isTypeAlias())
5082 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5083 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005084
5085 // C++ [class.dtor]p2:
5086 // A destructor is used to destroy objects of its class type. A
5087 // destructor takes no parameters, and no return type can be
5088 // specified for it (not even void). The address of a destructor
5089 // shall not be taken. A destructor shall not be static. A
5090 // destructor can be invoked for a const, volatile or const
5091 // volatile object. A destructor shall not be declared const,
5092 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005093 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005094 if (!D.isInvalidType())
5095 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5096 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005097 << SourceRange(D.getIdentifierLoc())
5098 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5099
John McCalld931b082010-08-26 03:08:43 +00005100 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005101 }
Chris Lattner65401802009-04-25 08:28:21 +00005102 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005103 // Destructors don't have return types, but the parser will
5104 // happily parse something like:
5105 //
5106 // class X {
5107 // float ~X();
5108 // };
5109 //
5110 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005111 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5112 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5113 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005114 }
Mike Stump1eb44332009-09-09 15:08:12 +00005115
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005116 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005117 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005118 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005119 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5120 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005121 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005122 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5123 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005124 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005125 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5126 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005127 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005128 }
5129
Douglas Gregorc938c162011-01-26 05:01:58 +00005130 // C++0x [class.dtor]p2:
5131 // A destructor shall not be declared with a ref-qualifier.
5132 if (FTI.hasRefQualifier()) {
5133 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5134 << FTI.RefQualifierIsLValueRef
5135 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5136 D.setInvalidType();
5137 }
5138
Douglas Gregor42a552f2008-11-05 20:51:48 +00005139 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005140 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005141 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5142
5143 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005144 FTI.freeArgs();
5145 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005146 }
5147
Mike Stump1eb44332009-09-09 15:08:12 +00005148 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005149 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005150 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005151 D.setInvalidType();
5152 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005153
5154 // Rebuild the function type "R" without any type qualifiers or
5155 // parameters (in case any of the errors above fired) and with
5156 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005157 // types.
John McCalle23cf432010-12-14 08:05:40 +00005158 if (!D.isInvalidType())
5159 return R;
5160
Douglas Gregord92ec472010-07-01 05:10:53 +00005161 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005162 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5163 EPI.Variadic = false;
5164 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005165 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005166 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005167}
5168
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005169/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5170/// well-formednes of the conversion function declarator @p D with
5171/// type @p R. If there are any errors in the declarator, this routine
5172/// will emit diagnostics and return true. Otherwise, it will return
5173/// false. Either way, the type @p R will be updated to reflect a
5174/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005175void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005176 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005177 // C++ [class.conv.fct]p1:
5178 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005179 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005180 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005181 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005182 if (!D.isInvalidType())
5183 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5184 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5185 << SourceRange(D.getIdentifierLoc());
5186 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005187 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005188 }
John McCalla3f81372010-04-13 00:04:31 +00005189
5190 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5191
Chris Lattner6e475012009-04-25 08:35:12 +00005192 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005193 // Conversion functions don't have return types, but the parser will
5194 // happily parse something like:
5195 //
5196 // class X {
5197 // float operator bool();
5198 // };
5199 //
5200 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005201 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5202 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5203 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005204 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005205 }
5206
John McCalla3f81372010-04-13 00:04:31 +00005207 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5208
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005209 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005210 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005211 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5212
5213 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005214 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005215 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005216 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005217 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005218 D.setInvalidType();
5219 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005220
John McCalla3f81372010-04-13 00:04:31 +00005221 // Diagnose "&operator bool()" and other such nonsense. This
5222 // is actually a gcc extension which we don't support.
5223 if (Proto->getResultType() != ConvType) {
5224 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5225 << Proto->getResultType();
5226 D.setInvalidType();
5227 ConvType = Proto->getResultType();
5228 }
5229
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005230 // C++ [class.conv.fct]p4:
5231 // The conversion-type-id shall not represent a function type nor
5232 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005233 if (ConvType->isArrayType()) {
5234 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5235 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005236 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005237 } else if (ConvType->isFunctionType()) {
5238 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5239 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005240 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005241 }
5242
5243 // Rebuild the function type "R" without any parameters (in case any
5244 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005245 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005246 if (D.isInvalidType())
5247 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005248
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005249 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005250 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005251 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005252 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005253 diag::warn_cxx98_compat_explicit_conversion_functions :
5254 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005255 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005256}
5257
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005258/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5259/// the declaration of the given C++ conversion function. This routine
5260/// is responsible for recording the conversion function in the C++
5261/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005262Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005263 assert(Conversion && "Expected to receive a conversion function declaration");
5264
Douglas Gregor9d350972008-12-12 08:25:50 +00005265 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005266
5267 // Make sure we aren't redeclaring the conversion function.
5268 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005269
5270 // C++ [class.conv.fct]p1:
5271 // [...] A conversion function is never used to convert a
5272 // (possibly cv-qualified) object to the (possibly cv-qualified)
5273 // same object type (or a reference to it), to a (possibly
5274 // cv-qualified) base class of that type (or a reference to it),
5275 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005276 // FIXME: Suppress this warning if the conversion function ends up being a
5277 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005278 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005279 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005280 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005281 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005282 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5283 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005284 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005285 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005286 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5287 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005288 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005289 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005290 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005291 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005292 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005293 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005294 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005295 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005296 }
5297
Douglas Gregore80622f2010-09-29 04:25:11 +00005298 if (FunctionTemplateDecl *ConversionTemplate
5299 = Conversion->getDescribedFunctionTemplate())
5300 return ConversionTemplate;
5301
John McCalld226f652010-08-21 09:40:31 +00005302 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005303}
5304
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005305//===----------------------------------------------------------------------===//
5306// Namespace Handling
5307//===----------------------------------------------------------------------===//
5308
John McCallea318642010-08-26 09:15:37 +00005309
5310
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005311/// ActOnStartNamespaceDef - This is called at the start of a namespace
5312/// definition.
John McCalld226f652010-08-21 09:40:31 +00005313Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005314 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005315 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005316 SourceLocation IdentLoc,
5317 IdentifierInfo *II,
5318 SourceLocation LBrace,
5319 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005320 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5321 // For anonymous namespace, take the location of the left brace.
5322 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005323 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005324 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005325 bool IsStd = false;
5326 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005327 Scope *DeclRegionScope = NamespcScope->getParent();
5328
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005329 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005330 if (II) {
5331 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005332 // The identifier in an original-namespace-definition shall not
5333 // have been previously defined in the declarative region in
5334 // which the original-namespace-definition appears. The
5335 // identifier in an original-namespace-definition is the name of
5336 // the namespace. Subsequently in that declarative region, it is
5337 // treated as an original-namespace-name.
5338 //
5339 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005340 // look through using directives, just look for any ordinary names.
5341
5342 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005343 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5344 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005345 NamedDecl *PrevDecl = 0;
5346 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005347 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005348 R.first != R.second; ++R.first) {
5349 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5350 PrevDecl = *R.first;
5351 break;
5352 }
5353 }
5354
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005355 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5356
5357 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005358 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005359 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005360 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005361 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005362 // The user probably just forgot the 'inline', so suggest that it
5363 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005364 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005365 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5366 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005367 Diag(Loc, diag::err_inline_namespace_mismatch)
5368 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005369 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005370 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5371
5372 IsInline = PrevNS->isInline();
5373 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005374 } else if (PrevDecl) {
5375 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005376 Diag(Loc, diag::err_redefinition_different_kind)
5377 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005378 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005379 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005380 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005381 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005382 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005383 // This is the first "real" definition of the namespace "std", so update
5384 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005385 PrevNS = getStdNamespace();
5386 IsStd = true;
5387 AddToKnown = !IsInline;
5388 } else {
5389 // We've seen this namespace for the first time.
5390 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005391 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005392 } else {
John McCall9aeed322009-10-01 00:25:31 +00005393 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005394
5395 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005396 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005397 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005398 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005399 } else {
5400 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005401 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005402 }
5403
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005404 if (PrevNS && IsInline != PrevNS->isInline()) {
5405 // inline-ness must match
5406 Diag(Loc, diag::err_inline_namespace_mismatch)
5407 << IsInline;
5408 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005409
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005410 // Recover by ignoring the new namespace's inline status.
5411 IsInline = PrevNS->isInline();
5412 }
5413 }
5414
5415 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5416 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005417 if (IsInvalid)
5418 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005419
5420 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005421
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005422 // FIXME: Should we be merging attributes?
5423 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005424 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005425
5426 if (IsStd)
5427 StdNamespace = Namespc;
5428 if (AddToKnown)
5429 KnownNamespaces[Namespc] = false;
5430
5431 if (II) {
5432 PushOnScopeChains(Namespc, DeclRegionScope);
5433 } else {
5434 // Link the anonymous namespace into its parent.
5435 DeclContext *Parent = CurContext->getRedeclContext();
5436 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5437 TU->setAnonymousNamespace(Namespc);
5438 } else {
5439 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005440 }
John McCall9aeed322009-10-01 00:25:31 +00005441
Douglas Gregora4181472010-03-24 00:46:35 +00005442 CurContext->addDecl(Namespc);
5443
John McCall9aeed322009-10-01 00:25:31 +00005444 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5445 // behaves as if it were replaced by
5446 // namespace unique { /* empty body */ }
5447 // using namespace unique;
5448 // namespace unique { namespace-body }
5449 // where all occurrences of 'unique' in a translation unit are
5450 // replaced by the same identifier and this identifier differs
5451 // from all other identifiers in the entire program.
5452
5453 // We just create the namespace with an empty name and then add an
5454 // implicit using declaration, just like the standard suggests.
5455 //
5456 // CodeGen enforces the "universally unique" aspect by giving all
5457 // declarations semantically contained within an anonymous
5458 // namespace internal linkage.
5459
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005460 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005461 UsingDirectiveDecl* UD
5462 = UsingDirectiveDecl::Create(Context, CurContext,
5463 /* 'using' */ LBrace,
5464 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005465 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005466 /* identifier */ SourceLocation(),
5467 Namespc,
5468 /* Ancestor */ CurContext);
5469 UD->setImplicit();
5470 CurContext->addDecl(UD);
5471 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005472 }
5473
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00005474 ActOnDocumentableDecl(Namespc);
5475
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005476 // Although we could have an invalid decl (i.e. the namespace name is a
5477 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005478 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5479 // for the namespace has the declarations that showed up in that particular
5480 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005481 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005482 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005483}
5484
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005485/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5486/// is a namespace alias, returns the namespace it points to.
5487static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5488 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5489 return AD->getNamespace();
5490 return dyn_cast_or_null<NamespaceDecl>(D);
5491}
5492
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005493/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5494/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005495void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005496 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5497 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005498 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005499 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005500 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005501 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005502}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005503
John McCall384aff82010-08-25 07:42:41 +00005504CXXRecordDecl *Sema::getStdBadAlloc() const {
5505 return cast_or_null<CXXRecordDecl>(
5506 StdBadAlloc.get(Context.getExternalSource()));
5507}
5508
5509NamespaceDecl *Sema::getStdNamespace() const {
5510 return cast_or_null<NamespaceDecl>(
5511 StdNamespace.get(Context.getExternalSource()));
5512}
5513
Douglas Gregor66992202010-06-29 17:53:46 +00005514/// \brief Retrieve the special "std" namespace, which may require us to
5515/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005516NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005517 if (!StdNamespace) {
5518 // The "std" namespace has not yet been defined, so build one implicitly.
5519 StdNamespace = NamespaceDecl::Create(Context,
5520 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005521 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005522 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005523 &PP.getIdentifierTable().get("std"),
5524 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005525 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005526 }
5527
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005528 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005529}
5530
Sebastian Redl395e04d2012-01-17 22:49:33 +00005531bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005532 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005533 "Looking for std::initializer_list outside of C++.");
5534
5535 // We're looking for implicit instantiations of
5536 // template <typename E> class std::initializer_list.
5537
5538 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5539 return false;
5540
Sebastian Redl84760e32012-01-17 22:49:58 +00005541 ClassTemplateDecl *Template = 0;
5542 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005543
Sebastian Redl84760e32012-01-17 22:49:58 +00005544 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005545
Sebastian Redl84760e32012-01-17 22:49:58 +00005546 ClassTemplateSpecializationDecl *Specialization =
5547 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5548 if (!Specialization)
5549 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005550
Sebastian Redl84760e32012-01-17 22:49:58 +00005551 Template = Specialization->getSpecializedTemplate();
5552 Arguments = Specialization->getTemplateArgs().data();
5553 } else if (const TemplateSpecializationType *TST =
5554 Ty->getAs<TemplateSpecializationType>()) {
5555 Template = dyn_cast_or_null<ClassTemplateDecl>(
5556 TST->getTemplateName().getAsTemplateDecl());
5557 Arguments = TST->getArgs();
5558 }
5559 if (!Template)
5560 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005561
5562 if (!StdInitializerList) {
5563 // Haven't recognized std::initializer_list yet, maybe this is it.
5564 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5565 if (TemplateClass->getIdentifier() !=
5566 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005567 !getStdNamespace()->InEnclosingNamespaceSetOf(
5568 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005569 return false;
5570 // This is a template called std::initializer_list, but is it the right
5571 // template?
5572 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005573 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005574 return false;
5575 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5576 return false;
5577
5578 // It's the right template.
5579 StdInitializerList = Template;
5580 }
5581
5582 if (Template != StdInitializerList)
5583 return false;
5584
5585 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005586 if (Element)
5587 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005588 return true;
5589}
5590
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005591static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5592 NamespaceDecl *Std = S.getStdNamespace();
5593 if (!Std) {
5594 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5595 return 0;
5596 }
5597
5598 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5599 Loc, Sema::LookupOrdinaryName);
5600 if (!S.LookupQualifiedName(Result, Std)) {
5601 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5602 return 0;
5603 }
5604 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5605 if (!Template) {
5606 Result.suppressDiagnostics();
5607 // We found something weird. Complain about the first thing we found.
5608 NamedDecl *Found = *Result.begin();
5609 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5610 return 0;
5611 }
5612
5613 // We found some template called std::initializer_list. Now verify that it's
5614 // correct.
5615 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005616 if (Params->getMinRequiredArguments() != 1 ||
5617 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005618 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5619 return 0;
5620 }
5621
5622 return Template;
5623}
5624
5625QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5626 if (!StdInitializerList) {
5627 StdInitializerList = LookupStdInitializerList(*this, Loc);
5628 if (!StdInitializerList)
5629 return QualType();
5630 }
5631
5632 TemplateArgumentListInfo Args(Loc, Loc);
5633 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5634 Context.getTrivialTypeSourceInfo(Element,
5635 Loc)));
5636 return Context.getCanonicalType(
5637 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5638}
5639
Sebastian Redl98d36062012-01-17 22:50:14 +00005640bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5641 // C++ [dcl.init.list]p2:
5642 // A constructor is an initializer-list constructor if its first parameter
5643 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5644 // std::initializer_list<E> for some type E, and either there are no other
5645 // parameters or else all other parameters have default arguments.
5646 if (Ctor->getNumParams() < 1 ||
5647 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5648 return false;
5649
5650 QualType ArgType = Ctor->getParamDecl(0)->getType();
5651 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5652 ArgType = RT->getPointeeType().getUnqualifiedType();
5653
5654 return isStdInitializerList(ArgType, 0);
5655}
5656
Douglas Gregor9172aa62011-03-26 22:25:30 +00005657/// \brief Determine whether a using statement is in a context where it will be
5658/// apply in all contexts.
5659static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5660 switch (CurContext->getDeclKind()) {
5661 case Decl::TranslationUnit:
5662 return true;
5663 case Decl::LinkageSpec:
5664 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5665 default:
5666 return false;
5667 }
5668}
5669
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005670namespace {
5671
5672// Callback to only accept typo corrections that are namespaces.
5673class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5674 public:
5675 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5676 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5677 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5678 }
5679 return false;
5680 }
5681};
5682
5683}
5684
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005685static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5686 CXXScopeSpec &SS,
5687 SourceLocation IdentLoc,
5688 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005689 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005690 R.clear();
5691 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005692 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005693 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005694 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5695 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005696 if (DeclContext *DC = S.computeDeclContext(SS, false))
5697 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5698 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5699 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5700 else
5701 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5702 << Ident << CorrectedQuotedStr
5703 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005704
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005705 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5706 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005707
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005708 R.addDecl(Corrected.getCorrectionDecl());
5709 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005710 }
5711 return false;
5712}
5713
John McCalld226f652010-08-21 09:40:31 +00005714Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005715 SourceLocation UsingLoc,
5716 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005717 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005718 SourceLocation IdentLoc,
5719 IdentifierInfo *NamespcName,
5720 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005721 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5722 assert(NamespcName && "Invalid NamespcName.");
5723 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005724
5725 // This can only happen along a recovery path.
5726 while (S->getFlags() & Scope::TemplateParamScope)
5727 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005728 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005729
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005730 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005731 NestedNameSpecifier *Qualifier = 0;
5732 if (SS.isSet())
5733 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5734
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005735 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005736 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5737 LookupParsedName(R, S, &SS);
5738 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005739 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005740
Douglas Gregor66992202010-06-29 17:53:46 +00005741 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005742 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005743 // Allow "using namespace std;" or "using namespace ::std;" even if
5744 // "std" hasn't been defined yet, for GCC compatibility.
5745 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5746 NamespcName->isStr("std")) {
5747 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005748 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005749 R.resolveKind();
5750 }
5751 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005752 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005753 }
5754
John McCallf36e02d2009-10-09 21:13:30 +00005755 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005756 NamedDecl *Named = R.getFoundDecl();
5757 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5758 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005759 // C++ [namespace.udir]p1:
5760 // A using-directive specifies that the names in the nominated
5761 // namespace can be used in the scope in which the
5762 // using-directive appears after the using-directive. During
5763 // unqualified name lookup (3.4.1), the names appear as if they
5764 // were declared in the nearest enclosing namespace which
5765 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005766 // namespace. [Note: in this context, "contains" means "contains
5767 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005768
5769 // Find enclosing context containing both using-directive and
5770 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005771 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005772 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5773 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5774 CommonAncestor = CommonAncestor->getParent();
5775
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005776 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005777 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005778 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005779
Douglas Gregor9172aa62011-03-26 22:25:30 +00005780 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005781 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005782 Diag(IdentLoc, diag::warn_using_directive_in_header);
5783 }
5784
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005785 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005786 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005787 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005788 }
5789
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005790 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005791 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005792}
5793
5794void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005795 // If the scope has an associated entity and the using directive is at
5796 // namespace or translation unit scope, add the UsingDirectiveDecl into
5797 // its lookup structure so qualified name lookup can find it.
5798 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5799 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005800 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005801 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005802 // Otherwise, it is at block sope. The using-directives will affect lookup
5803 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005804 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005805}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005806
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005807
John McCalld226f652010-08-21 09:40:31 +00005808Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005809 AccessSpecifier AS,
5810 bool HasUsingKeyword,
5811 SourceLocation UsingLoc,
5812 CXXScopeSpec &SS,
5813 UnqualifiedId &Name,
5814 AttributeList *AttrList,
5815 bool IsTypeName,
5816 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005817 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005818
Douglas Gregor12c118a2009-11-04 16:30:06 +00005819 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005820 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005821 case UnqualifiedId::IK_Identifier:
5822 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005823 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005824 case UnqualifiedId::IK_ConversionFunctionId:
5825 break;
5826
5827 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005828 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00005829 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005830 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005831 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00005832 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5833 // instead once inheriting constructors work.
5834 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00005835 diag::err_using_decl_constructor)
5836 << SS.getRange();
5837
David Blaikie4e4d0842012-03-11 07:00:24 +00005838 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005839
John McCalld226f652010-08-21 09:40:31 +00005840 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005841
5842 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005843 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005844 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005845 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005846
5847 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005848 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005849 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005850 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005851 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005852
5853 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5854 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005855 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005856 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005857
John McCall60fa3cf2009-12-11 02:10:03 +00005858 // Warn about using declarations.
5859 // TODO: store that the declaration was written without 'using' and
5860 // talk about access decls instead of using decls in the
5861 // diagnostics.
5862 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005863 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005864
5865 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005866 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005867 }
5868
Douglas Gregor56c04582010-12-16 00:46:58 +00005869 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5870 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5871 return 0;
5872
John McCall9488ea12009-11-17 05:59:44 +00005873 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005874 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005875 /* IsInstantiation */ false,
5876 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005877 if (UD)
5878 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005879
John McCalld226f652010-08-21 09:40:31 +00005880 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005881}
5882
Douglas Gregor09acc982010-07-07 23:08:52 +00005883/// \brief Determine whether a using declaration considers the given
5884/// declarations as "equivalent", e.g., if they are redeclarations of
5885/// the same entity or are both typedefs of the same type.
5886static bool
5887IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5888 bool &SuppressRedeclaration) {
5889 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5890 SuppressRedeclaration = false;
5891 return true;
5892 }
5893
Richard Smith162e1c12011-04-15 14:24:37 +00005894 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5895 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005896 SuppressRedeclaration = true;
5897 return Context.hasSameType(TD1->getUnderlyingType(),
5898 TD2->getUnderlyingType());
5899 }
5900
5901 return false;
5902}
5903
5904
John McCall9f54ad42009-12-10 09:41:52 +00005905/// Determines whether to create a using shadow decl for a particular
5906/// decl, given the set of decls existing prior to this using lookup.
5907bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5908 const LookupResult &Previous) {
5909 // Diagnose finding a decl which is not from a base class of the
5910 // current class. We do this now because there are cases where this
5911 // function will silently decide not to build a shadow decl, which
5912 // will pre-empt further diagnostics.
5913 //
5914 // We don't need to do this in C++0x because we do the check once on
5915 // the qualifier.
5916 //
5917 // FIXME: diagnose the following if we care enough:
5918 // struct A { int foo; };
5919 // struct B : A { using A::foo; };
5920 // template <class T> struct C : A {};
5921 // template <class T> struct D : C<T> { using B::foo; } // <---
5922 // This is invalid (during instantiation) in C++03 because B::foo
5923 // resolves to the using decl in B, which is not a base class of D<T>.
5924 // We can't diagnose it immediately because C<T> is an unknown
5925 // specialization. The UsingShadowDecl in D<T> then points directly
5926 // to A::foo, which will look well-formed when we instantiate.
5927 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005928 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005929 DeclContext *OrigDC = Orig->getDeclContext();
5930
5931 // Handle enums and anonymous structs.
5932 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5933 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5934 while (OrigRec->isAnonymousStructOrUnion())
5935 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5936
5937 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5938 if (OrigDC == CurContext) {
5939 Diag(Using->getLocation(),
5940 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005941 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005942 Diag(Orig->getLocation(), diag::note_using_decl_target);
5943 return true;
5944 }
5945
Douglas Gregordc355712011-02-25 00:36:19 +00005946 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005947 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005948 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005949 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005950 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005951 Diag(Orig->getLocation(), diag::note_using_decl_target);
5952 return true;
5953 }
5954 }
5955
5956 if (Previous.empty()) return false;
5957
5958 NamedDecl *Target = Orig;
5959 if (isa<UsingShadowDecl>(Target))
5960 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5961
John McCalld7533ec2009-12-11 02:33:26 +00005962 // If the target happens to be one of the previous declarations, we
5963 // don't have a conflict.
5964 //
5965 // FIXME: but we might be increasing its access, in which case we
5966 // should redeclare it.
5967 NamedDecl *NonTag = 0, *Tag = 0;
5968 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5969 I != E; ++I) {
5970 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005971 bool Result;
5972 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5973 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005974
5975 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5976 }
5977
John McCall9f54ad42009-12-10 09:41:52 +00005978 if (Target->isFunctionOrFunctionTemplate()) {
5979 FunctionDecl *FD;
5980 if (isa<FunctionTemplateDecl>(Target))
5981 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5982 else
5983 FD = cast<FunctionDecl>(Target);
5984
5985 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005986 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005987 case Ovl_Overload:
5988 return false;
5989
5990 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005991 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005992 break;
5993
5994 // We found a decl with the exact signature.
5995 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005996 // If we're in a record, we want to hide the target, so we
5997 // return true (without a diagnostic) to tell the caller not to
5998 // build a shadow decl.
5999 if (CurContext->isRecord())
6000 return true;
6001
6002 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006003 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006004 break;
6005 }
6006
6007 Diag(Target->getLocation(), diag::note_using_decl_target);
6008 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6009 return true;
6010 }
6011
6012 // Target is not a function.
6013
John McCall9f54ad42009-12-10 09:41:52 +00006014 if (isa<TagDecl>(Target)) {
6015 // No conflict between a tag and a non-tag.
6016 if (!Tag) return false;
6017
John McCall41ce66f2009-12-10 19:51:03 +00006018 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006019 Diag(Target->getLocation(), diag::note_using_decl_target);
6020 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6021 return true;
6022 }
6023
6024 // No conflict between a tag and a non-tag.
6025 if (!NonTag) return false;
6026
John McCall41ce66f2009-12-10 19:51:03 +00006027 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006028 Diag(Target->getLocation(), diag::note_using_decl_target);
6029 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6030 return true;
6031}
6032
John McCall9488ea12009-11-17 05:59:44 +00006033/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006034UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006035 UsingDecl *UD,
6036 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006037
6038 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006039 NamedDecl *Target = Orig;
6040 if (isa<UsingShadowDecl>(Target)) {
6041 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6042 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006043 }
6044
6045 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006046 = UsingShadowDecl::Create(Context, CurContext,
6047 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006048 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006049
6050 Shadow->setAccess(UD->getAccess());
6051 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6052 Shadow->setInvalidDecl();
6053
John McCall9488ea12009-11-17 05:59:44 +00006054 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006055 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006056 else
John McCall604e7f12009-12-08 07:46:18 +00006057 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006058
John McCall604e7f12009-12-08 07:46:18 +00006059
John McCall9f54ad42009-12-10 09:41:52 +00006060 return Shadow;
6061}
John McCall604e7f12009-12-08 07:46:18 +00006062
John McCall9f54ad42009-12-10 09:41:52 +00006063/// Hides a using shadow declaration. This is required by the current
6064/// using-decl implementation when a resolvable using declaration in a
6065/// class is followed by a declaration which would hide or override
6066/// one or more of the using decl's targets; for example:
6067///
6068/// struct Base { void foo(int); };
6069/// struct Derived : Base {
6070/// using Base::foo;
6071/// void foo(int);
6072/// };
6073///
6074/// The governing language is C++03 [namespace.udecl]p12:
6075///
6076/// When a using-declaration brings names from a base class into a
6077/// derived class scope, member functions in the derived class
6078/// override and/or hide member functions with the same name and
6079/// parameter types in a base class (rather than conflicting).
6080///
6081/// There are two ways to implement this:
6082/// (1) optimistically create shadow decls when they're not hidden
6083/// by existing declarations, or
6084/// (2) don't create any shadow decls (or at least don't make them
6085/// visible) until we've fully parsed/instantiated the class.
6086/// The problem with (1) is that we might have to retroactively remove
6087/// a shadow decl, which requires several O(n) operations because the
6088/// decl structures are (very reasonably) not designed for removal.
6089/// (2) avoids this but is very fiddly and phase-dependent.
6090void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006091 if (Shadow->getDeclName().getNameKind() ==
6092 DeclarationName::CXXConversionFunctionName)
6093 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6094
John McCall9f54ad42009-12-10 09:41:52 +00006095 // Remove it from the DeclContext...
6096 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006097
John McCall9f54ad42009-12-10 09:41:52 +00006098 // ...and the scope, if applicable...
6099 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006100 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006101 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006102 }
6103
John McCall9f54ad42009-12-10 09:41:52 +00006104 // ...and the using decl.
6105 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6106
6107 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006108 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006109}
6110
John McCall7ba107a2009-11-18 02:36:19 +00006111/// Builds a using declaration.
6112///
6113/// \param IsInstantiation - Whether this call arises from an
6114/// instantiation of an unresolved using declaration. We treat
6115/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006116NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6117 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006118 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006119 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006120 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006121 bool IsInstantiation,
6122 bool IsTypeName,
6123 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006124 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006125 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006126 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006127
Anders Carlsson550b14b2009-08-28 05:49:21 +00006128 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006129
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006130 if (SS.isEmpty()) {
6131 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006132 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006133 }
Mike Stump1eb44332009-09-09 15:08:12 +00006134
John McCall9f54ad42009-12-10 09:41:52 +00006135 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006136 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006137 ForRedeclaration);
6138 Previous.setHideTags(false);
6139 if (S) {
6140 LookupName(Previous, S);
6141
6142 // It is really dumb that we have to do this.
6143 LookupResult::Filter F = Previous.makeFilter();
6144 while (F.hasNext()) {
6145 NamedDecl *D = F.next();
6146 if (!isDeclInScope(D, CurContext, S))
6147 F.erase();
6148 }
6149 F.done();
6150 } else {
6151 assert(IsInstantiation && "no scope in non-instantiation");
6152 assert(CurContext->isRecord() && "scope not record in instantiation");
6153 LookupQualifiedName(Previous, CurContext);
6154 }
6155
John McCall9f54ad42009-12-10 09:41:52 +00006156 // Check for invalid redeclarations.
6157 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6158 return 0;
6159
6160 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006161 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6162 return 0;
6163
John McCallaf8e6ed2009-11-12 03:15:40 +00006164 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006165 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006166 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006167 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006168 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006169 // FIXME: not all declaration name kinds are legal here
6170 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6171 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006172 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006173 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006174 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006175 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6176 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006177 }
John McCalled976492009-12-04 22:46:56 +00006178 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006179 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6180 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006181 }
John McCalled976492009-12-04 22:46:56 +00006182 D->setAccess(AS);
6183 CurContext->addDecl(D);
6184
6185 if (!LookupContext) return D;
6186 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006187
John McCall77bb1aa2010-05-01 00:40:08 +00006188 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006189 UD->setInvalidDecl();
6190 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006191 }
6192
Richard Smithc5a89a12012-04-02 01:30:27 +00006193 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006194 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006195 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006196 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006197 return UD;
6198 }
6199
6200 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006201
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006202 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006203
John McCall604e7f12009-12-08 07:46:18 +00006204 // Unlike most lookups, we don't always want to hide tag
6205 // declarations: tag names are visible through the using declaration
6206 // even if hidden by ordinary names, *except* in a dependent context
6207 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006208 if (!IsInstantiation)
6209 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006210
John McCallb9abd8722012-04-07 03:04:20 +00006211 // For the purposes of this lookup, we have a base object type
6212 // equal to that of the current context.
6213 if (CurContext->isRecord()) {
6214 R.setBaseObjectType(
6215 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6216 }
6217
John McCalla24dc2e2009-11-17 02:14:36 +00006218 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006219
John McCallf36e02d2009-10-09 21:13:30 +00006220 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006221 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006222 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006223 UD->setInvalidDecl();
6224 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006225 }
6226
John McCalled976492009-12-04 22:46:56 +00006227 if (R.isAmbiguous()) {
6228 UD->setInvalidDecl();
6229 return UD;
6230 }
Mike Stump1eb44332009-09-09 15:08:12 +00006231
John McCall7ba107a2009-11-18 02:36:19 +00006232 if (IsTypeName) {
6233 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006234 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006235 Diag(IdentLoc, diag::err_using_typename_non_type);
6236 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6237 Diag((*I)->getUnderlyingDecl()->getLocation(),
6238 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006239 UD->setInvalidDecl();
6240 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006241 }
6242 } else {
6243 // If we asked for a non-typename and we got a type, error out,
6244 // but only if this is an instantiation of an unresolved using
6245 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006246 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006247 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6248 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006249 UD->setInvalidDecl();
6250 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006251 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006252 }
6253
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006254 // C++0x N2914 [namespace.udecl]p6:
6255 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006256 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006257 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6258 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006259 UD->setInvalidDecl();
6260 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006261 }
Mike Stump1eb44332009-09-09 15:08:12 +00006262
John McCall9f54ad42009-12-10 09:41:52 +00006263 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6264 if (!CheckUsingShadowDecl(UD, *I, Previous))
6265 BuildUsingShadowDecl(S, UD, *I);
6266 }
John McCall9488ea12009-11-17 05:59:44 +00006267
6268 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006269}
6270
Sebastian Redlf677ea32011-02-05 19:23:19 +00006271/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006272bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6273 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006274
Douglas Gregordc355712011-02-25 00:36:19 +00006275 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006276 assert(SourceType &&
6277 "Using decl naming constructor doesn't have type in scope spec.");
6278 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6279
6280 // Check whether the named type is a direct base class.
6281 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6282 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6283 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6284 BaseIt != BaseE; ++BaseIt) {
6285 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6286 if (CanonicalSourceType == BaseType)
6287 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006288 if (BaseIt->getType()->isDependentType())
6289 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006290 }
6291
6292 if (BaseIt == BaseE) {
6293 // Did not find SourceType in the bases.
6294 Diag(UD->getUsingLocation(),
6295 diag::err_using_decl_constructor_not_in_direct_base)
6296 << UD->getNameInfo().getSourceRange()
6297 << QualType(SourceType, 0) << TargetClass;
6298 return true;
6299 }
6300
Richard Smithc5a89a12012-04-02 01:30:27 +00006301 if (!CurContext->isDependentContext())
6302 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006303
6304 return false;
6305}
6306
John McCall9f54ad42009-12-10 09:41:52 +00006307/// Checks that the given using declaration is not an invalid
6308/// redeclaration. Note that this is checking only for the using decl
6309/// itself, not for any ill-formedness among the UsingShadowDecls.
6310bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6311 bool isTypeName,
6312 const CXXScopeSpec &SS,
6313 SourceLocation NameLoc,
6314 const LookupResult &Prev) {
6315 // C++03 [namespace.udecl]p8:
6316 // C++0x [namespace.udecl]p10:
6317 // A using-declaration is a declaration and can therefore be used
6318 // repeatedly where (and only where) multiple declarations are
6319 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006320 //
John McCall8a726212010-11-29 18:01:58 +00006321 // That's in non-member contexts.
6322 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006323 return false;
6324
6325 NestedNameSpecifier *Qual
6326 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6327
6328 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6329 NamedDecl *D = *I;
6330
6331 bool DTypename;
6332 NestedNameSpecifier *DQual;
6333 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6334 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006335 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006336 } else if (UnresolvedUsingValueDecl *UD
6337 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6338 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006339 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006340 } else if (UnresolvedUsingTypenameDecl *UD
6341 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6342 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006343 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006344 } else continue;
6345
6346 // using decls differ if one says 'typename' and the other doesn't.
6347 // FIXME: non-dependent using decls?
6348 if (isTypeName != DTypename) continue;
6349
6350 // using decls differ if they name different scopes (but note that
6351 // template instantiation can cause this check to trigger when it
6352 // didn't before instantiation).
6353 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6354 Context.getCanonicalNestedNameSpecifier(DQual))
6355 continue;
6356
6357 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006358 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006359 return true;
6360 }
6361
6362 return false;
6363}
6364
John McCall604e7f12009-12-08 07:46:18 +00006365
John McCalled976492009-12-04 22:46:56 +00006366/// Checks that the given nested-name qualifier used in a using decl
6367/// in the current context is appropriately related to the current
6368/// scope. If an error is found, diagnoses it and returns true.
6369bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6370 const CXXScopeSpec &SS,
6371 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006372 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006373
John McCall604e7f12009-12-08 07:46:18 +00006374 if (!CurContext->isRecord()) {
6375 // C++03 [namespace.udecl]p3:
6376 // C++0x [namespace.udecl]p8:
6377 // A using-declaration for a class member shall be a member-declaration.
6378
6379 // If we weren't able to compute a valid scope, it must be a
6380 // dependent class scope.
6381 if (!NamedContext || NamedContext->isRecord()) {
6382 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6383 << SS.getRange();
6384 return true;
6385 }
6386
6387 // Otherwise, everything is known to be fine.
6388 return false;
6389 }
6390
6391 // The current scope is a record.
6392
6393 // If the named context is dependent, we can't decide much.
6394 if (!NamedContext) {
6395 // FIXME: in C++0x, we can diagnose if we can prove that the
6396 // nested-name-specifier does not refer to a base class, which is
6397 // still possible in some cases.
6398
6399 // Otherwise we have to conservatively report that things might be
6400 // okay.
6401 return false;
6402 }
6403
6404 if (!NamedContext->isRecord()) {
6405 // Ideally this would point at the last name in the specifier,
6406 // but we don't have that level of source info.
6407 Diag(SS.getRange().getBegin(),
6408 diag::err_using_decl_nested_name_specifier_is_not_class)
6409 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6410 return true;
6411 }
6412
Douglas Gregor6fb07292010-12-21 07:41:49 +00006413 if (!NamedContext->isDependentContext() &&
6414 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6415 return true;
6416
David Blaikie4e4d0842012-03-11 07:00:24 +00006417 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006418 // C++0x [namespace.udecl]p3:
6419 // In a using-declaration used as a member-declaration, the
6420 // nested-name-specifier shall name a base class of the class
6421 // being defined.
6422
6423 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6424 cast<CXXRecordDecl>(NamedContext))) {
6425 if (CurContext == NamedContext) {
6426 Diag(NameLoc,
6427 diag::err_using_decl_nested_name_specifier_is_current_class)
6428 << SS.getRange();
6429 return true;
6430 }
6431
6432 Diag(SS.getRange().getBegin(),
6433 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6434 << (NestedNameSpecifier*) SS.getScopeRep()
6435 << cast<CXXRecordDecl>(CurContext)
6436 << SS.getRange();
6437 return true;
6438 }
6439
6440 return false;
6441 }
6442
6443 // C++03 [namespace.udecl]p4:
6444 // A using-declaration used as a member-declaration shall refer
6445 // to a member of a base class of the class being defined [etc.].
6446
6447 // Salient point: SS doesn't have to name a base class as long as
6448 // lookup only finds members from base classes. Therefore we can
6449 // diagnose here only if we can prove that that can't happen,
6450 // i.e. if the class hierarchies provably don't intersect.
6451
6452 // TODO: it would be nice if "definitely valid" results were cached
6453 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6454 // need to be repeated.
6455
6456 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006457 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006458
6459 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6460 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6461 Data->Bases.insert(Base);
6462 return true;
6463 }
6464
6465 bool hasDependentBases(const CXXRecordDecl *Class) {
6466 return !Class->forallBases(collect, this);
6467 }
6468
6469 /// Returns true if the base is dependent or is one of the
6470 /// accumulated base classes.
6471 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6472 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6473 return !Data->Bases.count(Base);
6474 }
6475
6476 bool mightShareBases(const CXXRecordDecl *Class) {
6477 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6478 }
6479 };
6480
6481 UserData Data;
6482
6483 // Returns false if we find a dependent base.
6484 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6485 return false;
6486
6487 // Returns false if the class has a dependent base or if it or one
6488 // of its bases is present in the base set of the current context.
6489 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6490 return false;
6491
6492 Diag(SS.getRange().getBegin(),
6493 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6494 << (NestedNameSpecifier*) SS.getScopeRep()
6495 << cast<CXXRecordDecl>(CurContext)
6496 << SS.getRange();
6497
6498 return true;
John McCalled976492009-12-04 22:46:56 +00006499}
6500
Richard Smith162e1c12011-04-15 14:24:37 +00006501Decl *Sema::ActOnAliasDeclaration(Scope *S,
6502 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006503 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006504 SourceLocation UsingLoc,
6505 UnqualifiedId &Name,
6506 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006507 // Skip up to the relevant declaration scope.
6508 while (S->getFlags() & Scope::TemplateParamScope)
6509 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006510 assert((S->getFlags() & Scope::DeclScope) &&
6511 "got alias-declaration outside of declaration scope");
6512
6513 if (Type.isInvalid())
6514 return 0;
6515
6516 bool Invalid = false;
6517 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6518 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006519 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006520
6521 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6522 return 0;
6523
6524 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006525 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006526 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006527 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6528 TInfo->getTypeLoc().getBeginLoc());
6529 }
Richard Smith162e1c12011-04-15 14:24:37 +00006530
6531 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6532 LookupName(Previous, S);
6533
6534 // Warn about shadowing the name of a template parameter.
6535 if (Previous.isSingleResult() &&
6536 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006537 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006538 Previous.clear();
6539 }
6540
6541 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6542 "name in alias declaration must be an identifier");
6543 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6544 Name.StartLocation,
6545 Name.Identifier, TInfo);
6546
6547 NewTD->setAccess(AS);
6548
6549 if (Invalid)
6550 NewTD->setInvalidDecl();
6551
Richard Smith3e4c6c42011-05-05 21:57:07 +00006552 CheckTypedefForVariablyModifiedType(S, NewTD);
6553 Invalid |= NewTD->isInvalidDecl();
6554
Richard Smith162e1c12011-04-15 14:24:37 +00006555 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006556
6557 NamedDecl *NewND;
6558 if (TemplateParamLists.size()) {
6559 TypeAliasTemplateDecl *OldDecl = 0;
6560 TemplateParameterList *OldTemplateParams = 0;
6561
6562 if (TemplateParamLists.size() != 1) {
6563 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6564 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6565 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6566 }
6567 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6568
6569 // Only consider previous declarations in the same scope.
6570 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6571 /*ExplicitInstantiationOrSpecialization*/false);
6572 if (!Previous.empty()) {
6573 Redeclaration = true;
6574
6575 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6576 if (!OldDecl && !Invalid) {
6577 Diag(UsingLoc, diag::err_redefinition_different_kind)
6578 << Name.Identifier;
6579
6580 NamedDecl *OldD = Previous.getRepresentativeDecl();
6581 if (OldD->getLocation().isValid())
6582 Diag(OldD->getLocation(), diag::note_previous_definition);
6583
6584 Invalid = true;
6585 }
6586
6587 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6588 if (TemplateParameterListsAreEqual(TemplateParams,
6589 OldDecl->getTemplateParameters(),
6590 /*Complain=*/true,
6591 TPL_TemplateMatch))
6592 OldTemplateParams = OldDecl->getTemplateParameters();
6593 else
6594 Invalid = true;
6595
6596 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6597 if (!Invalid &&
6598 !Context.hasSameType(OldTD->getUnderlyingType(),
6599 NewTD->getUnderlyingType())) {
6600 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6601 // but we can't reasonably accept it.
6602 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6603 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6604 if (OldTD->getLocation().isValid())
6605 Diag(OldTD->getLocation(), diag::note_previous_definition);
6606 Invalid = true;
6607 }
6608 }
6609 }
6610
6611 // Merge any previous default template arguments into our parameters,
6612 // and check the parameter list.
6613 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6614 TPC_TypeAliasTemplate))
6615 return 0;
6616
6617 TypeAliasTemplateDecl *NewDecl =
6618 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6619 Name.Identifier, TemplateParams,
6620 NewTD);
6621
6622 NewDecl->setAccess(AS);
6623
6624 if (Invalid)
6625 NewDecl->setInvalidDecl();
6626 else if (OldDecl)
6627 NewDecl->setPreviousDeclaration(OldDecl);
6628
6629 NewND = NewDecl;
6630 } else {
6631 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6632 NewND = NewTD;
6633 }
Richard Smith162e1c12011-04-15 14:24:37 +00006634
6635 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006636 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006637
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00006638 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00006639 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006640}
6641
John McCalld226f652010-08-21 09:40:31 +00006642Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006643 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006644 SourceLocation AliasLoc,
6645 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006646 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006647 SourceLocation IdentLoc,
6648 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006649
Anders Carlsson81c85c42009-03-28 23:53:49 +00006650 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006651 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6652 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006653
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006654 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006655 NamedDecl *PrevDecl
6656 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6657 ForRedeclaration);
6658 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6659 PrevDecl = 0;
6660
6661 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006662 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006663 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006664 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006665 // FIXME: At some point, we'll want to create the (redundant)
6666 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006667 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006668 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006669 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006670 }
Mike Stump1eb44332009-09-09 15:08:12 +00006671
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006672 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6673 diag::err_redefinition_different_kind;
6674 Diag(AliasLoc, DiagID) << Alias;
6675 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006676 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006677 }
6678
John McCalla24dc2e2009-11-17 02:14:36 +00006679 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006680 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006681
John McCallf36e02d2009-10-09 21:13:30 +00006682 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006683 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006684 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006685 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006686 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006687 }
Mike Stump1eb44332009-09-09 15:08:12 +00006688
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006689 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006690 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006691 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006692 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006693
John McCall3dbd3d52010-02-16 06:53:13 +00006694 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006695 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006696}
6697
Douglas Gregor39957dc2010-05-01 15:04:51 +00006698namespace {
6699 /// \brief Scoped object used to handle the state changes required in Sema
6700 /// to implicitly define the body of a C++ member function;
6701 class ImplicitlyDefinedFunctionScope {
6702 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006703 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006704
6705 public:
6706 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006707 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006708 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006709 S.PushFunctionScope();
6710 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6711 }
6712
6713 ~ImplicitlyDefinedFunctionScope() {
6714 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006715 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006716 }
6717 };
6718}
6719
Sean Hunt001cad92011-05-10 00:49:42 +00006720Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00006721Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6722 CXXMethodDecl *MD) {
6723 CXXRecordDecl *ClassDecl = MD->getParent();
6724
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006725 // C++ [except.spec]p14:
6726 // An implicitly declared special member function (Clause 12) shall have an
6727 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00006728 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006729 if (ClassDecl->isInvalidDecl())
6730 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006731
Sebastian Redl60618fa2011-03-12 11:50:43 +00006732 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006733 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6734 BEnd = ClassDecl->bases_end();
6735 B != BEnd; ++B) {
6736 if (B->isVirtual()) // Handled below.
6737 continue;
6738
Douglas Gregor18274032010-07-03 00:47:00 +00006739 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6740 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006741 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6742 // If this is a deleted function, add it anyway. This might be conformant
6743 // with the standard. This might not. I'm not sure. It might not matter.
6744 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006745 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006746 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006747 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006748
6749 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006750 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6751 BEnd = ClassDecl->vbases_end();
6752 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006753 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6754 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006755 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6756 // If this is a deleted function, add it anyway. This might be conformant
6757 // with the standard. This might not. I'm not sure. It might not matter.
6758 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006759 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006760 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006761 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006762
6763 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006764 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6765 FEnd = ClassDecl->field_end();
6766 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006767 if (F->hasInClassInitializer()) {
6768 if (Expr *E = F->getInClassInitializer())
6769 ExceptSpec.CalledExpr(E);
6770 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00006771 // DR1351:
6772 // If the brace-or-equal-initializer of a non-static data member
6773 // invokes a defaulted default constructor of its class or of an
6774 // enclosing class in a potentially evaluated subexpression, the
6775 // program is ill-formed.
6776 //
6777 // This resolution is unworkable: the exception specification of the
6778 // default constructor can be needed in an unevaluated context, in
6779 // particular, in the operand of a noexcept-expression, and we can be
6780 // unable to compute an exception specification for an enclosed class.
6781 //
6782 // We do not allow an in-class initializer to require the evaluation
6783 // of the exception specification for any in-class initializer whose
6784 // definition is not lexically complete.
6785 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00006786 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006787 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006788 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6789 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6790 // If this is a deleted function, add it anyway. This might be conformant
6791 // with the standard. This might not. I'm not sure. It might not matter.
6792 // In particular, the problem is that this function never gets called. It
6793 // might just be ill-formed because this function attempts to refer to
6794 // a deleted function here.
6795 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006796 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006797 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006798 }
John McCalle23cf432010-12-14 08:05:40 +00006799
Sean Hunt001cad92011-05-10 00:49:42 +00006800 return ExceptSpec;
6801}
6802
6803CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6804 CXXRecordDecl *ClassDecl) {
6805 // C++ [class.ctor]p5:
6806 // A default constructor for a class X is a constructor of class X
6807 // that can be called without an argument. If there is no
6808 // user-declared constructor for class X, a default constructor is
6809 // implicitly declared. An implicitly-declared default constructor
6810 // is an inline public member of its class.
6811 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6812 "Should not build implicit default constructor!");
6813
Richard Smith7756afa2012-06-10 05:43:50 +00006814 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6815 CXXDefaultConstructor,
6816 false);
6817
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006818 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006819 CanQualType ClassType
6820 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006821 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006822 DeclarationName Name
6823 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006824 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006825 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00006826 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00006827 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00006828 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006829 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006830 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006831 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006832 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00006833
6834 // Build an exception specification pointing back at this constructor.
6835 FunctionProtoType::ExtProtoInfo EPI;
6836 EPI.ExceptionSpecType = EST_Unevaluated;
6837 EPI.ExceptionSpecDecl = DefaultCon;
6838 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6839
Douglas Gregor18274032010-07-03 00:47:00 +00006840 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006841 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6842
Douglas Gregor23c94db2010-07-02 17:43:08 +00006843 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006844 PushOnScopeChains(DefaultCon, S, false);
6845 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006846
Sean Hunte16da072011-10-10 06:18:57 +00006847 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006848 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006849
Douglas Gregor32df23e2010-07-01 22:02:46 +00006850 return DefaultCon;
6851}
6852
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006853void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6854 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006855 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006856 !Constructor->doesThisDeclarationHaveABody() &&
6857 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006858 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006859
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006860 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006861 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006862
Douglas Gregor39957dc2010-05-01 15:04:51 +00006863 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006864 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006865 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006866 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006867 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006868 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006869 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006870 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006871 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006872
6873 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00006874 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006875
6876 Constructor->setUsed();
6877 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006878
6879 if (ASTMutationListener *L = getASTMutationListener()) {
6880 L->CompletedImplicitDefinition(Constructor);
6881 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006882}
6883
Richard Smith7a614d82011-06-11 17:19:42 +00006884void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6885 if (!D) return;
6886 AdjustDeclIfTemplate(D);
6887
6888 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
Richard Smith7a614d82011-06-11 17:19:42 +00006889
Richard Smithb9d0b762012-07-27 04:22:15 +00006890 if (!ClassDecl->isDependentType())
6891 CheckExplicitlyDefaultedMethods(ClassDecl);
Richard Smith7a614d82011-06-11 17:19:42 +00006892}
6893
Sebastian Redlf677ea32011-02-05 19:23:19 +00006894void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6895 // We start with an initial pass over the base classes to collect those that
6896 // inherit constructors from. If there are none, we can forgo all further
6897 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006898 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006899 BasesVector BasesToInheritFrom;
6900 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6901 BaseE = ClassDecl->bases_end();
6902 BaseIt != BaseE; ++BaseIt) {
6903 if (BaseIt->getInheritConstructors()) {
6904 QualType Base = BaseIt->getType();
6905 if (Base->isDependentType()) {
6906 // If we inherit constructors from anything that is dependent, just
6907 // abort processing altogether. We'll get another chance for the
6908 // instantiations.
6909 return;
6910 }
6911 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6912 }
6913 }
6914 if (BasesToInheritFrom.empty())
6915 return;
6916
6917 // Now collect the constructors that we already have in the current class.
6918 // Those take precedence over inherited constructors.
6919 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6920 // unless there is a user-declared constructor with the same signature in
6921 // the class where the using-declaration appears.
6922 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6923 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6924 CtorE = ClassDecl->ctor_end();
6925 CtorIt != CtorE; ++CtorIt) {
6926 ExistingConstructors.insert(
6927 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6928 }
6929
Sebastian Redlf677ea32011-02-05 19:23:19 +00006930 DeclarationName CreatedCtorName =
6931 Context.DeclarationNames.getCXXConstructorName(
6932 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6933
6934 // Now comes the true work.
6935 // First, we keep a map from constructor types to the base that introduced
6936 // them. Needed for finding conflicting constructors. We also keep the
6937 // actually inserted declarations in there, for pretty diagnostics.
6938 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6939 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6940 ConstructorToSourceMap InheritedConstructors;
6941 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6942 BaseE = BasesToInheritFrom.end();
6943 BaseIt != BaseE; ++BaseIt) {
6944 const RecordType *Base = *BaseIt;
6945 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6946 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6947 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6948 CtorE = BaseDecl->ctor_end();
6949 CtorIt != CtorE; ++CtorIt) {
6950 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00006951 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00006952 DeclarationName Name =
6953 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00006954 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6955 LookupQualifiedName(Result, CurContext);
6956 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006957 SourceLocation UsingLoc = UD ? UD->getLocation() :
6958 ClassDecl->getLocation();
6959
6960 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6961 // from the class X named in the using-declaration consists of actual
6962 // constructors and notional constructors that result from the
6963 // transformation of defaulted parameters as follows:
6964 // - all non-template default constructors of X, and
6965 // - for each non-template constructor of X that has at least one
6966 // parameter with a default argument, the set of constructors that
6967 // results from omitting any ellipsis parameter specification and
6968 // successively omitting parameters with a default argument from the
6969 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00006970 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006971 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6972 const FunctionProtoType *BaseCtorType =
6973 BaseCtor->getType()->getAs<FunctionProtoType>();
6974
6975 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6976 maxParams = BaseCtor->getNumParams();
6977 params <= maxParams; ++params) {
6978 // Skip default constructors. They're never inherited.
6979 if (params == 0)
6980 continue;
6981 // Skip copy and move constructors for the same reason.
6982 if (CanBeCopyOrMove && params == 1)
6983 continue;
6984
6985 // Build up a function type for this particular constructor.
6986 // FIXME: The working paper does not consider that the exception spec
6987 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006988 // source. This code doesn't yet, either. When it does, this code will
6989 // need to be delayed until after exception specifications and in-class
6990 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006991 const Type *NewCtorType;
6992 if (params == maxParams)
6993 NewCtorType = BaseCtorType;
6994 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006995 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006996 for (unsigned i = 0; i < params; ++i) {
6997 Args.push_back(BaseCtorType->getArgType(i));
6998 }
6999 FunctionProtoType::ExtProtoInfo ExtInfo =
7000 BaseCtorType->getExtProtoInfo();
7001 ExtInfo.Variadic = false;
7002 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7003 Args.data(), params, ExtInfo)
7004 .getTypePtr();
7005 }
7006 const Type *CanonicalNewCtorType =
7007 Context.getCanonicalType(NewCtorType);
7008
7009 // Now that we have the type, first check if the class already has a
7010 // constructor with this signature.
7011 if (ExistingConstructors.count(CanonicalNewCtorType))
7012 continue;
7013
7014 // Then we check if we have already declared an inherited constructor
7015 // with this signature.
7016 std::pair<ConstructorToSourceMap::iterator, bool> result =
7017 InheritedConstructors.insert(std::make_pair(
7018 CanonicalNewCtorType,
7019 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7020 if (!result.second) {
7021 // Already in the map. If it came from a different class, that's an
7022 // error. Not if it's from the same.
7023 CanQualType PreviousBase = result.first->second.first;
7024 if (CanonicalBase != PreviousBase) {
7025 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7026 const CXXConstructorDecl *PrevBaseCtor =
7027 PrevCtor->getInheritedConstructor();
7028 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7029
7030 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7031 Diag(BaseCtor->getLocation(),
7032 diag::note_using_decl_constructor_conflict_current_ctor);
7033 Diag(PrevBaseCtor->getLocation(),
7034 diag::note_using_decl_constructor_conflict_previous_ctor);
7035 Diag(PrevCtor->getLocation(),
7036 diag::note_using_decl_constructor_conflict_previous_using);
7037 }
7038 continue;
7039 }
7040
7041 // OK, we're there, now add the constructor.
7042 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007043 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007044 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7045 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007046 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7047 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007048 /*ImplicitlyDeclared=*/true,
7049 // FIXME: Due to a defect in the standard, we treat inherited
7050 // constructors as constexpr even if that makes them ill-formed.
7051 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007052 NewCtor->setAccess(BaseCtor->getAccess());
7053
7054 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007055 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007056 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007057 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7058 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007059 /*IdentifierInfo=*/0,
7060 BaseCtorType->getArgType(i),
7061 /*TInfo=*/0, SC_None,
7062 SC_None, /*DefaultArg=*/0));
7063 }
David Blaikie4278c652011-09-21 18:16:56 +00007064 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007065 NewCtor->setInheritedConstructor(BaseCtor);
7066
Sebastian Redlf677ea32011-02-05 19:23:19 +00007067 ClassDecl->addDecl(NewCtor);
7068 result.first->second.second = NewCtor;
7069 }
7070 }
7071 }
7072}
7073
Sean Huntcb45a0f2011-05-12 22:46:25 +00007074Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007075Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7076 CXXRecordDecl *ClassDecl = MD->getParent();
7077
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007078 // C++ [except.spec]p14:
7079 // An implicitly declared special member function (Clause 12) shall have
7080 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007081 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007082 if (ClassDecl->isInvalidDecl())
7083 return ExceptSpec;
7084
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007085 // Direct base-class destructors.
7086 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7087 BEnd = ClassDecl->bases_end();
7088 B != BEnd; ++B) {
7089 if (B->isVirtual()) // Handled below.
7090 continue;
7091
7092 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007093 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007094 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007095 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007096
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007097 // Virtual base-class destructors.
7098 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7099 BEnd = ClassDecl->vbases_end();
7100 B != BEnd; ++B) {
7101 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007102 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007103 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007104 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007105
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007106 // Field destructors.
7107 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7108 FEnd = ClassDecl->field_end();
7109 F != FEnd; ++F) {
7110 if (const RecordType *RecordTy
7111 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007112 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007113 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007114 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007115
Sean Huntcb45a0f2011-05-12 22:46:25 +00007116 return ExceptSpec;
7117}
7118
7119CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7120 // C++ [class.dtor]p2:
7121 // If a class has no user-declared destructor, a destructor is
7122 // declared implicitly. An implicitly-declared destructor is an
7123 // inline public member of its class.
Sean Huntcb45a0f2011-05-12 22:46:25 +00007124
Douglas Gregor4923aa22010-07-02 20:37:36 +00007125 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007126 CanQualType ClassType
7127 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007128 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007129 DeclarationName Name
7130 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007131 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007132 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007133 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7134 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007135 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007136 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007137 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007138 Destructor->setImplicit();
7139 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00007140
7141 // Build an exception specification pointing back at this destructor.
7142 FunctionProtoType::ExtProtoInfo EPI;
7143 EPI.ExceptionSpecType = EST_Unevaluated;
7144 EPI.ExceptionSpecDecl = Destructor;
7145 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7146
Douglas Gregor4923aa22010-07-02 20:37:36 +00007147 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007148 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007149
Douglas Gregor4923aa22010-07-02 20:37:36 +00007150 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007151 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007152 PushOnScopeChains(Destructor, S, false);
7153 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007154
Richard Smith9a561d52012-02-26 09:11:52 +00007155 AddOverriddenMethods(ClassDecl, Destructor);
7156
Richard Smith7d5088a2012-02-18 02:02:13 +00007157 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007158 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007159
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007160 return Destructor;
7161}
7162
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007163void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007164 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007165 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007166 !Destructor->doesThisDeclarationHaveABody() &&
7167 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007168 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007169 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007170 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007171
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007172 if (Destructor->isInvalidDecl())
7173 return;
7174
Douglas Gregor39957dc2010-05-01 15:04:51 +00007175 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007176
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007177 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007178 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7179 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007180
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007181 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007182 Diag(CurrentLocation, diag::note_member_synthesized_at)
7183 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7184
7185 Destructor->setInvalidDecl();
7186 return;
7187 }
7188
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007189 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007190 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007191 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007192 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007193 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007194
7195 if (ASTMutationListener *L = getASTMutationListener()) {
7196 L->CompletedImplicitDefinition(Destructor);
7197 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007198}
7199
Richard Smitha4156b82012-04-21 18:42:51 +00007200/// \brief Perform any semantic analysis which needs to be delayed until all
7201/// pending class member declarations have been parsed.
7202void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007203 // Perform any deferred checking of exception specifications for virtual
7204 // destructors.
7205 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7206 i != e; ++i) {
7207 const CXXDestructorDecl *Dtor =
7208 DelayedDestructorExceptionSpecChecks[i].first;
7209 assert(!Dtor->getParent()->isDependentType() &&
7210 "Should not ever add destructors of templates into the list.");
7211 CheckOverridingFunctionExceptionSpec(Dtor,
7212 DelayedDestructorExceptionSpecChecks[i].second);
7213 }
7214 DelayedDestructorExceptionSpecChecks.clear();
7215}
7216
Richard Smithb9d0b762012-07-27 04:22:15 +00007217void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7218 CXXDestructorDecl *Destructor) {
7219 assert(getLangOpts().CPlusPlus0x &&
7220 "adjusting dtor exception specs was introduced in c++11");
7221
Sebastian Redl0ee33912011-05-19 05:13:44 +00007222 // C++11 [class.dtor]p3:
7223 // A declaration of a destructor that does not have an exception-
7224 // specification is implicitly considered to have the same exception-
7225 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007226 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007227 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007228 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007229 return;
7230
Chandler Carruth3f224b22011-09-20 04:55:26 +00007231 // Replace the destructor's type, building off the existing one. Fortunately,
7232 // the only thing of interest in the destructor type is its extended info.
7233 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007234 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7235 EPI.ExceptionSpecType = EST_Unevaluated;
7236 EPI.ExceptionSpecDecl = Destructor;
7237 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007238
Sebastian Redl0ee33912011-05-19 05:13:44 +00007239 // FIXME: If the destructor has a body that could throw, and the newly created
7240 // spec doesn't allow exceptions, we should emit a warning, because this
7241 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007242 // However, we don't have a body or an exception specification yet, so it
7243 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007244}
7245
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007246/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007247/// \c To.
7248///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007249/// This routine is used to copy/move the members of a class with an
7250/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007251/// copied are arrays, this routine builds for loops to copy them.
7252///
7253/// \param S The Sema object used for type-checking.
7254///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007255/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007256///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007257/// \param T The type of the expressions being copied/moved. Both expressions
7258/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007259///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007260/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007261///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007262/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007263///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007264/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007265/// Otherwise, it's a non-static member subobject.
7266///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007267/// \param Copying Whether we're copying or moving.
7268///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007269/// \param Depth Internal parameter recording the depth of the recursion.
7270///
7271/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007272static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007273BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007274 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007275 bool CopyingBaseSubobject, bool Copying,
7276 unsigned Depth = 0) {
7277 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007278 // Each subobject is assigned in the manner appropriate to its type:
7279 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007280 // - if the subobject is of class type, as if by a call to operator= with
7281 // the subobject as the object expression and the corresponding
7282 // subobject of x as a single function argument (as if by explicit
7283 // qualification; that is, ignoring any possible virtual overriding
7284 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007285 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7286 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7287
7288 // Look for operator=.
7289 DeclarationName Name
7290 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7291 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7292 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7293
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007294 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007295 LookupResult::Filter F = OpLookup.makeFilter();
7296 while (F.hasNext()) {
7297 NamedDecl *D = F.next();
7298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007299 if (Method->isCopyAssignmentOperator() ||
7300 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007301 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007302
Douglas Gregor06a9f362010-05-01 20:49:11 +00007303 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007304 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007305 F.done();
7306
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007307 // Suppress the protected check (C++ [class.protected]) for each of the
7308 // assignment operators we found. This strange dance is required when
7309 // we're assigning via a base classes's copy-assignment operator. To
7310 // ensure that we're getting the right base class subobject (without
7311 // ambiguities), we need to cast "this" to that subobject type; to
7312 // ensure that we don't go through the virtual call mechanism, we need
7313 // to qualify the operator= name with the base class (see below). However,
7314 // this means that if the base class has a protected copy assignment
7315 // operator, the protected member access check will fail. So, we
7316 // rewrite "protected" access to "public" access in this case, since we
7317 // know by construction that we're calling from a derived class.
7318 if (CopyingBaseSubobject) {
7319 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7320 L != LEnd; ++L) {
7321 if (L.getAccess() == AS_protected)
7322 L.setAccess(AS_public);
7323 }
7324 }
7325
Douglas Gregor06a9f362010-05-01 20:49:11 +00007326 // Create the nested-name-specifier that will be used to qualify the
7327 // reference to operator=; this is required to suppress the virtual
7328 // call mechanism.
7329 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007330 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007331 SS.MakeTrivial(S.Context,
7332 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007333 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007334 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007335
7336 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007337 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007338 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007339 /*TemplateKWLoc=*/SourceLocation(),
7340 /*FirstQualifierInScope=*/0,
7341 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007342 /*TemplateArgs=*/0,
7343 /*SuppressQualifierCheck=*/true);
7344 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007345 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007346
7347 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007348
John McCall60d7b3a2010-08-24 06:29:42 +00007349 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007350 OpEqualRef.takeAs<Expr>(),
7351 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007352 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007353 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007354
7355 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007356 }
John McCallb0207482010-03-16 06:11:48 +00007357
Douglas Gregor06a9f362010-05-01 20:49:11 +00007358 // - if the subobject is of scalar type, the built-in assignment
7359 // operator is used.
7360 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7361 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007362 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007363 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007364 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007365
7366 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007367 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007368
7369 // - if the subobject is an array, each element is assigned, in the
7370 // manner appropriate to the element type;
7371
7372 // Construct a loop over the array bounds, e.g.,
7373 //
7374 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7375 //
7376 // that will copy each of the array elements.
7377 QualType SizeType = S.Context.getSizeType();
7378
7379 // Create the iteration variable.
7380 IdentifierInfo *IterationVarName = 0;
7381 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007382 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007383 llvm::raw_svector_ostream OS(Str);
7384 OS << "__i" << Depth;
7385 IterationVarName = &S.Context.Idents.get(OS.str());
7386 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007387 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007388 IterationVarName, SizeType,
7389 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007390 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007391
7392 // Initialize the iteration variable to zero.
7393 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007394 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007395
7396 // Create a reference to the iteration variable; we'll use this several
7397 // times throughout.
7398 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007399 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007400 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007401 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7402 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7403
Douglas Gregor06a9f362010-05-01 20:49:11 +00007404 // Create the DeclStmt that holds the iteration variable.
7405 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7406
7407 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007408 llvm::APInt Upper
7409 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007410 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007411 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007412 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7413 BO_NE, S.Context.BoolTy,
7414 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007415
7416 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007417 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007418 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7419 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007420
7421 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007422 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007423 IterationVarRefRVal,
7424 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007425 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007426 IterationVarRefRVal,
7427 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007428 if (!Copying) // Cast to rvalue
7429 From = CastForMoving(S, From);
7430
7431 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007432 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7433 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007434 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007435 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007436 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007437
7438 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007439 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007440 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007441 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007442 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007443}
7444
Richard Smithb9d0b762012-07-27 04:22:15 +00007445/// Determine whether an implicit copy assignment operator for ClassDecl has a
7446/// const argument.
7447/// FIXME: It ought to be possible to store this on the record.
7448static bool isImplicitCopyAssignmentArgConst(Sema &S,
7449 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007450 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007451 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007452
Douglas Gregord3c35902010-07-01 16:36:15 +00007453 // C++ [class.copy]p10:
7454 // If the class definition does not explicitly declare a copy
7455 // assignment operator, one is declared implicitly.
7456 // The implicitly-defined copy assignment operator for a class X
7457 // will have the form
7458 //
7459 // X& X::operator=(const X&)
7460 //
7461 // if
Douglas Gregord3c35902010-07-01 16:36:15 +00007462 // -- each direct base class B of X has a copy assignment operator
7463 // whose parameter is of type const B&, const volatile B& or B,
7464 // and
7465 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7466 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007467 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007468 // We'll handle this below
Richard Smithb9d0b762012-07-27 04:22:15 +00007469 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00007470 continue;
7471
Douglas Gregord3c35902010-07-01 16:36:15 +00007472 assert(!Base->getType()->isDependentType() &&
7473 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007474 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007475 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7476 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007477 }
7478
Richard Smithebaf0e62011-10-18 20:49:44 +00007479 // In C++11, the above citation has "or virtual" added
Richard Smithb9d0b762012-07-27 04:22:15 +00007480 if (S.getLangOpts().CPlusPlus0x) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007481 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7482 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007483 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007484 assert(!Base->getType()->isDependentType() &&
7485 "Cannot generate implicit members for class with dependent bases.");
7486 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007487 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7488 false, 0))
7489 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007490 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007491 }
7492
7493 // -- for all the nonstatic data members of X that are of a class
7494 // type M (or array thereof), each such class type has a copy
7495 // assignment operator whose parameter is of type const M&,
7496 // const volatile M& or M.
7497 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7498 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007499 Field != FieldEnd; ++Field) {
7500 QualType FieldType = S.Context.getBaseElementType(Field->getType());
7501 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7502 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7503 false, 0))
7504 return false;
Douglas Gregord3c35902010-07-01 16:36:15 +00007505 }
7506
7507 // Otherwise, the implicitly declared copy assignment operator will
7508 // have the form
7509 //
7510 // X& X::operator=(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00007511
7512 return true;
7513}
7514
7515Sema::ImplicitExceptionSpecification
7516Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7517 CXXRecordDecl *ClassDecl = MD->getParent();
7518
7519 ImplicitExceptionSpecification ExceptSpec(*this);
7520 if (ClassDecl->isInvalidDecl())
7521 return ExceptSpec;
7522
7523 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7524 assert(T->getNumArgs() == 1 && "not a copy assignment op");
7525 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7526
Douglas Gregorb87786f2010-07-01 17:48:08 +00007527 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00007528 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00007529 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007530
7531 // It is unspecified whether or not an implicit copy assignment operator
7532 // attempts to deduplicate calls to assignment operators of virtual bases are
7533 // made. As such, this exception specification is effectively unspecified.
7534 // Based on a similar decision made for constness in C++0x, we're erring on
7535 // the side of assuming such calls to be made regardless of whether they
7536 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007537 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7538 BaseEnd = ClassDecl->bases_end();
7539 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007540 if (Base->isVirtual())
7541 continue;
7542
Douglas Gregora376d102010-07-02 21:50:04 +00007543 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007544 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007545 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7546 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007547 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00007548 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007549
7550 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7551 BaseEnd = ClassDecl->vbases_end();
7552 Base != BaseEnd; ++Base) {
7553 CXXRecordDecl *BaseClassDecl
7554 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7555 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7556 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007557 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00007558 }
7559
Douglas Gregorb87786f2010-07-01 17:48:08 +00007560 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7561 FieldEnd = ClassDecl->field_end();
7562 Field != FieldEnd;
7563 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007564 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007565 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7566 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00007567 LookupCopyingAssignment(FieldClassDecl,
7568 ArgQuals | FieldType.getCVRQualifiers(),
7569 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007570 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007571 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007572 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007573
Richard Smithb9d0b762012-07-27 04:22:15 +00007574 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00007575}
7576
7577CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7578 // Note: The following rules are largely analoguous to the copy
7579 // constructor rules. Note that virtual bases are not taken into account
7580 // for determining the argument type of the operator. Note also that
7581 // operators taking an object instead of a reference are allowed.
7582
Sean Hunt30de05c2011-05-14 05:23:20 +00007583 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7584 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithb9d0b762012-07-27 04:22:15 +00007585 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
Sean Hunt30de05c2011-05-14 05:23:20 +00007586 ArgType = ArgType.withConst();
7587 ArgType = Context.getLValueReferenceType(ArgType);
7588
Douglas Gregord3c35902010-07-01 16:36:15 +00007589 // An implicitly-declared copy assignment operator is an inline public
7590 // member of its class.
7591 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007592 SourceLocation ClassLoc = ClassDecl->getLocation();
7593 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007594 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00007595 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00007596 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007597 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007598 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007599 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007600 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007601 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007602 CopyAssignment->setImplicit();
7603 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Richard Smithb9d0b762012-07-27 04:22:15 +00007604
7605 // Build an exception specification pointing back at this member.
7606 FunctionProtoType::ExtProtoInfo EPI;
7607 EPI.ExceptionSpecType = EST_Unevaluated;
7608 EPI.ExceptionSpecDecl = CopyAssignment;
7609 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7610
Douglas Gregord3c35902010-07-01 16:36:15 +00007611 // Add the parameter to the operator.
7612 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007613 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007614 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007615 SC_None,
7616 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007617 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007618
Douglas Gregora376d102010-07-02 21:50:04 +00007619 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007620 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007621
Douglas Gregor23c94db2010-07-02 17:43:08 +00007622 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007623 PushOnScopeChains(CopyAssignment, S, false);
7624 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007625
Nico Weberafcc96a2012-01-23 03:19:29 +00007626 // C++0x [class.copy]p19:
7627 // .... If the class definition does not explicitly declare a copy
7628 // assignment operator, there is no user-declared move constructor, and
7629 // there is no user-declared move assignment operator, a copy assignment
7630 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007631 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007632 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007633
Douglas Gregord3c35902010-07-01 16:36:15 +00007634 AddOverriddenMethods(ClassDecl, CopyAssignment);
7635 return CopyAssignment;
7636}
7637
Douglas Gregor06a9f362010-05-01 20:49:11 +00007638void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7639 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007640 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007641 CopyAssignOperator->isOverloadedOperator() &&
7642 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007643 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7644 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007645 "DefineImplicitCopyAssignment called for wrong function");
7646
7647 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7648
7649 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7650 CopyAssignOperator->setInvalidDecl();
7651 return;
7652 }
7653
7654 CopyAssignOperator->setUsed();
7655
7656 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007657 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007658
7659 // C++0x [class.copy]p30:
7660 // The implicitly-defined or explicitly-defaulted copy assignment operator
7661 // for a non-union class X performs memberwise copy assignment of its
7662 // subobjects. The direct base classes of X are assigned first, in the
7663 // order of their declaration in the base-specifier-list, and then the
7664 // immediate non-static data members of X are assigned, in the order in
7665 // which they were declared in the class definition.
7666
7667 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007668 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007669
7670 // The parameter for the "other" object, which we are copying from.
7671 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7672 Qualifiers OtherQuals = Other->getType().getQualifiers();
7673 QualType OtherRefType = Other->getType();
7674 if (const LValueReferenceType *OtherRef
7675 = OtherRefType->getAs<LValueReferenceType>()) {
7676 OtherRefType = OtherRef->getPointeeType();
7677 OtherQuals = OtherRefType.getQualifiers();
7678 }
7679
7680 // Our location for everything implicitly-generated.
7681 SourceLocation Loc = CopyAssignOperator->getLocation();
7682
7683 // Construct a reference to the "other" object. We'll be using this
7684 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007685 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007686 assert(OtherRef && "Reference to parameter cannot fail!");
7687
7688 // Construct the "this" pointer. We'll be using this throughout the generated
7689 // ASTs.
7690 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7691 assert(This && "Reference to this cannot fail!");
7692
7693 // Assign base classes.
7694 bool Invalid = false;
7695 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7696 E = ClassDecl->bases_end(); Base != E; ++Base) {
7697 // Form the assignment:
7698 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7699 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007700 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007701 Invalid = true;
7702 continue;
7703 }
7704
John McCallf871d0c2010-08-07 06:22:56 +00007705 CXXCastPath BasePath;
7706 BasePath.push_back(Base);
7707
Douglas Gregor06a9f362010-05-01 20:49:11 +00007708 // Construct the "from" expression, which is an implicit cast to the
7709 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007710 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007711 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7712 CK_UncheckedDerivedToBase,
7713 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007714
7715 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007716 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007717
7718 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007719 To = ImpCastExprToType(To.take(),
7720 Context.getCVRQualifiedType(BaseType,
7721 CopyAssignOperator->getTypeQualifiers()),
7722 CK_UncheckedDerivedToBase,
7723 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007724
7725 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007726 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007727 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007728 /*CopyingBaseSubobject=*/true,
7729 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007730 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007731 Diag(CurrentLocation, diag::note_member_synthesized_at)
7732 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7733 CopyAssignOperator->setInvalidDecl();
7734 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007735 }
7736
7737 // Success! Record the copy.
7738 Statements.push_back(Copy.takeAs<Expr>());
7739 }
7740
7741 // \brief Reference to the __builtin_memcpy function.
7742 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007743 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007744 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007745
7746 // Assign non-static members.
7747 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7748 FieldEnd = ClassDecl->field_end();
7749 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007750 if (Field->isUnnamedBitfield())
7751 continue;
7752
Douglas Gregor06a9f362010-05-01 20:49:11 +00007753 // Check for members of reference type; we can't copy those.
7754 if (Field->getType()->isReferenceType()) {
7755 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7756 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7757 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007758 Diag(CurrentLocation, diag::note_member_synthesized_at)
7759 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007760 Invalid = true;
7761 continue;
7762 }
7763
7764 // Check for members of const-qualified, non-class type.
7765 QualType BaseType = Context.getBaseElementType(Field->getType());
7766 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7767 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7768 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7769 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007770 Diag(CurrentLocation, diag::note_member_synthesized_at)
7771 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007772 Invalid = true;
7773 continue;
7774 }
John McCallb77115d2011-06-17 00:18:42 +00007775
7776 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007777 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7778 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007779
7780 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007781 if (FieldType->isIncompleteArrayType()) {
7782 assert(ClassDecl->hasFlexibleArrayMember() &&
7783 "Incomplete array type is not valid");
7784 continue;
7785 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007786
7787 // Build references to the field in the object we're copying from and to.
7788 CXXScopeSpec SS; // Intentionally empty
7789 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7790 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00007791 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007792 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007793 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007794 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007795 SS, SourceLocation(), 0,
7796 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007797 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007798 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007799 SS, SourceLocation(), 0,
7800 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007801 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7802 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7803
7804 // If the field should be copied with __builtin_memcpy rather than via
7805 // explicit assignments, do so. This optimization only applies for arrays
7806 // of scalars and arrays of class type with trivial copy-assignment
7807 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007808 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007809 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007810 // Compute the size of the memory buffer to be copied.
7811 QualType SizeType = Context.getSizeType();
7812 llvm::APInt Size(Context.getTypeSize(SizeType),
7813 Context.getTypeSizeInChars(BaseType).getQuantity());
7814 for (const ConstantArrayType *Array
7815 = Context.getAsConstantArrayType(FieldType);
7816 Array;
7817 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007818 llvm::APInt ArraySize
7819 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007820 Size *= ArraySize;
7821 }
7822
7823 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007824 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7825 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007826
7827 bool NeedsCollectableMemCpy =
7828 (BaseType->isRecordType() &&
7829 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7830
7831 if (NeedsCollectableMemCpy) {
7832 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007833 // Create a reference to the __builtin_objc_memmove_collectable function.
7834 LookupResult R(*this,
7835 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007836 Loc, LookupOrdinaryName);
7837 LookupName(R, TUScope, true);
7838
7839 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7840 if (!CollectableMemCpy) {
7841 // Something went horribly wrong earlier, and we will have
7842 // complained about it.
7843 Invalid = true;
7844 continue;
7845 }
7846
7847 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7848 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007849 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007850 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7851 }
7852 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007853 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007854 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007855 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7856 LookupOrdinaryName);
7857 LookupName(R, TUScope, true);
7858
7859 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7860 if (!BuiltinMemCpy) {
7861 // Something went horribly wrong earlier, and we will have complained
7862 // about it.
7863 Invalid = true;
7864 continue;
7865 }
7866
7867 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7868 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007869 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007870 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7871 }
7872
John McCallca0408f2010-08-23 06:44:23 +00007873 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007874 CallArgs.push_back(To.takeAs<Expr>());
7875 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007876 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007877 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007878 if (NeedsCollectableMemCpy)
7879 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007880 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007881 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007882 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007883 else
7884 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007885 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007886 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007887 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007888
Douglas Gregor06a9f362010-05-01 20:49:11 +00007889 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7890 Statements.push_back(Call.takeAs<Expr>());
7891 continue;
7892 }
7893
7894 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007895 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007896 To.get(), From.get(),
7897 /*CopyingBaseSubobject=*/false,
7898 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007899 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007900 Diag(CurrentLocation, diag::note_member_synthesized_at)
7901 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7902 CopyAssignOperator->setInvalidDecl();
7903 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007904 }
7905
7906 // Success! Record the copy.
7907 Statements.push_back(Copy.takeAs<Stmt>());
7908 }
7909
7910 if (!Invalid) {
7911 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007912 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007913
John McCall60d7b3a2010-08-24 06:29:42 +00007914 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007915 if (Return.isInvalid())
7916 Invalid = true;
7917 else {
7918 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007919
7920 if (Trap.hasErrorOccurred()) {
7921 Diag(CurrentLocation, diag::note_member_synthesized_at)
7922 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7923 Invalid = true;
7924 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007925 }
7926 }
7927
7928 if (Invalid) {
7929 CopyAssignOperator->setInvalidDecl();
7930 return;
7931 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007932
7933 StmtResult Body;
7934 {
7935 CompoundScopeRAII CompoundScope(*this);
7936 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7937 /*isStmtExpr=*/false);
7938 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7939 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007940 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007941
7942 if (ASTMutationListener *L = getASTMutationListener()) {
7943 L->CompletedImplicitDefinition(CopyAssignOperator);
7944 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007945}
7946
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007947Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007948Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
7949 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007950
Richard Smithb9d0b762012-07-27 04:22:15 +00007951 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007952 if (ClassDecl->isInvalidDecl())
7953 return ExceptSpec;
7954
7955 // C++0x [except.spec]p14:
7956 // An implicitly declared special member function (Clause 12) shall have an
7957 // exception-specification. [...]
7958
7959 // It is unspecified whether or not an implicit move assignment operator
7960 // attempts to deduplicate calls to assignment operators of virtual bases are
7961 // made. As such, this exception specification is effectively unspecified.
7962 // Based on a similar decision made for constness in C++0x, we're erring on
7963 // the side of assuming such calls to be made regardless of whether they
7964 // actually happen.
7965 // Note that a move constructor is not implicitly declared when there are
7966 // virtual bases, but it can still be user-declared and explicitly defaulted.
7967 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7968 BaseEnd = ClassDecl->bases_end();
7969 Base != BaseEnd; ++Base) {
7970 if (Base->isVirtual())
7971 continue;
7972
7973 CXXRecordDecl *BaseClassDecl
7974 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7975 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007976 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007977 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007978 }
7979
7980 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7981 BaseEnd = ClassDecl->vbases_end();
7982 Base != BaseEnd; ++Base) {
7983 CXXRecordDecl *BaseClassDecl
7984 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7985 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007986 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007987 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007988 }
7989
7990 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7991 FieldEnd = ClassDecl->field_end();
7992 Field != FieldEnd;
7993 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007994 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007995 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00007996 if (CXXMethodDecl *MoveAssign =
7997 LookupMovingAssignment(FieldClassDecl,
7998 FieldType.getCVRQualifiers(),
7999 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008000 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008001 }
8002 }
8003
8004 return ExceptSpec;
8005}
8006
Richard Smith1c931be2012-04-02 18:40:40 +00008007/// Determine whether the class type has any direct or indirect virtual base
8008/// classes which have a non-trivial move assignment operator.
8009static bool
8010hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8011 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8012 BaseEnd = ClassDecl->vbases_end();
8013 Base != BaseEnd; ++Base) {
8014 CXXRecordDecl *BaseClass =
8015 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8016
8017 // Try to declare the move assignment. If it would be deleted, then the
8018 // class does not have a non-trivial move assignment.
8019 if (BaseClass->needsImplicitMoveAssignment())
8020 S.DeclareImplicitMoveAssignment(BaseClass);
8021
8022 // If the class has both a trivial move assignment and a non-trivial move
8023 // assignment, hasTrivialMoveAssignment() is false.
8024 if (BaseClass->hasDeclaredMoveAssignment() &&
8025 !BaseClass->hasTrivialMoveAssignment())
8026 return true;
8027 }
8028
8029 return false;
8030}
8031
8032/// Determine whether the given type either has a move constructor or is
8033/// trivially copyable.
8034static bool
8035hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8036 Type = S.Context.getBaseElementType(Type);
8037
8038 // FIXME: Technically, non-trivially-copyable non-class types, such as
8039 // reference types, are supposed to return false here, but that appears
8040 // to be a standard defect.
8041 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Richard Smith5d59b792012-04-25 18:28:49 +00008042 if (!ClassDecl || !ClassDecl->getDefinition())
Richard Smith1c931be2012-04-02 18:40:40 +00008043 return true;
8044
8045 if (Type.isTriviallyCopyableType(S.Context))
8046 return true;
8047
8048 if (IsConstructor) {
8049 if (ClassDecl->needsImplicitMoveConstructor())
8050 S.DeclareImplicitMoveConstructor(ClassDecl);
8051 return ClassDecl->hasDeclaredMoveConstructor();
8052 }
8053
8054 if (ClassDecl->needsImplicitMoveAssignment())
8055 S.DeclareImplicitMoveAssignment(ClassDecl);
8056 return ClassDecl->hasDeclaredMoveAssignment();
8057}
8058
8059/// Determine whether all non-static data members and direct or virtual bases
8060/// of class \p ClassDecl have either a move operation, or are trivially
8061/// copyable.
8062static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8063 bool IsConstructor) {
8064 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8065 BaseEnd = ClassDecl->bases_end();
8066 Base != BaseEnd; ++Base) {
8067 if (Base->isVirtual())
8068 continue;
8069
8070 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8071 return false;
8072 }
8073
8074 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8075 BaseEnd = ClassDecl->vbases_end();
8076 Base != BaseEnd; ++Base) {
8077 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8078 return false;
8079 }
8080
8081 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8082 FieldEnd = ClassDecl->field_end();
8083 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008084 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008085 return false;
8086 }
8087
8088 return true;
8089}
8090
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008091CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008092 // C++11 [class.copy]p20:
8093 // If the definition of a class X does not explicitly declare a move
8094 // assignment operator, one will be implicitly declared as defaulted
8095 // if and only if:
8096 //
8097 // - [first 4 bullets]
8098 assert(ClassDecl->needsImplicitMoveAssignment());
8099
8100 // [Checked after we build the declaration]
8101 // - the move assignment operator would not be implicitly defined as
8102 // deleted,
8103
8104 // [DR1402]:
8105 // - X has no direct or indirect virtual base class with a non-trivial
8106 // move assignment operator, and
8107 // - each of X's non-static data members and direct or virtual base classes
8108 // has a type that either has a move assignment operator or is trivially
8109 // copyable.
8110 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8111 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8112 ClassDecl->setFailedImplicitMoveAssignment();
8113 return 0;
8114 }
8115
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008116 // Note: The following rules are largely analoguous to the move
8117 // constructor rules.
8118
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008119 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8120 QualType RetType = Context.getLValueReferenceType(ArgType);
8121 ArgType = Context.getRValueReferenceType(ArgType);
8122
8123 // An implicitly-declared move assignment operator is an inline public
8124 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008125 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8126 SourceLocation ClassLoc = ClassDecl->getLocation();
8127 DeclarationNameInfo NameInfo(Name, ClassLoc);
8128 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008129 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008130 /*TInfo=*/0, /*isStatic=*/false,
8131 /*StorageClassAsWritten=*/SC_None,
8132 /*isInline=*/true,
8133 /*isConstexpr=*/false,
8134 SourceLocation());
8135 MoveAssignment->setAccess(AS_public);
8136 MoveAssignment->setDefaulted();
8137 MoveAssignment->setImplicit();
8138 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8139
Richard Smithb9d0b762012-07-27 04:22:15 +00008140 // Build an exception specification pointing back at this member.
8141 FunctionProtoType::ExtProtoInfo EPI;
8142 EPI.ExceptionSpecType = EST_Unevaluated;
8143 EPI.ExceptionSpecDecl = MoveAssignment;
8144 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8145
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008146 // Add the parameter to the operator.
8147 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8148 ClassLoc, ClassLoc, /*Id=*/0,
8149 ArgType, /*TInfo=*/0,
8150 SC_None,
8151 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008152 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008153
8154 // Note that we have added this copy-assignment operator.
8155 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8156
8157 // C++0x [class.copy]p9:
8158 // If the definition of a class X does not explicitly declare a move
8159 // assignment operator, one will be implicitly declared as defaulted if and
8160 // only if:
8161 // [...]
8162 // - the move assignment operator would not be implicitly defined as
8163 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008164 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008165 // Cache this result so that we don't try to generate this over and over
8166 // on every lookup, leaking memory and wasting time.
8167 ClassDecl->setFailedImplicitMoveAssignment();
8168 return 0;
8169 }
8170
8171 if (Scope *S = getScopeForContext(ClassDecl))
8172 PushOnScopeChains(MoveAssignment, S, false);
8173 ClassDecl->addDecl(MoveAssignment);
8174
8175 AddOverriddenMethods(ClassDecl, MoveAssignment);
8176 return MoveAssignment;
8177}
8178
8179void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8180 CXXMethodDecl *MoveAssignOperator) {
8181 assert((MoveAssignOperator->isDefaulted() &&
8182 MoveAssignOperator->isOverloadedOperator() &&
8183 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008184 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8185 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008186 "DefineImplicitMoveAssignment called for wrong function");
8187
8188 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8189
8190 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8191 MoveAssignOperator->setInvalidDecl();
8192 return;
8193 }
8194
8195 MoveAssignOperator->setUsed();
8196
8197 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8198 DiagnosticErrorTrap Trap(Diags);
8199
8200 // C++0x [class.copy]p28:
8201 // The implicitly-defined or move assignment operator for a non-union class
8202 // X performs memberwise move assignment of its subobjects. The direct base
8203 // classes of X are assigned first, in the order of their declaration in the
8204 // base-specifier-list, and then the immediate non-static data members of X
8205 // are assigned, in the order in which they were declared in the class
8206 // definition.
8207
8208 // The statements that form the synthesized function body.
8209 ASTOwningVector<Stmt*> Statements(*this);
8210
8211 // The parameter for the "other" object, which we are move from.
8212 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8213 QualType OtherRefType = Other->getType()->
8214 getAs<RValueReferenceType>()->getPointeeType();
8215 assert(OtherRefType.getQualifiers() == 0 &&
8216 "Bad argument type of defaulted move assignment");
8217
8218 // Our location for everything implicitly-generated.
8219 SourceLocation Loc = MoveAssignOperator->getLocation();
8220
8221 // Construct a reference to the "other" object. We'll be using this
8222 // throughout the generated ASTs.
8223 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8224 assert(OtherRef && "Reference to parameter cannot fail!");
8225 // Cast to rvalue.
8226 OtherRef = CastForMoving(*this, OtherRef);
8227
8228 // Construct the "this" pointer. We'll be using this throughout the generated
8229 // ASTs.
8230 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8231 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008232
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008233 // Assign base classes.
8234 bool Invalid = false;
8235 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8236 E = ClassDecl->bases_end(); Base != E; ++Base) {
8237 // Form the assignment:
8238 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8239 QualType BaseType = Base->getType().getUnqualifiedType();
8240 if (!BaseType->isRecordType()) {
8241 Invalid = true;
8242 continue;
8243 }
8244
8245 CXXCastPath BasePath;
8246 BasePath.push_back(Base);
8247
8248 // Construct the "from" expression, which is an implicit cast to the
8249 // appropriately-qualified base type.
8250 Expr *From = OtherRef;
8251 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008252 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008253
8254 // Dereference "this".
8255 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8256
8257 // Implicitly cast "this" to the appropriately-qualified base type.
8258 To = ImpCastExprToType(To.take(),
8259 Context.getCVRQualifiedType(BaseType,
8260 MoveAssignOperator->getTypeQualifiers()),
8261 CK_UncheckedDerivedToBase,
8262 VK_LValue, &BasePath);
8263
8264 // Build the move.
8265 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8266 To.get(), From,
8267 /*CopyingBaseSubobject=*/true,
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 move.
8277 Statements.push_back(Move.takeAs<Expr>());
8278 }
8279
8280 // \brief Reference to the __builtin_memcpy function.
8281 Expr *BuiltinMemCpyRef = 0;
8282 // \brief Reference to the __builtin_objc_memmove_collectable function.
8283 Expr *CollectableMemCpyRef = 0;
8284
8285 // Assign non-static members.
8286 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8287 FieldEnd = ClassDecl->field_end();
8288 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008289 if (Field->isUnnamedBitfield())
8290 continue;
8291
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008292 // Check for members of reference type; we can't move those.
8293 if (Field->getType()->isReferenceType()) {
8294 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8295 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8296 Diag(Field->getLocation(), diag::note_declared_at);
8297 Diag(CurrentLocation, diag::note_member_synthesized_at)
8298 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8299 Invalid = true;
8300 continue;
8301 }
8302
8303 // Check for members of const-qualified, non-class type.
8304 QualType BaseType = Context.getBaseElementType(Field->getType());
8305 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8306 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8307 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8308 Diag(Field->getLocation(), diag::note_declared_at);
8309 Diag(CurrentLocation, diag::note_member_synthesized_at)
8310 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8311 Invalid = true;
8312 continue;
8313 }
8314
8315 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008316 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8317 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008318
8319 QualType FieldType = Field->getType().getNonReferenceType();
8320 if (FieldType->isIncompleteArrayType()) {
8321 assert(ClassDecl->hasFlexibleArrayMember() &&
8322 "Incomplete array type is not valid");
8323 continue;
8324 }
8325
8326 // Build references to the field in the object we're copying from and to.
8327 CXXScopeSpec SS; // Intentionally empty
8328 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8329 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008330 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008331 MemberLookup.resolveKind();
8332 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8333 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008334 SS, SourceLocation(), 0,
8335 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008336 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8337 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008338 SS, SourceLocation(), 0,
8339 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008340 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8341 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8342
8343 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8344 "Member reference with rvalue base must be rvalue except for reference "
8345 "members, which aren't allowed for move assignment.");
8346
8347 // If the field should be copied with __builtin_memcpy rather than via
8348 // explicit assignments, do so. This optimization only applies for arrays
8349 // of scalars and arrays of class type with trivial move-assignment
8350 // operators.
8351 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8352 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8353 // Compute the size of the memory buffer to be copied.
8354 QualType SizeType = Context.getSizeType();
8355 llvm::APInt Size(Context.getTypeSize(SizeType),
8356 Context.getTypeSizeInChars(BaseType).getQuantity());
8357 for (const ConstantArrayType *Array
8358 = Context.getAsConstantArrayType(FieldType);
8359 Array;
8360 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8361 llvm::APInt ArraySize
8362 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8363 Size *= ArraySize;
8364 }
8365
Douglas Gregor45d3d712011-09-01 02:09:07 +00008366 // Take the address of the field references for "from" and "to". We
8367 // directly construct UnaryOperators here because semantic analysis
8368 // does not permit us to take the address of an xvalue.
8369 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8370 Context.getPointerType(From.get()->getType()),
8371 VK_RValue, OK_Ordinary, Loc);
8372 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8373 Context.getPointerType(To.get()->getType()),
8374 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008375
8376 bool NeedsCollectableMemCpy =
8377 (BaseType->isRecordType() &&
8378 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8379
8380 if (NeedsCollectableMemCpy) {
8381 if (!CollectableMemCpyRef) {
8382 // Create a reference to the __builtin_objc_memmove_collectable function.
8383 LookupResult R(*this,
8384 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8385 Loc, LookupOrdinaryName);
8386 LookupName(R, TUScope, true);
8387
8388 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8389 if (!CollectableMemCpy) {
8390 // Something went horribly wrong earlier, and we will have
8391 // complained about it.
8392 Invalid = true;
8393 continue;
8394 }
8395
8396 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8397 CollectableMemCpy->getType(),
8398 VK_LValue, Loc, 0).take();
8399 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8400 }
8401 }
8402 // Create a reference to the __builtin_memcpy builtin function.
8403 else if (!BuiltinMemCpyRef) {
8404 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8405 LookupOrdinaryName);
8406 LookupName(R, TUScope, true);
8407
8408 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8409 if (!BuiltinMemCpy) {
8410 // Something went horribly wrong earlier, and we will have complained
8411 // about it.
8412 Invalid = true;
8413 continue;
8414 }
8415
8416 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8417 BuiltinMemCpy->getType(),
8418 VK_LValue, Loc, 0).take();
8419 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8420 }
8421
8422 ASTOwningVector<Expr*> CallArgs(*this);
8423 CallArgs.push_back(To.takeAs<Expr>());
8424 CallArgs.push_back(From.takeAs<Expr>());
8425 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8426 ExprResult Call = ExprError();
8427 if (NeedsCollectableMemCpy)
8428 Call = ActOnCallExpr(/*Scope=*/0,
8429 CollectableMemCpyRef,
8430 Loc, move_arg(CallArgs),
8431 Loc);
8432 else
8433 Call = ActOnCallExpr(/*Scope=*/0,
8434 BuiltinMemCpyRef,
8435 Loc, move_arg(CallArgs),
8436 Loc);
8437
8438 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8439 Statements.push_back(Call.takeAs<Expr>());
8440 continue;
8441 }
8442
8443 // Build the move of this field.
8444 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8445 To.get(), From.get(),
8446 /*CopyingBaseSubobject=*/false,
8447 /*Copying=*/false);
8448 if (Move.isInvalid()) {
8449 Diag(CurrentLocation, diag::note_member_synthesized_at)
8450 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8451 MoveAssignOperator->setInvalidDecl();
8452 return;
8453 }
8454
8455 // Success! Record the copy.
8456 Statements.push_back(Move.takeAs<Stmt>());
8457 }
8458
8459 if (!Invalid) {
8460 // Add a "return *this;"
8461 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8462
8463 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8464 if (Return.isInvalid())
8465 Invalid = true;
8466 else {
8467 Statements.push_back(Return.takeAs<Stmt>());
8468
8469 if (Trap.hasErrorOccurred()) {
8470 Diag(CurrentLocation, diag::note_member_synthesized_at)
8471 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8472 Invalid = true;
8473 }
8474 }
8475 }
8476
8477 if (Invalid) {
8478 MoveAssignOperator->setInvalidDecl();
8479 return;
8480 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008481
8482 StmtResult Body;
8483 {
8484 CompoundScopeRAII CompoundScope(*this);
8485 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8486 /*isStmtExpr=*/false);
8487 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8488 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008489 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8490
8491 if (ASTMutationListener *L = getASTMutationListener()) {
8492 L->CompletedImplicitDefinition(MoveAssignOperator);
8493 }
8494}
8495
Richard Smithb9d0b762012-07-27 04:22:15 +00008496/// Determine whether an implicit copy constructor for ClassDecl has a const
8497/// argument.
8498/// FIXME: It ought to be possible to store this on the record.
8499static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008500 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00008501 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008502
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008503 // C++ [class.copy]p5:
8504 // The implicitly-declared copy constructor for a class X will
8505 // have the form
8506 //
8507 // X::X(const X&)
8508 //
8509 // if
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008510 // -- each direct or virtual base class B of X has a copy
8511 // constructor whose first parameter is of type const B& or
8512 // const volatile B&, and
8513 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8514 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008515 Base != BaseEnd; ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008516 // Virtual bases are handled below.
8517 if (Base->isVirtual())
8518 continue;
Richard Smithb9d0b762012-07-27 04:22:15 +00008519
Douglas Gregor22584312010-07-02 23:41:54 +00008520 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008521 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008522 // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8523 // ambiguous, we should still produce a constructor with a const-qualified
8524 // parameter.
8525 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8526 return false;
Douglas Gregor598a8542010-07-01 18:27:03 +00008527 }
8528
8529 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8530 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008531 Base != BaseEnd; ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008532 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008533 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008534 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8535 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008536 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008537
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008538 // -- for all the nonstatic data members of X that are of a
8539 // class type M (or array thereof), each such class type
8540 // has a copy constructor whose first parameter is of type
8541 // const M& or const volatile M&.
8542 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8543 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008544 Field != FieldEnd; ++Field) {
8545 QualType FieldType = S.Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008546 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smithb9d0b762012-07-27 04:22:15 +00008547 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8548 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008549 }
8550 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008551
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008552 // Otherwise, the implicitly declared copy constructor will have
8553 // the form
8554 //
8555 // X::X(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00008556
8557 return true;
8558}
8559
8560Sema::ImplicitExceptionSpecification
8561Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8562 CXXRecordDecl *ClassDecl = MD->getParent();
8563
8564 ImplicitExceptionSpecification ExceptSpec(*this);
8565 if (ClassDecl->isInvalidDecl())
8566 return ExceptSpec;
8567
8568 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8569 assert(T->getNumArgs() >= 1 && "not a copy ctor");
8570 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8571
Douglas Gregor0d405db2010-07-01 20:59:04 +00008572 // C++ [except.spec]p14:
8573 // An implicitly declared special member function (Clause 12) shall have an
8574 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00008575 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8576 BaseEnd = ClassDecl->bases_end();
8577 Base != BaseEnd;
8578 ++Base) {
8579 // Virtual bases are handled below.
8580 if (Base->isVirtual())
8581 continue;
8582
Douglas Gregor22584312010-07-02 23:41:54 +00008583 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008584 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008585 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008586 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008587 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008588 }
8589 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8590 BaseEnd = ClassDecl->vbases_end();
8591 Base != BaseEnd;
8592 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008593 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008594 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008595 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008596 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008597 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008598 }
8599 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8600 FieldEnd = ClassDecl->field_end();
8601 Field != FieldEnd;
8602 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008603 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008604 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8605 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008606 LookupCopyingConstructor(FieldClassDecl,
8607 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00008608 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008609 }
8610 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008611
Richard Smithb9d0b762012-07-27 04:22:15 +00008612 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00008613}
8614
8615CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8616 CXXRecordDecl *ClassDecl) {
8617 // C++ [class.copy]p4:
8618 // If the class definition does not explicitly declare a copy
8619 // constructor, one is declared implicitly.
8620
Sean Hunt49634cf2011-05-13 06:10:58 +00008621 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8622 QualType ArgType = ClassType;
Richard Smithb9d0b762012-07-27 04:22:15 +00008623 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
Sean Hunt49634cf2011-05-13 06:10:58 +00008624 if (Const)
8625 ArgType = ArgType.withConst();
8626 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00008627
Richard Smith7756afa2012-06-10 05:43:50 +00008628 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8629 CXXCopyConstructor,
8630 Const);
8631
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008632 DeclarationName Name
8633 = Context.DeclarationNames.getCXXConstructorName(
8634 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008635 SourceLocation ClassLoc = ClassDecl->getLocation();
8636 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008637
8638 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008639 // member of its class.
8640 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008641 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008642 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008643 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008644 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008645 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008646 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008647
Richard Smithb9d0b762012-07-27 04:22:15 +00008648 // Build an exception specification pointing back at this member.
8649 FunctionProtoType::ExtProtoInfo EPI;
8650 EPI.ExceptionSpecType = EST_Unevaluated;
8651 EPI.ExceptionSpecDecl = CopyConstructor;
8652 CopyConstructor->setType(
8653 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8654
Douglas Gregor22584312010-07-02 23:41:54 +00008655 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008656 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8657
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008658 // Add the parameter to the constructor.
8659 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008660 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008661 /*IdentifierInfo=*/0,
8662 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008663 SC_None,
8664 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008665 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008666
Douglas Gregor23c94db2010-07-02 17:43:08 +00008667 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008668 PushOnScopeChains(CopyConstructor, S, false);
8669 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008670
Nico Weberafcc96a2012-01-23 03:19:29 +00008671 // C++11 [class.copy]p8:
8672 // ... If the class definition does not explicitly declare a copy
8673 // constructor, there is no user-declared move constructor, and there is no
8674 // user-declared move assignment operator, a copy constructor is implicitly
8675 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008676 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008677 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008678
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008679 return CopyConstructor;
8680}
8681
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008682void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008683 CXXConstructorDecl *CopyConstructor) {
8684 assert((CopyConstructor->isDefaulted() &&
8685 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008686 !CopyConstructor->doesThisDeclarationHaveABody() &&
8687 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008688 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008689
Anders Carlsson63010a72010-04-23 16:24:12 +00008690 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008691 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008692
Douglas Gregor39957dc2010-05-01 15:04:51 +00008693 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008694 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008695
Sean Huntcbb67482011-01-08 20:30:50 +00008696 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008697 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008698 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008699 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008700 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008701 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008702 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008703 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8704 CopyConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008705 MultiStmtArg(*this, 0, 0),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008706 /*isStmtExpr=*/false)
8707 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008708 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008709 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008710
8711 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008712 if (ASTMutationListener *L = getASTMutationListener()) {
8713 L->CompletedImplicitDefinition(CopyConstructor);
8714 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008715}
8716
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008717Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008718Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8719 CXXRecordDecl *ClassDecl = MD->getParent();
8720
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008721 // C++ [except.spec]p14:
8722 // An implicitly declared special member function (Clause 12) shall have an
8723 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008724 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008725 if (ClassDecl->isInvalidDecl())
8726 return ExceptSpec;
8727
8728 // Direct base-class constructors.
8729 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8730 BEnd = ClassDecl->bases_end();
8731 B != BEnd; ++B) {
8732 if (B->isVirtual()) // Handled below.
8733 continue;
8734
8735 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8736 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008737 CXXConstructorDecl *Constructor =
8738 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008739 // If this is a deleted function, add it anyway. This might be conformant
8740 // with the standard. This might not. I'm not sure. It might not matter.
8741 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008742 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008743 }
8744 }
8745
8746 // Virtual base-class constructors.
8747 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8748 BEnd = ClassDecl->vbases_end();
8749 B != BEnd; ++B) {
8750 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8751 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008752 CXXConstructorDecl *Constructor =
8753 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008754 // If this is a deleted function, add it anyway. This might be conformant
8755 // with the standard. This might not. I'm not sure. It might not matter.
8756 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008757 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008758 }
8759 }
8760
8761 // Field constructors.
8762 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8763 FEnd = ClassDecl->field_end();
8764 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008765 QualType FieldType = Context.getBaseElementType(F->getType());
8766 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8767 CXXConstructorDecl *Constructor =
8768 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008769 // If this is a deleted function, add it anyway. This might be conformant
8770 // with the standard. This might not. I'm not sure. It might not matter.
8771 // In particular, the problem is that this function never gets called. It
8772 // might just be ill-formed because this function attempts to refer to
8773 // a deleted function here.
8774 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008775 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008776 }
8777 }
8778
8779 return ExceptSpec;
8780}
8781
8782CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8783 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008784 // C++11 [class.copy]p9:
8785 // If the definition of a class X does not explicitly declare a move
8786 // constructor, one will be implicitly declared as defaulted if and only if:
8787 //
8788 // - [first 4 bullets]
8789 assert(ClassDecl->needsImplicitMoveConstructor());
8790
8791 // [Checked after we build the declaration]
8792 // - the move assignment operator would not be implicitly defined as
8793 // deleted,
8794
8795 // [DR1402]:
8796 // - each of X's non-static data members and direct or virtual base classes
8797 // has a type that either has a move constructor or is trivially copyable.
8798 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8799 ClassDecl->setFailedImplicitMoveConstructor();
8800 return 0;
8801 }
8802
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008803 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8804 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008805
Richard Smith7756afa2012-06-10 05:43:50 +00008806 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8807 CXXMoveConstructor,
8808 false);
8809
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008810 DeclarationName Name
8811 = Context.DeclarationNames.getCXXConstructorName(
8812 Context.getCanonicalType(ClassType));
8813 SourceLocation ClassLoc = ClassDecl->getLocation();
8814 DeclarationNameInfo NameInfo(Name, ClassLoc);
8815
8816 // C++0x [class.copy]p11:
8817 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008818 // member of its class.
8819 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008820 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008821 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008822 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008823 MoveConstructor->setAccess(AS_public);
8824 MoveConstructor->setDefaulted();
8825 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008826
Richard Smithb9d0b762012-07-27 04:22:15 +00008827 // Build an exception specification pointing back at this member.
8828 FunctionProtoType::ExtProtoInfo EPI;
8829 EPI.ExceptionSpecType = EST_Unevaluated;
8830 EPI.ExceptionSpecDecl = MoveConstructor;
8831 MoveConstructor->setType(
8832 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8833
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008834 // Add the parameter to the constructor.
8835 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8836 ClassLoc, ClassLoc,
8837 /*IdentifierInfo=*/0,
8838 ArgType, /*TInfo=*/0,
8839 SC_None,
8840 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008841 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008842
8843 // C++0x [class.copy]p9:
8844 // If the definition of a class X does not explicitly declare a move
8845 // constructor, one will be implicitly declared as defaulted if and only if:
8846 // [...]
8847 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008848 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008849 // Cache this result so that we don't try to generate this over and over
8850 // on every lookup, leaking memory and wasting time.
8851 ClassDecl->setFailedImplicitMoveConstructor();
8852 return 0;
8853 }
8854
8855 // Note that we have declared this constructor.
8856 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8857
8858 if (Scope *S = getScopeForContext(ClassDecl))
8859 PushOnScopeChains(MoveConstructor, S, false);
8860 ClassDecl->addDecl(MoveConstructor);
8861
8862 return MoveConstructor;
8863}
8864
8865void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8866 CXXConstructorDecl *MoveConstructor) {
8867 assert((MoveConstructor->isDefaulted() &&
8868 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008869 !MoveConstructor->doesThisDeclarationHaveABody() &&
8870 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008871 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8872
8873 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8874 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8875
8876 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8877 DiagnosticErrorTrap Trap(Diags);
8878
8879 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8880 Trap.hasErrorOccurred()) {
8881 Diag(CurrentLocation, diag::note_member_synthesized_at)
8882 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8883 MoveConstructor->setInvalidDecl();
8884 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008885 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008886 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8887 MoveConstructor->getLocation(),
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008888 MultiStmtArg(*this, 0, 0),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008889 /*isStmtExpr=*/false)
8890 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008891 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008892 }
8893
8894 MoveConstructor->setUsed();
8895
8896 if (ASTMutationListener *L = getASTMutationListener()) {
8897 L->CompletedImplicitDefinition(MoveConstructor);
8898 }
8899}
8900
Douglas Gregore4e68d42012-02-15 19:33:52 +00008901bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8902 return FD->isDeleted() &&
8903 (FD->isDefaulted() || FD->isImplicit()) &&
8904 isa<CXXMethodDecl>(FD);
8905}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008906
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008907/// \brief Mark the call operator of the given lambda closure type as "used".
8908static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8909 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008910 = cast<CXXMethodDecl>(
8911 *Lambda->lookup(
8912 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008913 CallOperator->setReferenced();
8914 CallOperator->setUsed();
8915}
8916
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008917void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8918 SourceLocation CurrentLocation,
8919 CXXConversionDecl *Conv)
8920{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008921 CXXRecordDecl *Lambda = Conv->getParent();
8922
8923 // Make sure that the lambda call operator is marked used.
8924 markLambdaCallOperatorUsed(*this, Lambda);
8925
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008926 Conv->setUsed();
8927
8928 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8929 DiagnosticErrorTrap Trap(Diags);
8930
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008931 // Return the address of the __invoke function.
8932 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8933 CXXMethodDecl *Invoke
8934 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8935 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8936 VK_LValue, Conv->getLocation()).take();
8937 assert(FunctionRef && "Can't refer to __invoke function?");
8938 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8939 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8940 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008941 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008942
8943 // Fill in the __invoke function with a dummy implementation. IR generation
8944 // will fill in the actual details.
8945 Invoke->setUsed();
8946 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008947 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008948
8949 if (ASTMutationListener *L = getASTMutationListener()) {
8950 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008951 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008952 }
8953}
8954
8955void Sema::DefineImplicitLambdaToBlockPointerConversion(
8956 SourceLocation CurrentLocation,
8957 CXXConversionDecl *Conv)
8958{
8959 Conv->setUsed();
8960
8961 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8962 DiagnosticErrorTrap Trap(Diags);
8963
Douglas Gregorac1303e2012-02-22 05:02:47 +00008964 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008965 Expr *This = ActOnCXXThis(CurrentLocation).take();
8966 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008967
Eli Friedman23f02672012-03-01 04:01:32 +00008968 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8969 Conv->getLocation(),
8970 Conv, DerefThis);
8971
8972 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8973 // behavior. Note that only the general conversion function does this
8974 // (since it's unusable otherwise); in the case where we inline the
8975 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008976 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008977 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8978 CK_CopyAndAutoreleaseBlockObject,
8979 BuildBlock.get(), 0, VK_RValue);
8980
8981 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008982 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008983 Conv->setInvalidDecl();
8984 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008985 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008986
Douglas Gregorac1303e2012-02-22 05:02:47 +00008987 // Create the return statement that returns the block from the conversion
8988 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008989 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008990 if (Return.isInvalid()) {
8991 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8992 Conv->setInvalidDecl();
8993 return;
8994 }
8995
8996 // Set the body of the conversion function.
8997 Stmt *ReturnS = Return.take();
8998 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8999 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009000 Conv->getLocation()));
9001
Douglas Gregorac1303e2012-02-22 05:02:47 +00009002 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009003 if (ASTMutationListener *L = getASTMutationListener()) {
9004 L->CompletedImplicitDefinition(Conv);
9005 }
9006}
9007
Douglas Gregorf52757d2012-03-10 06:53:13 +00009008/// \brief Determine whether the given list arguments contains exactly one
9009/// "real" (non-default) argument.
9010static bool hasOneRealArgument(MultiExprArg Args) {
9011 switch (Args.size()) {
9012 case 0:
9013 return false;
9014
9015 default:
9016 if (!Args.get()[1]->isDefaultArgument())
9017 return false;
9018
9019 // fall through
9020 case 1:
9021 return !Args.get()[0]->isDefaultArgument();
9022 }
9023
9024 return false;
9025}
9026
John McCall60d7b3a2010-08-24 06:29:42 +00009027ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009028Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009029 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009030 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009031 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009032 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009033 unsigned ConstructKind,
9034 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009035 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009036
Douglas Gregor2f599792010-04-02 18:24:57 +00009037 // C++0x [class.copy]p34:
9038 // When certain criteria are met, an implementation is allowed to
9039 // omit the copy/move construction of a class object, even if the
9040 // copy/move constructor and/or destructor for the object have
9041 // side effects. [...]
9042 // - when a temporary class object that has not been bound to a
9043 // reference (12.2) would be copied/moved to a class object
9044 // with the same cv-unqualified type, the copy/move operation
9045 // can be omitted by constructing the temporary object
9046 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009047 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009048 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009049 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009050 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009051 }
Mike Stump1eb44332009-09-09 15:08:12 +00009052
9053 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009054 Elidable, move(ExprArgs), HadMultipleCandidates,
9055 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009056}
9057
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009058/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9059/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009060ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009061Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9062 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009063 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009064 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009065 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009066 unsigned ConstructKind,
9067 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009068 unsigned NumExprs = ExprArgs.size();
9069 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009070
Eli Friedman5f2987c2012-02-02 03:46:19 +00009071 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009072 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009073 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009074 HadMultipleCandidates, /*FIXME*/false,
9075 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009076 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9077 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009078}
9079
Mike Stump1eb44332009-09-09 15:08:12 +00009080bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009081 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009082 MultiExprArg Exprs,
9083 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009084 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009085 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009086 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009087 move(Exprs), HadMultipleCandidates, false,
9088 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009089 if (TempResult.isInvalid())
9090 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009091
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009092 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009093 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009094 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009095 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009096 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009097
Anders Carlssonfe2de492009-08-25 05:18:00 +00009098 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009099}
9100
John McCall68c6c9a2010-02-02 09:10:11 +00009101void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009102 if (VD->isInvalidDecl()) return;
9103
John McCall68c6c9a2010-02-02 09:10:11 +00009104 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009105 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009106 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009107 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009108
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009109 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009110 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009111 CheckDestructorAccess(VD->getLocation(), Destructor,
9112 PDiag(diag::err_access_dtor_var)
9113 << VD->getDeclName()
9114 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009115 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009116
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009117 if (!VD->hasGlobalStorage()) return;
9118
9119 // Emit warning for non-trivial dtor in global scope (a real global,
9120 // class-static, function-static).
9121 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9122
9123 // TODO: this should be re-enabled for static locals by !CXAAtExit
9124 if (!VD->isStaticLocal())
9125 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009126}
9127
Douglas Gregor39da0b82009-09-09 23:08:42 +00009128/// \brief Given a constructor and the set of arguments provided for the
9129/// constructor, convert the arguments and add any required default arguments
9130/// to form a proper call to this constructor.
9131///
9132/// \returns true if an error occurred, false otherwise.
9133bool
9134Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9135 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009136 SourceLocation Loc,
Douglas Gregored878af2012-02-24 23:56:31 +00009137 ASTOwningVector<Expr*> &ConvertedArgs,
9138 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009139 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9140 unsigned NumArgs = ArgsPtr.size();
9141 Expr **Args = (Expr **)ArgsPtr.get();
9142
9143 const FunctionProtoType *Proto
9144 = Constructor->getType()->getAs<FunctionProtoType>();
9145 assert(Proto && "Constructor without a prototype?");
9146 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009147
9148 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009149 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009150 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009151 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009152 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009153
9154 VariadicCallType CallType =
9155 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009156 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009157 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9158 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009159 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009160 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009161
9162 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9163
Richard Smith831421f2012-06-25 20:30:08 +00009164 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9165 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009166
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009167 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009168}
9169
Anders Carlsson20d45d22009-12-12 00:32:00 +00009170static inline bool
9171CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9172 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009173 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009174 if (isa<NamespaceDecl>(DC)) {
9175 return SemaRef.Diag(FnDecl->getLocation(),
9176 diag::err_operator_new_delete_declared_in_namespace)
9177 << FnDecl->getDeclName();
9178 }
9179
9180 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009181 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009182 return SemaRef.Diag(FnDecl->getLocation(),
9183 diag::err_operator_new_delete_declared_static)
9184 << FnDecl->getDeclName();
9185 }
9186
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009187 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009188}
9189
Anders Carlsson156c78e2009-12-13 17:53:43 +00009190static inline bool
9191CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9192 CanQualType ExpectedResultType,
9193 CanQualType ExpectedFirstParamType,
9194 unsigned DependentParamTypeDiag,
9195 unsigned InvalidParamTypeDiag) {
9196 QualType ResultType =
9197 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9198
9199 // Check that the result type is not dependent.
9200 if (ResultType->isDependentType())
9201 return SemaRef.Diag(FnDecl->getLocation(),
9202 diag::err_operator_new_delete_dependent_result_type)
9203 << FnDecl->getDeclName() << ExpectedResultType;
9204
9205 // Check that the result type is what we expect.
9206 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9207 return SemaRef.Diag(FnDecl->getLocation(),
9208 diag::err_operator_new_delete_invalid_result_type)
9209 << FnDecl->getDeclName() << ExpectedResultType;
9210
9211 // A function template must have at least 2 parameters.
9212 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9213 return SemaRef.Diag(FnDecl->getLocation(),
9214 diag::err_operator_new_delete_template_too_few_parameters)
9215 << FnDecl->getDeclName();
9216
9217 // The function decl must have at least 1 parameter.
9218 if (FnDecl->getNumParams() == 0)
9219 return SemaRef.Diag(FnDecl->getLocation(),
9220 diag::err_operator_new_delete_too_few_parameters)
9221 << FnDecl->getDeclName();
9222
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009223 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009224 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9225 if (FirstParamType->isDependentType())
9226 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9227 << FnDecl->getDeclName() << ExpectedFirstParamType;
9228
9229 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009230 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009231 ExpectedFirstParamType)
9232 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9233 << FnDecl->getDeclName() << ExpectedFirstParamType;
9234
9235 return false;
9236}
9237
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009238static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009239CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009240 // C++ [basic.stc.dynamic.allocation]p1:
9241 // A program is ill-formed if an allocation function is declared in a
9242 // namespace scope other than global scope or declared static in global
9243 // scope.
9244 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9245 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009246
9247 CanQualType SizeTy =
9248 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9249
9250 // C++ [basic.stc.dynamic.allocation]p1:
9251 // The return type shall be void*. The first parameter shall have type
9252 // std::size_t.
9253 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9254 SizeTy,
9255 diag::err_operator_new_dependent_param_type,
9256 diag::err_operator_new_param_type))
9257 return true;
9258
9259 // C++ [basic.stc.dynamic.allocation]p1:
9260 // The first parameter shall not have an associated default argument.
9261 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009262 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009263 diag::err_operator_new_default_arg)
9264 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9265
9266 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009267}
9268
9269static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009270CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9271 // C++ [basic.stc.dynamic.deallocation]p1:
9272 // A program is ill-formed if deallocation functions are declared in a
9273 // namespace scope other than global scope or declared static in global
9274 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009275 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9276 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009277
9278 // C++ [basic.stc.dynamic.deallocation]p2:
9279 // Each deallocation function shall return void and its first parameter
9280 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009281 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9282 SemaRef.Context.VoidPtrTy,
9283 diag::err_operator_delete_dependent_param_type,
9284 diag::err_operator_delete_param_type))
9285 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009286
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009287 return false;
9288}
9289
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009290/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9291/// of this overloaded operator is well-formed. If so, returns false;
9292/// otherwise, emits appropriate diagnostics and returns true.
9293bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009294 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009295 "Expected an overloaded operator declaration");
9296
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009297 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9298
Mike Stump1eb44332009-09-09 15:08:12 +00009299 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009300 // The allocation and deallocation functions, operator new,
9301 // operator new[], operator delete and operator delete[], are
9302 // described completely in 3.7.3. The attributes and restrictions
9303 // found in the rest of this subclause do not apply to them unless
9304 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009305 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009306 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009307
Anders Carlssona3ccda52009-12-12 00:26:23 +00009308 if (Op == OO_New || Op == OO_Array_New)
9309 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009310
9311 // C++ [over.oper]p6:
9312 // An operator function shall either be a non-static member
9313 // function or be a non-member function and have at least one
9314 // parameter whose type is a class, a reference to a class, an
9315 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009316 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9317 if (MethodDecl->isStatic())
9318 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009319 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009320 } else {
9321 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009322 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9323 ParamEnd = FnDecl->param_end();
9324 Param != ParamEnd; ++Param) {
9325 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009326 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9327 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009328 ClassOrEnumParam = true;
9329 break;
9330 }
9331 }
9332
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009333 if (!ClassOrEnumParam)
9334 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009335 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009336 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009337 }
9338
9339 // C++ [over.oper]p8:
9340 // An operator function cannot have default arguments (8.3.6),
9341 // except where explicitly stated below.
9342 //
Mike Stump1eb44332009-09-09 15:08:12 +00009343 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009344 // (C++ [over.call]p1).
9345 if (Op != OO_Call) {
9346 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9347 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009348 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009349 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009350 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009351 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009352 }
9353 }
9354
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009355 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9356 { false, false, false }
9357#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9358 , { Unary, Binary, MemberOnly }
9359#include "clang/Basic/OperatorKinds.def"
9360 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009361
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009362 bool CanBeUnaryOperator = OperatorUses[Op][0];
9363 bool CanBeBinaryOperator = OperatorUses[Op][1];
9364 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009365
9366 // C++ [over.oper]p8:
9367 // [...] Operator functions cannot have more or fewer parameters
9368 // than the number required for the corresponding operator, as
9369 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009370 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009371 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009372 if (Op != OO_Call &&
9373 ((NumParams == 1 && !CanBeUnaryOperator) ||
9374 (NumParams == 2 && !CanBeBinaryOperator) ||
9375 (NumParams < 1) || (NumParams > 2))) {
9376 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009377 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009378 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009379 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009380 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009381 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009382 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009383 assert(CanBeBinaryOperator &&
9384 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009385 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009386 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009387
Chris Lattner416e46f2008-11-21 07:57:12 +00009388 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009389 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009390 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009391
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009392 // Overloaded operators other than operator() cannot be variadic.
9393 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009394 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009395 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009396 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009397 }
9398
9399 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009400 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9401 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009402 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009403 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009404 }
9405
9406 // C++ [over.inc]p1:
9407 // The user-defined function called operator++ implements the
9408 // prefix and postfix ++ operator. If this function is a member
9409 // function with no parameters, or a non-member function with one
9410 // parameter of class or enumeration type, it defines the prefix
9411 // increment operator ++ for objects of that type. If the function
9412 // is a member function with one parameter (which shall be of type
9413 // int) or a non-member function with two parameters (the second
9414 // of which shall be of type int), it defines the postfix
9415 // increment operator ++ for objects of that type.
9416 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9417 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9418 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009419 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009420 ParamIsInt = BT->getKind() == BuiltinType::Int;
9421
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009422 if (!ParamIsInt)
9423 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009424 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009425 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009426 }
9427
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009428 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009429}
Chris Lattner5a003a42008-12-17 07:09:26 +00009430
Sean Hunta6c058d2010-01-13 09:01:02 +00009431/// CheckLiteralOperatorDeclaration - Check whether the declaration
9432/// of this literal operator function is well-formed. If so, returns
9433/// false; otherwise, emits appropriate diagnostics and returns true.
9434bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009435 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009436 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9437 << FnDecl->getDeclName();
9438 return true;
9439 }
9440
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009441 if (FnDecl->isExternC()) {
9442 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9443 return true;
9444 }
9445
Sean Hunta6c058d2010-01-13 09:01:02 +00009446 bool Valid = false;
9447
Richard Smith36f5cfe2012-03-09 08:00:36 +00009448 // This might be the definition of a literal operator template.
9449 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9450 // This might be a specialization of a literal operator template.
9451 if (!TpDecl)
9452 TpDecl = FnDecl->getPrimaryTemplate();
9453
Sean Hunt216c2782010-04-07 23:11:06 +00009454 // template <char...> type operator "" name() is the only valid template
9455 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009456 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009457 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009458 // Must have only one template parameter
9459 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9460 if (Params->size() == 1) {
9461 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009462 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009463
Sean Hunt216c2782010-04-07 23:11:06 +00009464 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009465 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9466 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9467 Valid = true;
9468 }
9469 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009470 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009471 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009472 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9473
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009474 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009475
Sean Hunt30019c02010-04-07 22:57:35 +00009476 // unsigned long long int, long double, and any character type are allowed
9477 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009478 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9479 Context.hasSameType(T, Context.LongDoubleTy) ||
9480 Context.hasSameType(T, Context.CharTy) ||
9481 Context.hasSameType(T, Context.WCharTy) ||
9482 Context.hasSameType(T, Context.Char16Ty) ||
9483 Context.hasSameType(T, Context.Char32Ty)) {
9484 if (++Param == FnDecl->param_end())
9485 Valid = true;
9486 goto FinishedParams;
9487 }
9488
Sean Hunt30019c02010-04-07 22:57:35 +00009489 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009490 const PointerType *PT = T->getAs<PointerType>();
9491 if (!PT)
9492 goto FinishedParams;
9493 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009494 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009495 goto FinishedParams;
9496 T = T.getUnqualifiedType();
9497
9498 // Move on to the second parameter;
9499 ++Param;
9500
9501 // If there is no second parameter, the first must be a const char *
9502 if (Param == FnDecl->param_end()) {
9503 if (Context.hasSameType(T, Context.CharTy))
9504 Valid = true;
9505 goto FinishedParams;
9506 }
9507
9508 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9509 // are allowed as the first parameter to a two-parameter function
9510 if (!(Context.hasSameType(T, Context.CharTy) ||
9511 Context.hasSameType(T, Context.WCharTy) ||
9512 Context.hasSameType(T, Context.Char16Ty) ||
9513 Context.hasSameType(T, Context.Char32Ty)))
9514 goto FinishedParams;
9515
9516 // The second and final parameter must be an std::size_t
9517 T = (*Param)->getType().getUnqualifiedType();
9518 if (Context.hasSameType(T, Context.getSizeType()) &&
9519 ++Param == FnDecl->param_end())
9520 Valid = true;
9521 }
9522
9523 // FIXME: This diagnostic is absolutely terrible.
9524FinishedParams:
9525 if (!Valid) {
9526 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9527 << FnDecl->getDeclName();
9528 return true;
9529 }
9530
Richard Smitha9e88b22012-03-09 08:16:22 +00009531 // A parameter-declaration-clause containing a default argument is not
9532 // equivalent to any of the permitted forms.
9533 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9534 ParamEnd = FnDecl->param_end();
9535 Param != ParamEnd; ++Param) {
9536 if ((*Param)->hasDefaultArg()) {
9537 Diag((*Param)->getDefaultArgRange().getBegin(),
9538 diag::err_literal_operator_default_argument)
9539 << (*Param)->getDefaultArgRange();
9540 break;
9541 }
9542 }
9543
Richard Smith2fb4ae32012-03-08 02:39:21 +00009544 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009545 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9546 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009547 // C++11 [usrlit.suffix]p1:
9548 // Literal suffix identifiers that do not start with an underscore
9549 // are reserved for future standardization.
9550 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009551 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009552
Sean Hunta6c058d2010-01-13 09:01:02 +00009553 return false;
9554}
9555
Douglas Gregor074149e2009-01-05 19:45:36 +00009556/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9557/// linkage specification, including the language and (if present)
9558/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9559/// the location of the language string literal, which is provided
9560/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9561/// the '{' brace. Otherwise, this linkage specification does not
9562/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009563Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9564 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009565 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009566 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009567 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009568 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009569 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009570 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009571 Language = LinkageSpecDecl::lang_cxx;
9572 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009573 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009574 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009575 }
Mike Stump1eb44332009-09-09 15:08:12 +00009576
Chris Lattnercc98eac2008-12-17 07:13:27 +00009577 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009578
Douglas Gregor074149e2009-01-05 19:45:36 +00009579 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009580 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009581 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009582 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009583 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009584}
9585
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009586/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009587/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9588/// valid, it's the position of the closing '}' brace in a linkage
9589/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009590Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009591 Decl *LinkageSpec,
9592 SourceLocation RBraceLoc) {
9593 if (LinkageSpec) {
9594 if (RBraceLoc.isValid()) {
9595 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9596 LSDecl->setRBraceLoc(RBraceLoc);
9597 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009598 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009599 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009600 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009601}
9602
Douglas Gregord308e622009-05-18 20:51:54 +00009603/// \brief Perform semantic analysis for the variable declaration that
9604/// occurs within a C++ catch clause, returning the newly-created
9605/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009606VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009607 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009608 SourceLocation StartLoc,
9609 SourceLocation Loc,
9610 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009611 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009612 QualType ExDeclType = TInfo->getType();
9613
Sebastian Redl4b07b292008-12-22 19:15:10 +00009614 // Arrays and functions decay.
9615 if (ExDeclType->isArrayType())
9616 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9617 else if (ExDeclType->isFunctionType())
9618 ExDeclType = Context.getPointerType(ExDeclType);
9619
9620 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9621 // The exception-declaration shall not denote a pointer or reference to an
9622 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009623 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009624 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009625 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009626 Invalid = true;
9627 }
Douglas Gregord308e622009-05-18 20:51:54 +00009628
Sebastian Redl4b07b292008-12-22 19:15:10 +00009629 QualType BaseType = ExDeclType;
9630 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009631 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009632 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009633 BaseType = Ptr->getPointeeType();
9634 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009635 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009636 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009637 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009638 BaseType = Ref->getPointeeType();
9639 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009640 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009641 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009642 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009643 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009644 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009645
Mike Stump1eb44332009-09-09 15:08:12 +00009646 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009647 RequireNonAbstractType(Loc, ExDeclType,
9648 diag::err_abstract_type_in_decl,
9649 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009650 Invalid = true;
9651
John McCall5a180392010-07-24 00:37:23 +00009652 // Only the non-fragile NeXT runtime currently supports C++ catches
9653 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009654 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009655 QualType T = ExDeclType;
9656 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9657 T = RT->getPointeeType();
9658
9659 if (T->isObjCObjectType()) {
9660 Diag(Loc, diag::err_objc_object_catch);
9661 Invalid = true;
9662 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +00009663 // FIXME: should this be a test for macosx-fragile specifically?
9664 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009665 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009666 }
9667 }
9668
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009669 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9670 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009671 ExDecl->setExceptionVariable(true);
9672
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009673 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009674 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009675 Invalid = true;
9676
Douglas Gregorc41b8782011-07-06 18:14:43 +00009677 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009678 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009679 // C++ [except.handle]p16:
9680 // The object declared in an exception-declaration or, if the
9681 // exception-declaration does not specify a name, a temporary (12.2) is
9682 // copy-initialized (8.5) from the exception object. [...]
9683 // The object is destroyed when the handler exits, after the destruction
9684 // of any automatic objects initialized within the handler.
9685 //
9686 // We just pretend to initialize the object with itself, then make sure
9687 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009688 QualType initType = ExDeclType;
9689
9690 InitializedEntity entity =
9691 InitializedEntity::InitializeVariable(ExDecl);
9692 InitializationKind initKind =
9693 InitializationKind::CreateCopy(Loc, SourceLocation());
9694
9695 Expr *opaqueValue =
9696 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9697 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9698 ExprResult result = sequence.Perform(*this, entity, initKind,
9699 MultiExprArg(&opaqueValue, 1));
9700 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009701 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009702 else {
9703 // If the constructor used was non-trivial, set this as the
9704 // "initializer".
9705 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9706 if (!construct->getConstructor()->isTrivial()) {
9707 Expr *init = MaybeCreateExprWithCleanups(construct);
9708 ExDecl->setInit(init);
9709 }
9710
9711 // And make sure it's destructable.
9712 FinalizeVarWithDestructor(ExDecl, recordType);
9713 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009714 }
9715 }
9716
Douglas Gregord308e622009-05-18 20:51:54 +00009717 if (Invalid)
9718 ExDecl->setInvalidDecl();
9719
9720 return ExDecl;
9721}
9722
9723/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9724/// handler.
John McCalld226f652010-08-21 09:40:31 +00009725Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009726 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009727 bool Invalid = D.isInvalidType();
9728
9729 // Check for unexpanded parameter packs.
9730 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9731 UPPC_ExceptionType)) {
9732 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9733 D.getIdentifierLoc());
9734 Invalid = true;
9735 }
9736
Sebastian Redl4b07b292008-12-22 19:15:10 +00009737 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009738 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009739 LookupOrdinaryName,
9740 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009741 // The scope should be freshly made just for us. There is just no way
9742 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009743 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009744 if (PrevDecl->isTemplateParameter()) {
9745 // Maybe we will complain about the shadowed template parameter.
9746 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009747 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009748 }
9749 }
9750
Chris Lattnereaaebc72009-04-25 08:06:05 +00009751 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009752 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9753 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009754 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009755 }
9756
Douglas Gregor83cb9422010-09-09 17:09:21 +00009757 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009758 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009759 D.getIdentifierLoc(),
9760 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009761 if (Invalid)
9762 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009763
Sebastian Redl4b07b292008-12-22 19:15:10 +00009764 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009765 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009766 PushOnScopeChains(ExDecl, S);
9767 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009768 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009769
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009770 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009771 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009772}
Anders Carlssonfb311762009-03-14 00:25:26 +00009773
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009774Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009775 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +00009776 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009777 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +00009778 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +00009779
Richard Smithe3f470a2012-07-11 22:37:56 +00009780 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9781 return 0;
9782
9783 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9784 AssertMessage, RParenLoc, false);
9785}
9786
9787Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9788 Expr *AssertExpr,
9789 StringLiteral *AssertMessage,
9790 SourceLocation RParenLoc,
9791 bool Failed) {
9792 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9793 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +00009794 // In a static_assert-declaration, the constant-expression shall be a
9795 // constant expression that can be contextually converted to bool.
9796 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9797 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009798 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +00009799
Richard Smithdaaefc52011-12-14 23:32:26 +00009800 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +00009801 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009802 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +00009803 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009804 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +00009805
Richard Smithe3f470a2012-07-11 22:37:56 +00009806 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +00009807 llvm::SmallString<256> MsgBuffer;
9808 llvm::raw_svector_ostream Msg(MsgBuffer);
9809 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009810 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009811 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +00009812 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +00009813 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009814 }
Mike Stump1eb44332009-09-09 15:08:12 +00009815
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009816 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +00009817 AssertExpr, AssertMessage, RParenLoc,
9818 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +00009819
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009820 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009821 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009822}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009823
Douglas Gregor1d869352010-04-07 16:53:43 +00009824/// \brief Perform semantic analysis of the given friend type declaration.
9825///
9826/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009827FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9828 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009829 TypeSourceInfo *TSInfo) {
9830 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9831
9832 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009833 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009834
Richard Smith6b130222011-10-18 21:39:00 +00009835 // C++03 [class.friend]p2:
9836 // An elaborated-type-specifier shall be used in a friend declaration
9837 // for a class.*
9838 //
9839 // * The class-key of the elaborated-type-specifier is required.
9840 if (!ActiveTemplateInstantiations.empty()) {
9841 // Do not complain about the form of friend template types during
9842 // template instantiation; we will already have complained when the
9843 // template was declared.
9844 } else if (!T->isElaboratedTypeSpecifier()) {
9845 // If we evaluated the type to a record type, suggest putting
9846 // a tag in front.
9847 if (const RecordType *RT = T->getAs<RecordType>()) {
9848 RecordDecl *RD = RT->getDecl();
9849
9850 std::string InsertionText = std::string(" ") + RD->getKindName();
9851
9852 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009853 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009854 diag::warn_cxx98_compat_unelaborated_friend_type :
9855 diag::ext_unelaborated_friend_type)
9856 << (unsigned) RD->getTagKind()
9857 << T
9858 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9859 InsertionText);
9860 } else {
9861 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009862 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009863 diag::warn_cxx98_compat_nonclass_type_friend :
9864 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009865 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009866 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009867 }
Richard Smith6b130222011-10-18 21:39:00 +00009868 } else if (T->getAs<EnumType>()) {
9869 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009870 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009871 diag::warn_cxx98_compat_enum_friend :
9872 diag::ext_enum_friend)
9873 << T
9874 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009875 }
9876
Douglas Gregor06245bf2010-04-07 17:57:12 +00009877 // C++0x [class.friend]p3:
9878 // If the type specifier in a friend declaration designates a (possibly
9879 // cv-qualified) class type, that class is declared as a friend; otherwise,
9880 // the friend declaration is ignored.
9881
9882 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9883 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009884
Abramo Bagnara0216df82011-10-29 20:52:52 +00009885 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009886}
9887
John McCall9a34edb2010-10-19 01:40:49 +00009888/// Handle a friend tag declaration where the scope specifier was
9889/// templated.
9890Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9891 unsigned TagSpec, SourceLocation TagLoc,
9892 CXXScopeSpec &SS,
9893 IdentifierInfo *Name, SourceLocation NameLoc,
9894 AttributeList *Attr,
9895 MultiTemplateParamsArg TempParamLists) {
9896 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9897
9898 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009899 bool Invalid = false;
9900
9901 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009902 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00009903 TempParamLists.get(),
9904 TempParamLists.size(),
9905 /*friend*/ true,
9906 isExplicitSpecialization,
9907 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009908 if (TemplateParams->size() > 0) {
9909 // This is a declaration of a class template.
9910 if (Invalid)
9911 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009912
Eric Christopher4110e132011-07-21 05:34:24 +00009913 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9914 SS, Name, NameLoc, Attr,
9915 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009916 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009917 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009918 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009919 } else {
9920 // The "template<>" header is extraneous.
9921 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9922 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9923 isExplicitSpecialization = true;
9924 }
9925 }
9926
9927 if (Invalid) return 0;
9928
John McCall9a34edb2010-10-19 01:40:49 +00009929 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009930 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00009931 if (TempParamLists.get()[I]->size()) {
9932 isAllExplicitSpecializations = false;
9933 break;
9934 }
9935 }
9936
9937 // FIXME: don't ignore attributes.
9938
9939 // If it's explicit specializations all the way down, just forget
9940 // about the template header and build an appropriate non-templated
9941 // friend. TODO: for source fidelity, remember the headers.
9942 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009943 if (SS.isEmpty()) {
9944 bool Owned = false;
9945 bool IsDependent = false;
9946 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9947 Attr, AS_public,
9948 /*ModulePrivateLoc=*/SourceLocation(),
9949 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009950 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009951 /*ScopedEnumUsesClassTag=*/false,
9952 /*UnderlyingType=*/TypeResult());
9953 }
9954
Douglas Gregor2494dd02011-03-01 01:34:45 +00009955 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009956 ElaboratedTypeKeyword Keyword
9957 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009958 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009959 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009960 if (T.isNull())
9961 return 0;
9962
9963 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9964 if (isa<DependentNameType>(T)) {
9965 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009966 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009967 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009968 TL.setNameLoc(NameLoc);
9969 } else {
9970 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009971 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009972 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009973 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9974 }
9975
9976 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9977 TSI, FriendLoc);
9978 Friend->setAccess(AS_public);
9979 CurContext->addDecl(Friend);
9980 return Friend;
9981 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009982
9983 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9984
9985
John McCall9a34edb2010-10-19 01:40:49 +00009986
9987 // Handle the case of a templated-scope friend class. e.g.
9988 // template <class T> class A<T>::B;
9989 // FIXME: we don't support these right now.
9990 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9991 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9992 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9993 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009994 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009995 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009996 TL.setNameLoc(NameLoc);
9997
9998 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9999 TSI, FriendLoc);
10000 Friend->setAccess(AS_public);
10001 Friend->setUnsupportedFriend(true);
10002 CurContext->addDecl(Friend);
10003 return Friend;
10004}
10005
10006
John McCalldd4a3b02009-09-16 22:47:08 +000010007/// Handle a friend type declaration. This works in tandem with
10008/// ActOnTag.
10009///
10010/// Notes on friend class templates:
10011///
10012/// We generally treat friend class declarations as if they were
10013/// declaring a class. So, for example, the elaborated type specifier
10014/// in a friend declaration is required to obey the restrictions of a
10015/// class-head (i.e. no typedefs in the scope chain), template
10016/// parameters are required to match up with simple template-ids, &c.
10017/// However, unlike when declaring a template specialization, it's
10018/// okay to refer to a template specialization without an empty
10019/// template parameter declaration, e.g.
10020/// friend class A<T>::B<unsigned>;
10021/// We permit this as a special case; if there are any template
10022/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010023/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010024Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010025 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010026 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010027
10028 assert(DS.isFriendSpecified());
10029 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10030
John McCalldd4a3b02009-09-16 22:47:08 +000010031 // Try to convert the decl specifier to a type. This works for
10032 // friend templates because ActOnTag never produces a ClassTemplateDecl
10033 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010034 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010035 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10036 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010037 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010038 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010039
Douglas Gregor6ccab972010-12-16 01:14:37 +000010040 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10041 return 0;
10042
John McCalldd4a3b02009-09-16 22:47:08 +000010043 // This is definitely an error in C++98. It's probably meant to
10044 // be forbidden in C++0x, too, but the specification is just
10045 // poorly written.
10046 //
10047 // The problem is with declarations like the following:
10048 // template <T> friend A<T>::foo;
10049 // where deciding whether a class C is a friend or not now hinges
10050 // on whether there exists an instantiation of A that causes
10051 // 'foo' to equal C. There are restrictions on class-heads
10052 // (which we declare (by fiat) elaborated friend declarations to
10053 // be) that makes this tractable.
10054 //
10055 // FIXME: handle "template <> friend class A<T>;", which
10056 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010057 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010058 Diag(Loc, diag::err_tagless_friend_type_template)
10059 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010060 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010061 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010062
John McCall02cace72009-08-28 07:59:38 +000010063 // C++98 [class.friend]p1: A friend of a class is a function
10064 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010065 // This is fixed in DR77, which just barely didn't make the C++03
10066 // deadline. It's also a very silly restriction that seriously
10067 // affects inner classes and which nobody else seems to implement;
10068 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010069 //
10070 // But note that we could warn about it: it's always useless to
10071 // friend one of your own members (it's not, however, worthless to
10072 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010073
John McCalldd4a3b02009-09-16 22:47:08 +000010074 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010075 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010076 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010077 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010078 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010079 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010080 DS.getFriendSpecLoc());
10081 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010082 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010083
10084 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010085 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010086
John McCalldd4a3b02009-09-16 22:47:08 +000010087 D->setAccess(AS_public);
10088 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010089
John McCalld226f652010-08-21 09:40:31 +000010090 return D;
John McCall02cace72009-08-28 07:59:38 +000010091}
10092
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010093Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010094 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010095 const DeclSpec &DS = D.getDeclSpec();
10096
10097 assert(DS.isFriendSpecified());
10098 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10099
10100 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010101 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010102
10103 // C++ [class.friend]p1
10104 // A friend of a class is a function or class....
10105 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010106 // It *doesn't* see through dependent types, which is correct
10107 // according to [temp.arg.type]p3:
10108 // If a declaration acquires a function type through a
10109 // type dependent on a template-parameter and this causes
10110 // a declaration that does not use the syntactic form of a
10111 // function declarator to have a function type, the program
10112 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010113 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010114 Diag(Loc, diag::err_unexpected_friend);
10115
10116 // It might be worthwhile to try to recover by creating an
10117 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010118 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010119 }
10120
10121 // C++ [namespace.memdef]p3
10122 // - If a friend declaration in a non-local class first declares a
10123 // class or function, the friend class or function is a member
10124 // of the innermost enclosing namespace.
10125 // - The name of the friend is not found by simple name lookup
10126 // until a matching declaration is provided in that namespace
10127 // scope (either before or after the class declaration granting
10128 // friendship).
10129 // - If a friend function is called, its name may be found by the
10130 // name lookup that considers functions from namespaces and
10131 // classes associated with the types of the function arguments.
10132 // - When looking for a prior declaration of a class or a function
10133 // declared as a friend, scopes outside the innermost enclosing
10134 // namespace scope are not considered.
10135
John McCall337ec3d2010-10-12 23:13:28 +000010136 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010137 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10138 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010139 assert(Name);
10140
Douglas Gregor6ccab972010-12-16 01:14:37 +000010141 // Check for unexpanded parameter packs.
10142 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10143 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10144 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10145 return 0;
10146
John McCall67d1a672009-08-06 02:15:43 +000010147 // The context we found the declaration in, or in which we should
10148 // create the declaration.
10149 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010150 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010151 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010152 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010153
John McCall337ec3d2010-10-12 23:13:28 +000010154 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010155
John McCall337ec3d2010-10-12 23:13:28 +000010156 // There are four cases here.
10157 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010158 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010159 // there as appropriate.
10160 // Recover from invalid scope qualifiers as if they just weren't there.
10161 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010162 // C++0x [namespace.memdef]p3:
10163 // If the name in a friend declaration is neither qualified nor
10164 // a template-id and the declaration is a function or an
10165 // elaborated-type-specifier, the lookup to determine whether
10166 // the entity has been previously declared shall not consider
10167 // any scopes outside the innermost enclosing namespace.
10168 // C++0x [class.friend]p11:
10169 // If a friend declaration appears in a local class and the name
10170 // specified is an unqualified name, a prior declaration is
10171 // looked up without considering scopes that are outside the
10172 // innermost enclosing non-class scope. For a friend function
10173 // declaration, if there is no prior declaration, the program is
10174 // ill-formed.
10175 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010176 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010177
John McCall29ae6e52010-10-13 05:45:15 +000010178 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010179 DC = CurContext;
10180 while (true) {
10181 // Skip class contexts. If someone can cite chapter and verse
10182 // for this behavior, that would be nice --- it's what GCC and
10183 // EDG do, and it seems like a reasonable intent, but the spec
10184 // really only says that checks for unqualified existing
10185 // declarations should stop at the nearest enclosing namespace,
10186 // not that they should only consider the nearest enclosing
10187 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010188 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010189 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010190
John McCall68263142009-11-18 22:49:29 +000010191 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010192
10193 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010194 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010195 break;
John McCall29ae6e52010-10-13 05:45:15 +000010196
John McCall8a407372010-10-14 22:22:28 +000010197 if (isTemplateId) {
10198 if (isa<TranslationUnitDecl>(DC)) break;
10199 } else {
10200 if (DC->isFileContext()) break;
10201 }
John McCall67d1a672009-08-06 02:15:43 +000010202 DC = DC->getParent();
10203 }
10204
10205 // C++ [class.friend]p1: A friend of a class is a function or
10206 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010207 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010208 // Most C++ 98 compilers do seem to give an error here, so
10209 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010210 if (!Previous.empty() && DC->Equals(CurContext))
10211 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010212 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010213 diag::warn_cxx98_compat_friend_is_member :
10214 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010215
John McCall380aaa42010-10-13 06:22:15 +000010216 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010217
Douglas Gregor883af832011-10-10 01:11:59 +000010218 // C++ [class.friend]p6:
10219 // A function can be defined in a friend declaration of a class if and
10220 // only if the class is a non-local class (9.8), the function name is
10221 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010222 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010223 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10224 }
10225
John McCall337ec3d2010-10-12 23:13:28 +000010226 // - There's a non-dependent scope specifier, in which case we
10227 // compute it and do a previous lookup there for a function
10228 // or function template.
10229 } else if (!SS.getScopeRep()->isDependent()) {
10230 DC = computeDeclContext(SS);
10231 if (!DC) return 0;
10232
10233 if (RequireCompleteDeclContext(SS, DC)) return 0;
10234
10235 LookupQualifiedName(Previous, DC);
10236
10237 // Ignore things found implicitly in the wrong scope.
10238 // TODO: better diagnostics for this case. Suggesting the right
10239 // qualified scope would be nice...
10240 LookupResult::Filter F = Previous.makeFilter();
10241 while (F.hasNext()) {
10242 NamedDecl *D = F.next();
10243 if (!DC->InEnclosingNamespaceSetOf(
10244 D->getDeclContext()->getRedeclContext()))
10245 F.erase();
10246 }
10247 F.done();
10248
10249 if (Previous.empty()) {
10250 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010251 Diag(Loc, diag::err_qualified_friend_not_found)
10252 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010253 return 0;
10254 }
10255
10256 // C++ [class.friend]p1: A friend of a class is a function or
10257 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010258 if (DC->Equals(CurContext))
10259 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010260 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010261 diag::warn_cxx98_compat_friend_is_member :
10262 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010263
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010264 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010265 // C++ [class.friend]p6:
10266 // A function can be defined in a friend declaration of a class if and
10267 // only if the class is a non-local class (9.8), the function name is
10268 // unqualified, and the function has namespace scope.
10269 SemaDiagnosticBuilder DB
10270 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10271
10272 DB << SS.getScopeRep();
10273 if (DC->isFileContext())
10274 DB << FixItHint::CreateRemoval(SS.getRange());
10275 SS.clear();
10276 }
John McCall337ec3d2010-10-12 23:13:28 +000010277
10278 // - There's a scope specifier that does not match any template
10279 // parameter lists, in which case we use some arbitrary context,
10280 // create a method or method template, and wait for instantiation.
10281 // - There's a scope specifier that does match some template
10282 // parameter lists, which we don't handle right now.
10283 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010284 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010285 // C++ [class.friend]p6:
10286 // A function can be defined in a friend declaration of a class if and
10287 // only if the class is a non-local class (9.8), the function name is
10288 // unqualified, and the function has namespace scope.
10289 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10290 << SS.getScopeRep();
10291 }
10292
John McCall337ec3d2010-10-12 23:13:28 +000010293 DC = CurContext;
10294 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010295 }
Douglas Gregor883af832011-10-10 01:11:59 +000010296
John McCall29ae6e52010-10-13 05:45:15 +000010297 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010298 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010299 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10300 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10301 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010302 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010303 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10304 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010305 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010306 }
John McCall67d1a672009-08-06 02:15:43 +000010307 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010308
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010309 // FIXME: This is an egregious hack to cope with cases where the scope stack
10310 // does not contain the declaration context, i.e., in an out-of-line
10311 // definition of a class.
10312 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10313 if (!DCScope) {
10314 FakeDCScope.setEntity(DC);
10315 DCScope = &FakeDCScope;
10316 }
10317
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010318 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010319 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10320 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010321 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010322
Douglas Gregor182ddf02009-09-28 00:08:27 +000010323 assert(ND->getDeclContext() == DC);
10324 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010325
John McCallab88d972009-08-31 22:39:49 +000010326 // Add the function declaration to the appropriate lookup tables,
10327 // adjusting the redeclarations list as necessary. We don't
10328 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010329 //
John McCallab88d972009-08-31 22:39:49 +000010330 // Also update the scope-based lookup if the target context's
10331 // lookup context is in lexical scope.
10332 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010333 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010334 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010335 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010336 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010337 }
John McCall02cace72009-08-28 07:59:38 +000010338
10339 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010340 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010341 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010342 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010343 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010344
John McCall1f2e1a92012-08-10 03:15:35 +000010345 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010346 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010347 } else {
10348 if (DC->isRecord()) CheckFriendAccess(ND);
10349
John McCall6102ca12010-10-16 06:59:13 +000010350 FunctionDecl *FD;
10351 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10352 FD = FTD->getTemplatedDecl();
10353 else
10354 FD = cast<FunctionDecl>(ND);
10355
10356 // Mark templated-scope function declarations as unsupported.
10357 if (FD->getNumTemplateParameterLists())
10358 FrD->setUnsupportedFriend(true);
10359 }
John McCall337ec3d2010-10-12 23:13:28 +000010360
John McCalld226f652010-08-21 09:40:31 +000010361 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010362}
10363
John McCalld226f652010-08-21 09:40:31 +000010364void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10365 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010366
Sebastian Redl50de12f2009-03-24 22:27:57 +000010367 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10368 if (!Fn) {
10369 Diag(DelLoc, diag::err_deleted_non_function);
10370 return;
10371 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010372 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010373 // Don't consider the implicit declaration we generate for explicit
10374 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010375 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10376 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010377 Diag(DelLoc, diag::err_deleted_decl_not_first);
10378 Diag(Prev->getLocation(), diag::note_previous_declaration);
10379 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010380 // If the declaration wasn't the first, we delete the function anyway for
10381 // recovery.
10382 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010383 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010384
10385 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10386 if (!MD)
10387 return;
10388
10389 // A deleted special member function is trivial if the corresponding
10390 // implicitly-declared function would have been.
10391 switch (getSpecialMember(MD)) {
10392 case CXXInvalid:
10393 break;
10394 case CXXDefaultConstructor:
10395 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10396 break;
10397 case CXXCopyConstructor:
10398 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10399 break;
10400 case CXXMoveConstructor:
10401 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10402 break;
10403 case CXXCopyAssignment:
10404 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10405 break;
10406 case CXXMoveAssignment:
10407 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10408 break;
10409 case CXXDestructor:
10410 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10411 break;
10412 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010413}
Sebastian Redl13e88542009-04-27 21:33:24 +000010414
Sean Hunte4246a62011-05-12 06:15:49 +000010415void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10416 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10417
10418 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010419 if (MD->getParent()->isDependentType()) {
10420 MD->setDefaulted();
10421 MD->setExplicitlyDefaulted();
10422 return;
10423 }
10424
Sean Hunte4246a62011-05-12 06:15:49 +000010425 CXXSpecialMember Member = getSpecialMember(MD);
10426 if (Member == CXXInvalid) {
10427 Diag(DefaultLoc, diag::err_default_special_members);
10428 return;
10429 }
10430
10431 MD->setDefaulted();
10432 MD->setExplicitlyDefaulted();
10433
Sean Huntcd10dec2011-05-23 23:14:04 +000010434 // If this definition appears within the record, do the checking when
10435 // the record is complete.
10436 const FunctionDecl *Primary = MD;
10437 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10438 // Find the uninstantiated declaration that actually had the '= default'
10439 // on it.
10440 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10441
10442 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010443 return;
10444
Richard Smithb9d0b762012-07-27 04:22:15 +000010445 CheckExplicitlyDefaultedSpecialMember(MD);
10446
Sean Hunte4246a62011-05-12 06:15:49 +000010447 switch (Member) {
10448 case CXXDefaultConstructor: {
10449 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010450 if (!CD->isInvalidDecl())
10451 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10452 break;
10453 }
10454
10455 case CXXCopyConstructor: {
10456 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010457 if (!CD->isInvalidDecl())
10458 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010459 break;
10460 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010461
Sean Hunt2b188082011-05-14 05:23:28 +000010462 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010463 if (!MD->isInvalidDecl())
10464 DefineImplicitCopyAssignment(DefaultLoc, MD);
10465 break;
10466 }
10467
Sean Huntcb45a0f2011-05-12 22:46:25 +000010468 case CXXDestructor: {
10469 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010470 if (!DD->isInvalidDecl())
10471 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010472 break;
10473 }
10474
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010475 case CXXMoveConstructor: {
10476 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010477 if (!CD->isInvalidDecl())
10478 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010479 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010480 }
Sean Hunt82713172011-05-25 23:16:36 +000010481
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010482 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010483 if (!MD->isInvalidDecl())
10484 DefineImplicitMoveAssignment(DefaultLoc, MD);
10485 break;
10486 }
10487
10488 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010489 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010490 }
10491 } else {
10492 Diag(DefaultLoc, diag::err_default_special_members);
10493 }
10494}
10495
Sebastian Redl13e88542009-04-27 21:33:24 +000010496static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010497 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010498 Stmt *SubStmt = *CI;
10499 if (!SubStmt)
10500 continue;
10501 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010502 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010503 diag::err_return_in_constructor_handler);
10504 if (!isa<Expr>(SubStmt))
10505 SearchForReturnInStmt(Self, SubStmt);
10506 }
10507}
10508
10509void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10510 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10511 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10512 SearchForReturnInStmt(*this, Handler);
10513 }
10514}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010515
Mike Stump1eb44332009-09-09 15:08:12 +000010516bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010517 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010518 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10519 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010520
Chandler Carruth73857792010-02-15 11:53:20 +000010521 if (Context.hasSameType(NewTy, OldTy) ||
10522 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010523 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010524
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010525 // Check if the return types are covariant
10526 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010527
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010528 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010529 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10530 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010531 NewClassTy = NewPT->getPointeeType();
10532 OldClassTy = OldPT->getPointeeType();
10533 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010534 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10535 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10536 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10537 NewClassTy = NewRT->getPointeeType();
10538 OldClassTy = OldRT->getPointeeType();
10539 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010540 }
10541 }
Mike Stump1eb44332009-09-09 15:08:12 +000010542
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010543 // The return types aren't either both pointers or references to a class type.
10544 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010545 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010546 diag::err_different_return_type_for_overriding_virtual_function)
10547 << New->getDeclName() << NewTy << OldTy;
10548 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010549
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010550 return true;
10551 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010552
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010553 // C++ [class.virtual]p6:
10554 // If the return type of D::f differs from the return type of B::f, the
10555 // class type in the return type of D::f shall be complete at the point of
10556 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010557 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10558 if (!RT->isBeingDefined() &&
10559 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010560 diag::err_covariant_return_incomplete,
10561 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010562 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010563 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010564
Douglas Gregora4923eb2009-11-16 21:35:15 +000010565 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010566 // Check if the new class derives from the old class.
10567 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10568 Diag(New->getLocation(),
10569 diag::err_covariant_return_not_derived)
10570 << New->getDeclName() << NewTy << OldTy;
10571 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10572 return true;
10573 }
Mike Stump1eb44332009-09-09 15:08:12 +000010574
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010575 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010576 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010577 diag::err_covariant_return_inaccessible_base,
10578 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10579 // FIXME: Should this point to the return type?
10580 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010581 // FIXME: this note won't trigger for delayed access control
10582 // diagnostics, and it's impossible to get an undelayed error
10583 // here from access control during the original parse because
10584 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010585 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10586 return true;
10587 }
10588 }
Mike Stump1eb44332009-09-09 15:08:12 +000010589
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010590 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010591 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010592 Diag(New->getLocation(),
10593 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010594 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010595 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10596 return true;
10597 };
Mike Stump1eb44332009-09-09 15:08:12 +000010598
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010599
10600 // The new class type must have the same or less qualifiers as the old type.
10601 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10602 Diag(New->getLocation(),
10603 diag::err_covariant_return_type_class_type_more_qualified)
10604 << New->getDeclName() << NewTy << OldTy;
10605 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10606 return true;
10607 };
Mike Stump1eb44332009-09-09 15:08:12 +000010608
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010609 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010610}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010611
Douglas Gregor4ba31362009-12-01 17:24:26 +000010612/// \brief Mark the given method pure.
10613///
10614/// \param Method the method to be marked pure.
10615///
10616/// \param InitRange the source range that covers the "0" initializer.
10617bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010618 SourceLocation EndLoc = InitRange.getEnd();
10619 if (EndLoc.isValid())
10620 Method->setRangeEnd(EndLoc);
10621
Douglas Gregor4ba31362009-12-01 17:24:26 +000010622 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10623 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010624 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010625 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010626
10627 if (!Method->isInvalidDecl())
10628 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10629 << Method->getDeclName() << InitRange;
10630 return true;
10631}
10632
Douglas Gregor552e2992012-02-21 02:22:07 +000010633/// \brief Determine whether the given declaration is a static data member.
10634static bool isStaticDataMember(Decl *D) {
10635 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10636 if (!Var)
10637 return false;
10638
10639 return Var->isStaticDataMember();
10640}
John McCall731ad842009-12-19 09:28:58 +000010641/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10642/// an initializer for the out-of-line declaration 'Dcl'. The scope
10643/// is a fresh scope pushed for just this purpose.
10644///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010645/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10646/// static data member of class X, names should be looked up in the scope of
10647/// class X.
John McCalld226f652010-08-21 09:40:31 +000010648void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010649 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010650 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010651
John McCall731ad842009-12-19 09:28:58 +000010652 // We should only get called for declarations with scope specifiers, like:
10653 // int foo::bar;
10654 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010655 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010656
10657 // If we are parsing the initializer for a static data member, push a
10658 // new expression evaluation context that is associated with this static
10659 // data member.
10660 if (isStaticDataMember(D))
10661 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010662}
10663
10664/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010665/// initializer for the out-of-line declaration 'D'.
10666void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010667 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010668 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010669
Douglas Gregor552e2992012-02-21 02:22:07 +000010670 if (isStaticDataMember(D))
10671 PopExpressionEvaluationContext();
10672
John McCall731ad842009-12-19 09:28:58 +000010673 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010674 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010675}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010676
10677/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10678/// C++ if/switch/while/for statement.
10679/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010680DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010681 // C++ 6.4p2:
10682 // The declarator shall not specify a function or an array.
10683 // The type-specifier-seq shall not contain typedef and shall not declare a
10684 // new class or enumeration.
10685 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10686 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010687
10688 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010689 if (!Dcl)
10690 return true;
10691
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010692 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10693 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010694 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010695 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010696 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010697
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010698 return Dcl;
10699}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010700
Douglas Gregordfe65432011-07-28 19:11:31 +000010701void Sema::LoadExternalVTableUses() {
10702 if (!ExternalSource)
10703 return;
10704
10705 SmallVector<ExternalVTableUse, 4> VTables;
10706 ExternalSource->ReadUsedVTables(VTables);
10707 SmallVector<VTableUse, 4> NewUses;
10708 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10709 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10710 = VTablesUsed.find(VTables[I].Record);
10711 // Even if a definition wasn't required before, it may be required now.
10712 if (Pos != VTablesUsed.end()) {
10713 if (!Pos->second && VTables[I].DefinitionRequired)
10714 Pos->second = true;
10715 continue;
10716 }
10717
10718 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10719 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10720 }
10721
10722 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10723}
10724
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010725void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10726 bool DefinitionRequired) {
10727 // Ignore any vtable uses in unevaluated operands or for classes that do
10728 // not have a vtable.
10729 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10730 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010731 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010732 return;
10733
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010734 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010735 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010736 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10737 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10738 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10739 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010740 // If we already had an entry, check to see if we are promoting this vtable
10741 // to required a definition. If so, we need to reappend to the VTableUses
10742 // list, since we may have already processed the first entry.
10743 if (DefinitionRequired && !Pos.first->second) {
10744 Pos.first->second = true;
10745 } else {
10746 // Otherwise, we can early exit.
10747 return;
10748 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010749 }
10750
10751 // Local classes need to have their virtual members marked
10752 // immediately. For all other classes, we mark their virtual members
10753 // at the end of the translation unit.
10754 if (Class->isLocalClass())
10755 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010756 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010757 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010758}
10759
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010760bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010761 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010762 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010763 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010764
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010765 // Note: The VTableUses vector could grow as a result of marking
10766 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000010767 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010768 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010769 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010770 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010771 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010772 if (!Class)
10773 continue;
10774
10775 SourceLocation Loc = VTableUses[I].second;
10776
Richard Smithb9d0b762012-07-27 04:22:15 +000010777 bool DefineVTable = true;
10778
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010779 // If this class has a key function, but that key function is
10780 // defined in another translation unit, we don't need to emit the
10781 // vtable even though we're using it.
10782 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010783 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010784 switch (KeyFunction->getTemplateSpecializationKind()) {
10785 case TSK_Undeclared:
10786 case TSK_ExplicitSpecialization:
10787 case TSK_ExplicitInstantiationDeclaration:
10788 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000010789 DefineVTable = false;
10790 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010791
10792 case TSK_ExplicitInstantiationDefinition:
10793 case TSK_ImplicitInstantiation:
10794 // We will be instantiating the key function.
10795 break;
10796 }
10797 } else if (!KeyFunction) {
10798 // If we have a class with no key function that is the subject
10799 // of an explicit instantiation declaration, suppress the
10800 // vtable; it will live with the explicit instantiation
10801 // definition.
10802 bool IsExplicitInstantiationDeclaration
10803 = Class->getTemplateSpecializationKind()
10804 == TSK_ExplicitInstantiationDeclaration;
10805 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10806 REnd = Class->redecls_end();
10807 R != REnd; ++R) {
10808 TemplateSpecializationKind TSK
10809 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10810 if (TSK == TSK_ExplicitInstantiationDeclaration)
10811 IsExplicitInstantiationDeclaration = true;
10812 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10813 IsExplicitInstantiationDeclaration = false;
10814 break;
10815 }
10816 }
10817
10818 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000010819 DefineVTable = false;
10820 }
10821
10822 // The exception specifications for all virtual members may be needed even
10823 // if we are not providing an authoritative form of the vtable in this TU.
10824 // We may choose to emit it available_externally anyway.
10825 if (!DefineVTable) {
10826 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10827 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010828 }
10829
10830 // Mark all of the virtual members of this class as referenced, so
10831 // that we can build a vtable. Then, tell the AST consumer that a
10832 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010833 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010834 MarkVirtualMembersReferenced(Loc, Class);
10835 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10836 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10837
10838 // Optionally warn if we're emitting a weak vtable.
10839 if (Class->getLinkage() == ExternalLinkage &&
10840 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010841 const FunctionDecl *KeyFunctionDef = 0;
10842 if (!KeyFunction ||
10843 (KeyFunction->hasBody(KeyFunctionDef) &&
10844 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010845 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10846 TSK_ExplicitInstantiationDefinition
10847 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10848 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010849 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010850 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010851 VTableUses.clear();
10852
Douglas Gregor78844032011-04-22 22:25:37 +000010853 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010854}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010855
Richard Smithb9d0b762012-07-27 04:22:15 +000010856void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10857 const CXXRecordDecl *RD) {
10858 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10859 E = RD->method_end(); I != E; ++I)
10860 if ((*I)->isVirtual() && !(*I)->isPure())
10861 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10862}
10863
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010864void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10865 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000010866 // Mark all functions which will appear in RD's vtable as used.
10867 CXXFinalOverriderMap FinalOverriders;
10868 RD->getFinalOverriders(FinalOverriders);
10869 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10870 E = FinalOverriders.end();
10871 I != E; ++I) {
10872 for (OverridingMethods::const_iterator OI = I->second.begin(),
10873 OE = I->second.end();
10874 OI != OE; ++OI) {
10875 assert(OI->second.size() > 0 && "no final overrider");
10876 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000010877
Richard Smithff817f72012-07-07 06:59:51 +000010878 // C++ [basic.def.odr]p2:
10879 // [...] A virtual member function is used if it is not pure. [...]
10880 if (!Overrider->isPure())
10881 MarkFunctionReferenced(Loc, Overrider);
10882 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010883 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010884
10885 // Only classes that have virtual bases need a VTT.
10886 if (RD->getNumVBases() == 0)
10887 return;
10888
10889 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10890 e = RD->bases_end(); i != e; ++i) {
10891 const CXXRecordDecl *Base =
10892 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010893 if (Base->getNumVBases() == 0)
10894 continue;
10895 MarkVirtualMembersReferenced(Loc, Base);
10896 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010897}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010898
10899/// SetIvarInitializers - This routine builds initialization ASTs for the
10900/// Objective-C implementation whose ivars need be initialized.
10901void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010902 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010903 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010904 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010905 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010906 CollectIvarsToConstructOrDestruct(OID, ivars);
10907 if (ivars.empty())
10908 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010909 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010910 for (unsigned i = 0; i < ivars.size(); i++) {
10911 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010912 if (Field->isInvalidDecl())
10913 continue;
10914
Sean Huntcbb67482011-01-08 20:30:50 +000010915 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010916 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10917 InitializationKind InitKind =
10918 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10919
10920 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010921 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010922 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010923 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010924 // Note, MemberInit could actually come back empty if no initialization
10925 // is required (e.g., because it would call a trivial default constructor)
10926 if (!MemberInit.get() || MemberInit.isInvalid())
10927 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010928
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010929 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010930 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10931 SourceLocation(),
10932 MemberInit.takeAs<Expr>(),
10933 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010934 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010935
10936 // Be sure that the destructor is accessible and is marked as referenced.
10937 if (const RecordType *RecordTy
10938 = Context.getBaseElementType(Field->getType())
10939 ->getAs<RecordType>()) {
10940 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010941 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010942 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010943 CheckDestructorAccess(Field->getLocation(), Destructor,
10944 PDiag(diag::err_access_dtor_ivar)
10945 << Context.getBaseElementType(Field->getType()));
10946 }
10947 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010948 }
10949 ObjCImplementation->setIvarInitializers(Context,
10950 AllToInit.data(), AllToInit.size());
10951 }
10952}
Sean Huntfe57eef2011-05-04 05:57:24 +000010953
Sean Huntebcbe1d2011-05-04 23:29:54 +000010954static
10955void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10956 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10957 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10958 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10959 Sema &S) {
10960 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10961 CE = Current.end();
10962 if (Ctor->isInvalidDecl())
10963 return;
10964
10965 const FunctionDecl *FNTarget = 0;
10966 CXXConstructorDecl *Target;
10967
10968 // We ignore the result here since if we don't have a body, Target will be
10969 // null below.
10970 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10971 Target
10972= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10973
10974 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10975 // Avoid dereferencing a null pointer here.
10976 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10977
10978 if (!Current.insert(Canonical))
10979 return;
10980
10981 // We know that beyond here, we aren't chaining into a cycle.
10982 if (!Target || !Target->isDelegatingConstructor() ||
10983 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10984 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10985 Valid.insert(*CI);
10986 Current.clear();
10987 // We've hit a cycle.
10988 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10989 Current.count(TCanonical)) {
10990 // If we haven't diagnosed this cycle yet, do so now.
10991 if (!Invalid.count(TCanonical)) {
10992 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010993 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010994 << Ctor;
10995
10996 // Don't add a note for a function delegating directo to itself.
10997 if (TCanonical != Canonical)
10998 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10999
11000 CXXConstructorDecl *C = Target;
11001 while (C->getCanonicalDecl() != Canonical) {
11002 (void)C->getTargetConstructor()->hasBody(FNTarget);
11003 assert(FNTarget && "Ctor cycle through bodiless function");
11004
11005 C
11006 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11007 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11008 }
11009 }
11010
11011 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11012 Invalid.insert(*CI);
11013 Current.clear();
11014 } else {
11015 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11016 }
11017}
11018
11019
Sean Huntfe57eef2011-05-04 05:57:24 +000011020void Sema::CheckDelegatingCtorCycles() {
11021 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11022
Sean Huntebcbe1d2011-05-04 23:29:54 +000011023 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11024 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011025
Douglas Gregor0129b562011-07-27 21:57:17 +000011026 for (DelegatingCtorDeclsType::iterator
11027 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011028 E = DelegatingCtorDecls.end();
11029 I != E; ++I) {
11030 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011031 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011032
11033 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11034 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011035}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011036
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011037namespace {
11038 /// \brief AST visitor that finds references to the 'this' expression.
11039 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11040 Sema &S;
11041
11042 public:
11043 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11044
11045 bool VisitCXXThisExpr(CXXThisExpr *E) {
11046 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11047 << E->isImplicit();
11048 return false;
11049 }
11050 };
11051}
11052
11053bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11054 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11055 if (!TSInfo)
11056 return false;
11057
11058 TypeLoc TL = TSInfo->getTypeLoc();
11059 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11060 if (!ProtoTL)
11061 return false;
11062
11063 // C++11 [expr.prim.general]p3:
11064 // [The expression this] shall not appear before the optional
11065 // cv-qualifier-seq and it shall not appear within the declaration of a
11066 // static member function (although its type and value category are defined
11067 // within a static member function as they are within a non-static member
11068 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011069 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011070 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11071 FindCXXThisExpr Finder(*this);
11072
11073 // If the return type came after the cv-qualifier-seq, check it now.
11074 if (Proto->hasTrailingReturn() &&
11075 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11076 return true;
11077
11078 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011079 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11080 return true;
11081
11082 return checkThisInStaticMemberFunctionAttributes(Method);
11083}
11084
11085bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11086 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11087 if (!TSInfo)
11088 return false;
11089
11090 TypeLoc TL = TSInfo->getTypeLoc();
11091 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11092 if (!ProtoTL)
11093 return false;
11094
11095 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11096 FindCXXThisExpr Finder(*this);
11097
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011098 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011099 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011100 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011101 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011102 case EST_DynamicNone:
11103 case EST_MSAny:
11104 case EST_None:
11105 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011106
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011107 case EST_ComputedNoexcept:
11108 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11109 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011110
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011111 case EST_Dynamic:
11112 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011113 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011114 E != EEnd; ++E) {
11115 if (!Finder.TraverseType(*E))
11116 return true;
11117 }
11118 break;
11119 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011120
11121 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011122}
11123
11124bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11125 FindCXXThisExpr Finder(*this);
11126
11127 // Check attributes.
11128 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11129 A != AEnd; ++A) {
11130 // FIXME: This should be emitted by tblgen.
11131 Expr *Arg = 0;
11132 ArrayRef<Expr *> Args;
11133 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11134 Arg = G->getArg();
11135 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11136 Arg = G->getArg();
11137 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11138 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11139 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11140 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11141 else if (ExclusiveLockFunctionAttr *ELF
11142 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11143 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11144 else if (SharedLockFunctionAttr *SLF
11145 = dyn_cast<SharedLockFunctionAttr>(*A))
11146 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11147 else if (ExclusiveTrylockFunctionAttr *ETLF
11148 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11149 Arg = ETLF->getSuccessValue();
11150 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11151 } else if (SharedTrylockFunctionAttr *STLF
11152 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11153 Arg = STLF->getSuccessValue();
11154 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11155 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11156 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11157 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11158 Arg = LR->getArg();
11159 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11160 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11161 else if (ExclusiveLocksRequiredAttr *ELR
11162 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11163 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11164 else if (SharedLocksRequiredAttr *SLR
11165 = dyn_cast<SharedLocksRequiredAttr>(*A))
11166 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11167
11168 if (Arg && !Finder.TraverseStmt(Arg))
11169 return true;
11170
11171 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11172 if (!Finder.TraverseStmt(Args[I]))
11173 return true;
11174 }
11175 }
11176
11177 return false;
11178}
11179
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011180void
11181Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11182 ArrayRef<ParsedType> DynamicExceptions,
11183 ArrayRef<SourceRange> DynamicExceptionRanges,
11184 Expr *NoexceptExpr,
11185 llvm::SmallVectorImpl<QualType> &Exceptions,
11186 FunctionProtoType::ExtProtoInfo &EPI) {
11187 Exceptions.clear();
11188 EPI.ExceptionSpecType = EST;
11189 if (EST == EST_Dynamic) {
11190 Exceptions.reserve(DynamicExceptions.size());
11191 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11192 // FIXME: Preserve type source info.
11193 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11194
11195 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11196 collectUnexpandedParameterPacks(ET, Unexpanded);
11197 if (!Unexpanded.empty()) {
11198 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11199 UPPC_ExceptionType,
11200 Unexpanded);
11201 continue;
11202 }
11203
11204 // Check that the type is valid for an exception spec, and
11205 // drop it if not.
11206 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11207 Exceptions.push_back(ET);
11208 }
11209 EPI.NumExceptions = Exceptions.size();
11210 EPI.Exceptions = Exceptions.data();
11211 return;
11212 }
11213
11214 if (EST == EST_ComputedNoexcept) {
11215 // If an error occurred, there's no expression here.
11216 if (NoexceptExpr) {
11217 assert((NoexceptExpr->isTypeDependent() ||
11218 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11219 Context.BoolTy) &&
11220 "Parser should have made sure that the expression is boolean");
11221 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11222 EPI.ExceptionSpecType = EST_BasicNoexcept;
11223 return;
11224 }
11225
11226 if (!NoexceptExpr->isValueDependent())
11227 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011228 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011229 /*AllowFold*/ false).take();
11230 EPI.NoexceptExpr = NoexceptExpr;
11231 }
11232 return;
11233 }
11234}
11235
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011236/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11237Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11238 // Implicitly declared functions (e.g. copy constructors) are
11239 // __host__ __device__
11240 if (D->isImplicit())
11241 return CFT_HostDevice;
11242
11243 if (D->hasAttr<CUDAGlobalAttr>())
11244 return CFT_Global;
11245
11246 if (D->hasAttr<CUDADeviceAttr>()) {
11247 if (D->hasAttr<CUDAHostAttr>())
11248 return CFT_HostDevice;
11249 else
11250 return CFT_Device;
11251 }
11252
11253 return CFT_Host;
11254}
11255
11256bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11257 CUDAFunctionTarget CalleeTarget) {
11258 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11259 // Callable from the device only."
11260 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11261 return true;
11262
11263 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11264 // Callable from the host only."
11265 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11266 // Callable from the host only."
11267 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11268 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11269 return true;
11270
11271 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11272 return true;
11273
11274 return false;
11275}