blob: f66509d1770c1078d8a0eb076ab67273ce711ee0 [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"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000040#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000041#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000042
43using namespace clang;
44
Chris Lattner8123a952008-04-10 02:22:51 +000045//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
Chris Lattner9e979552008-04-12 23:52:44 +000049namespace {
50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51 /// the default argument of a parameter to determine whether it
52 /// contains any ill-formed subexpressions. For example, this will
53 /// diagnose the use of local variables or parameters within the
54 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000055 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000057 Expr *DefaultArg;
58 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 public:
Mike Stump1eb44332009-09-09 15:08:12 +000061 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000062 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000063
Chris Lattner9e979552008-04-12 23:52:44 +000064 bool VisitExpr(Expr *Node);
65 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000066 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000067 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000068 };
Chris Lattner8123a952008-04-10 02:22:51 +000069
Chris Lattner9e979552008-04-12 23:52:44 +000070 /// VisitExpr - Visit all of the children of this expression.
71 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000073 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000074 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000075 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000076 }
77
Chris Lattner9e979552008-04-12 23:52:44 +000078 /// VisitDeclRefExpr - Visit a reference to a declaration, to
79 /// determine whether this declaration can be used in the default
80 /// argument expression.
81 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000082 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000083 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84 // C++ [dcl.fct.default]p9
85 // Default arguments are evaluated each time the function is
86 // called. The order of evaluation of function arguments is
87 // unspecified. Consequently, parameters of a function shall not
88 // be used in default argument expressions, even if they are not
89 // evaluated. Parameters of a function declared before a default
90 // argument expression are in scope and can hide namespace and
91 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000092 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000093 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000094 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000095 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000096 // C++ [dcl.fct.default]p7
97 // Local variables shall not be used in default argument
98 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000099 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000100 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000102 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104
Douglas Gregor3996f232008-11-04 13:41:56 +0000105 return false;
106 }
Chris Lattner9e979552008-04-12 23:52:44 +0000107
Douglas Gregor796da182008-11-04 14:32:21 +0000108 /// VisitCXXThisExpr - Visit a C++ "this" expression.
109 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110 // C++ [dcl.fct.default]p8:
111 // The keyword this shall not be used in a default argument of a
112 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000113 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000114 diag::err_param_default_argument_references_this)
115 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000116 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000117
118 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119 // C++11 [expr.lambda.prim]p13:
120 // A lambda-expression appearing in a default argument shall not
121 // implicitly or explicitly capture any entity.
122 if (Lambda->capture_begin() == Lambda->capture_end())
123 return false;
124
125 return S->Diag(Lambda->getLocStart(),
126 diag::err_lambda_capture_default_arg);
127 }
Chris Lattner8123a952008-04-10 02:22:51 +0000128}
129
Richard Smithe6975e92012-04-17 00:58:00 +0000130void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000132 // If we have an MSAny spec already, don't bother.
133 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000134 return;
135
136 const FunctionProtoType *Proto
137 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000138 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
139 if (!Proto)
140 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000141
142 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
143
144 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000145 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000146 ClearExceptions();
147 ComputedEST = EST;
148 return;
149 }
150
Richard Smith7a614d82011-06-11 17:19:42 +0000151 // FIXME: If the call to this decl is using any of its default arguments, we
152 // need to search them for potentially-throwing calls.
153
Sean Hunt001cad92011-05-10 00:49:42 +0000154 // If this function has a basic noexcept, it doesn't affect the outcome.
155 if (EST == EST_BasicNoexcept)
156 return;
157
158 // If we have a throw-all spec at this point, ignore the function.
159 if (ComputedEST == EST_None)
160 return;
161
162 // If we're still at noexcept(true) and there's a nothrow() callee,
163 // change to that specification.
164 if (EST == EST_DynamicNone) {
165 if (ComputedEST == EST_BasicNoexcept)
166 ComputedEST = EST_DynamicNone;
167 return;
168 }
169
170 // Check out noexcept specs.
171 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000172 FunctionProtoType::NoexceptResult NR =
173 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000174 assert(NR != FunctionProtoType::NR_NoNoexcept &&
175 "Must have noexcept result for EST_ComputedNoexcept.");
176 assert(NR != FunctionProtoType::NR_Dependent &&
177 "Should not generate implicit declarations for dependent cases, "
178 "and don't know how to handle them anyway.");
179
180 // noexcept(false) -> no spec on the new function
181 if (NR == FunctionProtoType::NR_Throw) {
182 ClearExceptions();
183 ComputedEST = EST_None;
184 }
185 // noexcept(true) won't change anything either.
186 return;
187 }
188
189 assert(EST == EST_Dynamic && "EST case not considered earlier.");
190 assert(ComputedEST != EST_None &&
191 "Shouldn't collect exceptions when throw-all is guaranteed.");
192 ComputedEST = EST_Dynamic;
193 // Record the exceptions in this function's exception specification.
194 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195 EEnd = Proto->exception_end();
196 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000197 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000198 Exceptions.push_back(*E);
199}
200
Richard Smith7a614d82011-06-11 17:19:42 +0000201void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000202 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000203 return;
204
205 // FIXME:
206 //
207 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000208 // [An] implicit exception-specification specifies the type-id T if and
209 // only if T is allowed by the exception-specification of a function directly
210 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000211 // function it directly invokes allows all exceptions, and f shall allow no
212 // exceptions if every function it directly invokes allows no exceptions.
213 //
214 // Note in particular that if an implicit exception-specification is generated
215 // for a function containing a throw-expression, that specification can still
216 // be noexcept(true).
217 //
218 // Note also that 'directly invoked' is not defined in the standard, and there
219 // is no indication that we should only consider potentially-evaluated calls.
220 //
221 // Ultimately we should implement the intent of the standard: the exception
222 // specification should be the set of exceptions which can be thrown by the
223 // implicit definition. For now, we assume that any non-nothrow expression can
224 // throw any exception.
225
Richard Smithe6975e92012-04-17 00:58:00 +0000226 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000227 ComputedEST = EST_None;
228}
229
Anders Carlssoned961f92009-08-25 02:29:20 +0000230bool
John McCall9ae2f072010-08-23 23:25:46 +0000231Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000233 if (RequireCompleteType(Param->getLocation(), Param->getType(),
234 diag::err_typecheck_decl_incomplete_type)) {
235 Param->setInvalidDecl();
236 return true;
237 }
238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // C++ [dcl.fct.default]p5
240 // A default argument expression is implicitly converted (clause
241 // 4) to the parameter type. The default argument expression has
242 // the same semantic constraints as the initializer expression in
243 // a declaration of a variable of the parameter type, using the
244 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000245 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
246 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000247 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
248 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000249 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000250 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
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
Richard Smith6c3af3d2013-01-17 01:17:56 +0000255 CheckCompletedExpr(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.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000355 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000356 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000357 DeclaratorChunk &chunk = D.getTypeObject(i);
358 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000359 if (MightBeFunction) {
360 // This is a function declaration. It can have default arguments, but
361 // keep looking in case its return type is a function type with default
362 // arguments.
363 MightBeFunction = false;
364 continue;
365 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000366 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
367 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000368 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000369 if (Param->hasUnparsedDefaultArg()) {
370 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000371 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000372 << SourceRange((*Toks)[1].getLocation(),
373 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000374 delete Toks;
375 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000376 } else if (Param->getDefaultArg()) {
377 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
378 << Param->getDefaultArg()->getSourceRange();
379 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000380 }
381 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000382 } else if (chunk.Kind != DeclaratorChunk::Paren) {
383 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000384 }
385 }
386}
387
Craig Topper1a6eac82012-09-21 04:33:26 +0000388/// MergeCXXFunctionDecl - Merge two declarations of the same C++
389/// function, once we already know that they have the same
390/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
391/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000392bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
393 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000394 bool Invalid = false;
395
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 // For non-template functions, default arguments can be added in
398 // later declarations of a function in the same
399 // scope. Declarations in different scopes have completely
400 // distinct sets of default arguments. That is, declarations in
401 // inner scopes do not acquire default arguments from
402 // declarations in outer scopes, and vice versa. In a given
403 // function declaration, all parameters subsequent to a
404 // parameter with a default argument shall have default
405 // arguments supplied in this or previous declarations. A
406 // default argument shall not be redefined by a later
407 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000408 //
409 // C++ [dcl.fct.default]p6:
410 // Except for member functions of class templates, the default arguments
411 // in a member function definition that appears outside of the class
412 // definition are added to the set of default arguments provided by the
413 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000414 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
415 ParmVarDecl *OldParam = Old->getParamDecl(p);
416 ParmVarDecl *NewParam = New->getParamDecl(p);
417
James Molloy9cda03f2012-03-13 08:55:35 +0000418 bool OldParamHasDfl = OldParam->hasDefaultArg();
419 bool NewParamHasDfl = NewParam->hasDefaultArg();
420
421 NamedDecl *ND = Old;
422 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
423 // Ignore default parameters of old decl if they are not in
424 // the same scope.
425 OldParamHasDfl = false;
426
427 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000428
Francois Pichet8d051e02011-04-10 03:03:52 +0000429 unsigned DiagDefaultParamID =
430 diag::err_param_default_argument_redefinition;
431
432 // MSVC accepts that default parameters be redefined for member functions
433 // of template class. The new default parameter's value is ignored.
434 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000435 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000436 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
437 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000438 // Merge the old default argument into the new parameter.
439 NewParam->setHasInheritedDefaultArg();
440 if (OldParam->hasUninstantiatedDefaultArg())
441 NewParam->setUninstantiatedDefaultArg(
442 OldParam->getUninstantiatedDefaultArg());
443 else
444 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000445 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000446 Invalid = false;
447 }
448 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000449
Francois Pichet8cf90492011-04-10 04:58:30 +0000450 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
451 // hint here. Alternatively, we could walk the type-source information
452 // for NewParam to find the last source location in the type... but it
453 // isn't worth the effort right now. This is the kind of test case that
454 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000455 // int f(int);
456 // void g(int (*fp)(int) = f);
457 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000458 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000459 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000460
461 // Look for the function declaration where the default argument was
462 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000463 for (FunctionDecl *Older = Old->getPreviousDecl();
464 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000465 if (!Older->getParamDecl(p)->hasDefaultArg())
466 break;
467
468 OldParam = Older->getParamDecl(p);
469 }
470
471 Diag(OldParam->getLocation(), diag::note_previous_definition)
472 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000473 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000474 // Merge the old default argument into the new parameter.
475 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000476 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000477 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000478 if (OldParam->hasUninstantiatedDefaultArg())
479 NewParam->setUninstantiatedDefaultArg(
480 OldParam->getUninstantiatedDefaultArg());
481 else
John McCall3d6c1782010-05-04 01:53:42 +0000482 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000483 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000484 if (New->getDescribedFunctionTemplate()) {
485 // Paragraph 4, quoted above, only applies to non-template functions.
486 Diag(NewParam->getLocation(),
487 diag::err_param_default_argument_template_redecl)
488 << NewParam->getDefaultArgRange();
489 Diag(Old->getLocation(), diag::note_template_prev_declaration)
490 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000491 } else if (New->getTemplateSpecializationKind()
492 != TSK_ImplicitInstantiation &&
493 New->getTemplateSpecializationKind() != TSK_Undeclared) {
494 // C++ [temp.expr.spec]p21:
495 // Default function arguments shall not be specified in a declaration
496 // or a definition for one of the following explicit specializations:
497 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000498 // - the explicit specialization of a member function template;
499 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000500 // template where the class template specialization to which the
501 // member function specialization belongs is implicitly
502 // instantiated.
503 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
504 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
505 << New->getDeclName()
506 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000507 } else if (New->getDeclContext()->isDependentContext()) {
508 // C++ [dcl.fct.default]p6 (DR217):
509 // Default arguments for a member function of a class template shall
510 // be specified on the initial declaration of the member function
511 // within the class template.
512 //
513 // Reading the tea leaves a bit in DR217 and its reference to DR205
514 // leads me to the conclusion that one cannot add default function
515 // arguments for an out-of-line definition of a member function of a
516 // dependent type.
517 int WhichKind = 2;
518 if (CXXRecordDecl *Record
519 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
520 if (Record->getDescribedClassTemplate())
521 WhichKind = 0;
522 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
523 WhichKind = 1;
524 else
525 WhichKind = 2;
526 }
527
528 Diag(NewParam->getLocation(),
529 diag::err_param_default_argument_member_template_redecl)
530 << WhichKind
531 << NewParam->getDefaultArgRange();
532 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000533 }
534 }
535
Richard Smithb8abff62012-11-28 03:45:24 +0000536 // DR1344: If a default argument is added outside a class definition and that
537 // default argument makes the function a special member function, the program
538 // is ill-formed. This can only happen for constructors.
539 if (isa<CXXConstructorDecl>(New) &&
540 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
541 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
542 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
543 if (NewSM != OldSM) {
544 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
545 assert(NewParam->hasDefaultArg());
546 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
547 << NewParam->getDefaultArgRange() << NewSM;
548 Diag(Old->getLocation(), diag::note_previous_declaration);
549 }
550 }
551
Richard Smithff234882012-02-20 23:28:05 +0000552 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000553 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000554 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000555 if (New->isConstexpr() != Old->isConstexpr()) {
556 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
557 << New << New->isConstexpr();
558 Diag(Old->getLocation(), diag::note_previous_declaration);
559 Invalid = true;
560 }
561
Douglas Gregore13ad832010-02-12 07:32:17 +0000562 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000563 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000564
Douglas Gregorcda9c672009-02-16 17:45:42 +0000565 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000566}
567
Sebastian Redl60618fa2011-03-12 11:50:43 +0000568/// \brief Merge the exception specifications of two variable declarations.
569///
570/// This is called when there's a redeclaration of a VarDecl. The function
571/// checks if the redeclaration might have an exception specification and
572/// validates compatibility and merges the specs if necessary.
573void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
574 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000575 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000576 return;
577
578 assert(Context.hasSameType(New->getType(), Old->getType()) &&
579 "Should only be called if types are otherwise the same.");
580
581 QualType NewType = New->getType();
582 QualType OldType = Old->getType();
583
584 // We're only interested in pointers and references to functions, as well
585 // as pointers to member functions.
586 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
587 NewType = R->getPointeeType();
588 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
589 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
590 NewType = P->getPointeeType();
591 OldType = OldType->getAs<PointerType>()->getPointeeType();
592 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
593 NewType = M->getPointeeType();
594 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
595 }
596
597 if (!NewType->isFunctionProtoType())
598 return;
599
600 // There's lots of special cases for functions. For function pointers, system
601 // libraries are hopefully not as broken so that we don't need these
602 // workarounds.
603 if (CheckEquivalentExceptionSpec(
604 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
605 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
606 New->setInvalidDecl();
607 }
608}
609
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610/// CheckCXXDefaultArguments - Verify that the default arguments for a
611/// function declaration are well-formed according to C++
612/// [dcl.fct.default].
613void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
614 unsigned NumParams = FD->getNumParams();
615 unsigned p;
616
Douglas Gregorc6889e72012-02-14 22:28:59 +0000617 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
618 isa<CXXMethodDecl>(FD) &&
619 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
620
Chris Lattner3d1cee32008-04-08 05:04:30 +0000621 // Find first parameter with a default argument
622 for (p = 0; p < NumParams; ++p) {
623 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000624 if (Param->hasDefaultArg()) {
625 // C++11 [expr.prim.lambda]p5:
626 // [...] Default arguments (8.3.6) shall not be specified in the
627 // parameter-declaration-clause of a lambda-declarator.
628 //
629 // FIXME: Core issue 974 strikes this sentence, we only provide an
630 // extension warning.
631 if (IsLambda)
632 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
633 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000634 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000635 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000636 }
637
638 // C++ [dcl.fct.default]p4:
639 // In a given function declaration, all parameters
640 // subsequent to a parameter with a default argument shall
641 // have default arguments supplied in this or previous
642 // declarations. A default argument shall not be redefined
643 // by a later declaration (not even to the same value).
644 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000645 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000646 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000647 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000648 if (Param->isInvalidDecl())
649 /* We already complained about this parameter. */;
650 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000651 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000652 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000653 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000654 else
Mike Stump1eb44332009-09-09 15:08:12 +0000655 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000656 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattner3d1cee32008-04-08 05:04:30 +0000658 LastMissingDefaultArg = p;
659 }
660 }
661
662 if (LastMissingDefaultArg > 0) {
663 // Some default arguments were missing. Clear out all of the
664 // default arguments up to (and including) the last missing
665 // default argument, so that we leave the function parameters
666 // in a semantically valid state.
667 for (p = 0; p <= LastMissingDefaultArg; ++p) {
668 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000669 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000670 Param->setDefaultArg(0);
671 }
672 }
673 }
674}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000675
Richard Smith9f569cc2011-10-01 02:31:28 +0000676// CheckConstexprParameterTypes - Check whether a function's parameter types
677// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000678// diagnostic and return false.
679static bool CheckConstexprParameterTypes(Sema &SemaRef,
680 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 unsigned ArgIndex = 0;
682 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
683 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
684 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
685 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
686 SourceLocation ParamLoc = PD->getLocation();
687 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000688 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000689 diag::err_constexpr_non_literal_param,
690 ArgIndex+1, PD->getSourceRange(),
691 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000692 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000693 }
Joao Matos17d35c32012-08-31 22:18:20 +0000694 return true;
695}
696
697/// \brief Get diagnostic %select index for tag kind for
698/// record diagnostic message.
699/// WARNING: Indexes apply to particular diagnostics only!
700///
701/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000702static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000703 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000704 case TTK_Struct: return 0;
705 case TTK_Interface: return 1;
706 case TTK_Class: return 2;
707 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000708 }
Joao Matos17d35c32012-08-31 22:18:20 +0000709}
710
711// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
712// the requirements of a constexpr function definition or a constexpr
713// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000714// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000715//
Richard Smith86c3ae42012-02-13 03:54:03 +0000716// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
717bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000718 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
719 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000720 // C++11 [dcl.constexpr]p4:
721 // The definition of a constexpr constructor shall satisfy the following
722 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000723 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000724 const CXXRecordDecl *RD = MD->getParent();
725 if (RD->getNumVBases()) {
726 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
727 << isa<CXXConstructorDecl>(NewFD)
728 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
729 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
730 E = RD->vbases_end(); I != E; ++I)
731 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000732 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000733 return false;
734 }
Richard Smith35340502012-01-13 04:54:00 +0000735 }
736
737 if (!isa<CXXConstructorDecl>(NewFD)) {
738 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000739 // The definition of a constexpr function shall satisfy the following
740 // constraints:
741 // - it shall not be virtual;
742 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
743 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000744 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000745
Richard Smith86c3ae42012-02-13 03:54:03 +0000746 // If it's not obvious why this function is virtual, find an overridden
747 // function which uses the 'virtual' keyword.
748 const CXXMethodDecl *WrittenVirtual = Method;
749 while (!WrittenVirtual->isVirtualAsWritten())
750 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
751 if (WrittenVirtual != Method)
752 Diag(WrittenVirtual->getLocation(),
753 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000754 return false;
755 }
756
757 // - its return type shall be a literal type;
758 QualType RT = NewFD->getResultType();
759 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000760 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000761 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000762 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000763 }
764
Richard Smith35340502012-01-13 04:54:00 +0000765 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000766 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000767 return false;
768
Richard Smith9f569cc2011-10-01 02:31:28 +0000769 return true;
770}
771
772/// Check the given declaration statement is legal within a constexpr function
773/// body. C++0x [dcl.constexpr]p3,p4.
774///
775/// \return true if the body is OK, false if we have diagnosed a problem.
776static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
777 DeclStmt *DS) {
778 // C++0x [dcl.constexpr]p3 and p4:
779 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
780 // contain only
781 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
782 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
783 switch ((*DclIt)->getKind()) {
784 case Decl::StaticAssert:
785 case Decl::Using:
786 case Decl::UsingShadow:
787 case Decl::UsingDirective:
788 case Decl::UnresolvedUsingTypename:
789 // - static_assert-declarations
790 // - using-declarations,
791 // - using-directives,
792 continue;
793
794 case Decl::Typedef:
795 case Decl::TypeAlias: {
796 // - typedef declarations and alias-declarations that do not define
797 // classes or enumerations,
798 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
799 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
800 // Don't allow variably-modified types in constexpr functions.
801 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
802 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
803 << TL.getSourceRange() << TL.getType()
804 << isa<CXXConstructorDecl>(Dcl);
805 return false;
806 }
807 continue;
808 }
809
810 case Decl::Enum:
811 case Decl::CXXRecord:
812 // As an extension, we allow the declaration (but not the definition) of
813 // classes and enumerations in all declarations, not just in typedef and
814 // alias declarations.
815 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
816 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
817 << isa<CXXConstructorDecl>(Dcl);
818 return false;
819 }
820 continue;
821
822 case Decl::Var:
823 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
824 << isa<CXXConstructorDecl>(Dcl);
825 return false;
826
827 default:
828 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
829 << isa<CXXConstructorDecl>(Dcl);
830 return false;
831 }
832 }
833
834 return true;
835}
836
837/// Check that the given field is initialized within a constexpr constructor.
838///
839/// \param Dcl The constexpr constructor being checked.
840/// \param Field The field being checked. This may be a member of an anonymous
841/// struct or union nested within the class being checked.
842/// \param Inits All declarations, including anonymous struct/union members and
843/// indirect members, for which any initialization was provided.
844/// \param Diagnosed Set to true if an error is produced.
845static void CheckConstexprCtorInitializer(Sema &SemaRef,
846 const FunctionDecl *Dcl,
847 FieldDecl *Field,
848 llvm::SmallSet<Decl*, 16> &Inits,
849 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000850 if (Field->isUnnamedBitfield())
851 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000852
853 if (Field->isAnonymousStructOrUnion() &&
854 Field->getType()->getAsCXXRecordDecl()->isEmpty())
855 return;
856
Richard Smith9f569cc2011-10-01 02:31:28 +0000857 if (!Inits.count(Field)) {
858 if (!Diagnosed) {
859 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
860 Diagnosed = true;
861 }
862 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
863 } else if (Field->isAnonymousStructOrUnion()) {
864 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
865 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
866 I != E; ++I)
867 // If an anonymous union contains an anonymous struct of which any member
868 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000869 if (!RD->isUnion() || Inits.count(*I))
870 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000871 }
872}
873
874/// Check the body for the given constexpr function declaration only contains
875/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
876///
877/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000878bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000879 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000880 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000881 // The definition of a constexpr function shall satisfy the following
882 // constraints: [...]
883 // - its function-body shall be = delete, = default, or a
884 // compound-statement
885 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000886 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000887 // In the definition of a constexpr constructor, [...]
888 // - its function-body shall not be a function-try-block;
889 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
890 << isa<CXXConstructorDecl>(Dcl);
891 return false;
892 }
893
894 // - its function-body shall be [...] a compound-statement that contains only
895 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
896
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000897 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smith9f569cc2011-10-01 02:31:28 +0000898 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
899 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
900 switch ((*BodyIt)->getStmtClass()) {
901 case Stmt::NullStmtClass:
902 // - null statements,
903 continue;
904
905 case Stmt::DeclStmtClass:
906 // - static_assert-declarations
907 // - using-declarations,
908 // - using-directives,
909 // - typedef declarations and alias-declarations that do not define
910 // classes or enumerations,
911 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
912 return false;
913 continue;
914
915 case Stmt::ReturnStmtClass:
916 // - and exactly one return statement;
917 if (isa<CXXConstructorDecl>(Dcl))
918 break;
919
920 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000921 continue;
922
923 default:
924 break;
925 }
926
927 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928 << isa<CXXConstructorDecl>(Dcl);
929 return false;
930 }
931
932 if (const CXXConstructorDecl *Constructor
933 = dyn_cast<CXXConstructorDecl>(Dcl)) {
934 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000935 // DR1359:
936 // - every non-variant non-static data member and base class sub-object
937 // shall be initialized;
938 // - if the class is a non-empty union, or for each non-empty anonymous
939 // union member of a non-union class, exactly one non-static data member
940 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000941 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000942 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000943 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
944 return false;
945 }
Richard Smith6e433752011-10-10 16:38:04 +0000946 } else if (!Constructor->isDependentContext() &&
947 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000948 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
949
950 // Skip detailed checking if we have enough initializers, and we would
951 // allow at most one initializer per member.
952 bool AnyAnonStructUnionMembers = false;
953 unsigned Fields = 0;
954 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
955 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000956 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000957 AnyAnonStructUnionMembers = true;
958 break;
959 }
960 }
961 if (AnyAnonStructUnionMembers ||
962 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
963 // Check initialization of non-static data members. Base classes are
964 // always initialized so do not need to be checked. Dependent bases
965 // might not have initializers in the member initializer list.
966 llvm::SmallSet<Decl*, 16> Inits;
967 for (CXXConstructorDecl::init_const_iterator
968 I = Constructor->init_begin(), E = Constructor->init_end();
969 I != E; ++I) {
970 if (FieldDecl *FD = (*I)->getMember())
971 Inits.insert(FD);
972 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
973 Inits.insert(ID->chain_begin(), ID->chain_end());
974 }
975
976 bool Diagnosed = false;
977 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
978 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000979 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000980 if (Diagnosed)
981 return false;
982 }
983 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000984 } else {
985 if (ReturnStmts.empty()) {
986 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
987 return false;
988 }
989 if (ReturnStmts.size() > 1) {
990 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
991 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
992 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
993 return false;
994 }
995 }
996
Richard Smith5ba73e12012-02-04 00:33:54 +0000997 // C++11 [dcl.constexpr]p5:
998 // if no function argument values exist such that the function invocation
999 // substitution would produce a constant expression, the program is
1000 // ill-formed; no diagnostic required.
1001 // C++11 [dcl.constexpr]p3:
1002 // - every constructor call and implicit conversion used in initializing the
1003 // return value shall be one of those allowed in a constant expression.
1004 // C++11 [dcl.constexpr]p4:
1005 // - every constructor involved in initializing non-static data members and
1006 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001007 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001008 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001009 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001010 << isa<CXXConstructorDecl>(Dcl);
1011 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1012 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001013 // Don't return false here: we allow this for compatibility in
1014 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001015 }
1016
Richard Smith9f569cc2011-10-01 02:31:28 +00001017 return true;
1018}
1019
Douglas Gregorb48fe382008-10-31 09:07:45 +00001020/// isCurrentClassName - Determine whether the identifier II is the
1021/// name of the class type currently being defined. In the case of
1022/// nested classes, this will only return true if II is the name of
1023/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001024bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1025 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001026 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001027
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001028 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001029 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001030 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001031 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1032 } else
1033 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1034
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001035 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001036 return &II == CurDecl->getIdentifier();
1037 else
1038 return false;
1039}
1040
Douglas Gregor229d47a2012-11-10 07:24:09 +00001041/// \brief Determine whether the given class is a base class of the given
1042/// class, including looking at dependent bases.
1043static bool findCircularInheritance(const CXXRecordDecl *Class,
1044 const CXXRecordDecl *Current) {
1045 SmallVector<const CXXRecordDecl*, 8> Queue;
1046
1047 Class = Class->getCanonicalDecl();
1048 while (true) {
1049 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1050 E = Current->bases_end();
1051 I != E; ++I) {
1052 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1053 if (!Base)
1054 continue;
1055
1056 Base = Base->getDefinition();
1057 if (!Base)
1058 continue;
1059
1060 if (Base->getCanonicalDecl() == Class)
1061 return true;
1062
1063 Queue.push_back(Base);
1064 }
1065
1066 if (Queue.empty())
1067 return false;
1068
1069 Current = Queue.back();
1070 Queue.pop_back();
1071 }
1072
1073 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001074}
1075
Mike Stump1eb44332009-09-09 15:08:12 +00001076/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001077///
1078/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1079/// and returns NULL otherwise.
1080CXXBaseSpecifier *
1081Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1082 SourceRange SpecifierRange,
1083 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001084 TypeSourceInfo *TInfo,
1085 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001086 QualType BaseType = TInfo->getType();
1087
Douglas Gregor2943aed2009-03-03 04:44:36 +00001088 // C++ [class.union]p1:
1089 // A union shall not have base classes.
1090 if (Class->isUnion()) {
1091 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1092 << SpecifierRange;
1093 return 0;
1094 }
1095
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001096 if (EllipsisLoc.isValid() &&
1097 !TInfo->getType()->containsUnexpandedParameterPack()) {
1098 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1099 << TInfo->getTypeLoc().getSourceRange();
1100 EllipsisLoc = SourceLocation();
1101 }
Douglas Gregord777e282012-11-10 01:18:17 +00001102
1103 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1104
1105 if (BaseType->isDependentType()) {
1106 // Make sure that we don't have circular inheritance among our dependent
1107 // bases. For non-dependent bases, the check for completeness below handles
1108 // this.
1109 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1110 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1111 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001112 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001113 Diag(BaseLoc, diag::err_circular_inheritance)
1114 << BaseType << Context.getTypeDeclType(Class);
1115
1116 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1117 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1118 << BaseType;
1119
1120 return 0;
1121 }
1122 }
1123
Mike Stump1eb44332009-09-09 15:08:12 +00001124 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001125 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001126 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001127 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001128
1129 // Base specifiers must be record types.
1130 if (!BaseType->isRecordType()) {
1131 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1132 return 0;
1133 }
1134
1135 // C++ [class.union]p1:
1136 // A union shall not be used as a base class.
1137 if (BaseType->isUnionType()) {
1138 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1139 return 0;
1140 }
1141
1142 // C++ [class.derived]p2:
1143 // The class-name in a base-specifier shall not be an incompletely
1144 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001145 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001146 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001147 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001148 return 0;
John McCall572fc622010-08-17 07:23:57 +00001149 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001150
Eli Friedman1d954f62009-08-15 21:55:26 +00001151 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001152 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001153 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001154 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001155 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001156 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1157 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001158
Anders Carlsson1d209272011-03-25 14:55:14 +00001159 // C++ [class]p3:
1160 // If a class is marked final and it appears as a base-type-specifier in
1161 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001162 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001163 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1164 << CXXBaseDecl->getDeclName();
1165 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1166 << CXXBaseDecl->getDeclName();
1167 return 0;
1168 }
1169
John McCall572fc622010-08-17 07:23:57 +00001170 if (BaseDecl->isInvalidDecl())
1171 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001172
1173 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001174 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001175 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001176 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001177}
1178
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001179/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1180/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001181/// example:
1182/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001183/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001184BaseResult
John McCalld226f652010-08-21 09:40:31 +00001185Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001186 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001187 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001188 ParsedType basetype, SourceLocation BaseLoc,
1189 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001190 if (!classdecl)
1191 return true;
1192
Douglas Gregor40808ce2009-03-09 23:48:35 +00001193 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001194 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001195 if (!Class)
1196 return true;
1197
Richard Smith05321402013-02-19 23:47:15 +00001198 // We do not support any C++11 attributes on base-specifiers yet.
1199 // Diagnose any attributes we see.
1200 if (!Attributes.empty()) {
1201 for (AttributeList *Attr = Attributes.getList(); Attr;
1202 Attr = Attr->getNext()) {
1203 if (Attr->isInvalid() ||
1204 Attr->getKind() == AttributeList::IgnoredAttribute)
1205 continue;
1206 Diag(Attr->getLoc(),
1207 Attr->getKind() == AttributeList::UnknownAttribute
1208 ? diag::warn_unknown_attribute_ignored
1209 : diag::err_base_specifier_attribute)
1210 << Attr->getName();
1211 }
1212 }
1213
Nick Lewycky56062202010-07-26 16:56:01 +00001214 TypeSourceInfo *TInfo = 0;
1215 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001216
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001217 if (EllipsisLoc.isInvalid() &&
1218 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001219 UPPC_BaseType))
1220 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001221
Douglas Gregor2943aed2009-03-03 04:44:36 +00001222 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001223 Virtual, Access, TInfo,
1224 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001225 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001226 else
1227 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Douglas Gregor2943aed2009-03-03 04:44:36 +00001229 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001230}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001231
Douglas Gregor2943aed2009-03-03 04:44:36 +00001232/// \brief Performs the actual work of attaching the given base class
1233/// specifiers to a C++ class.
1234bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1235 unsigned NumBases) {
1236 if (NumBases == 0)
1237 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001238
1239 // Used to keep track of which base types we have already seen, so
1240 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001241 // that the key is always the unqualified canonical type of the base
1242 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001243 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1244
1245 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001246 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001247 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001248 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001249 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001250 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001251 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001252
1253 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1254 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001255 // C++ [class.mi]p3:
1256 // A class shall not be specified as a direct base class of a
1257 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001258 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001259 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001260 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001261 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001262
1263 // Delete the duplicate base class specifier; we're going to
1264 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001265 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001266
1267 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001268 } else {
1269 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001270 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001271 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001272 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1273 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1274 if (Class->isInterface() &&
1275 (!RD->isInterface() ||
1276 KnownBase->getAccessSpecifier() != AS_public)) {
1277 // The Microsoft extension __interface does not permit bases that
1278 // are not themselves public interfaces.
1279 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1280 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1281 << RD->getSourceRange();
1282 Invalid = true;
1283 }
1284 if (RD->hasAttr<WeakAttr>())
1285 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1286 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001287 }
1288 }
1289
1290 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001291 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001292
1293 // Delete the remaining (good) base class specifiers, since their
1294 // data has been copied into the CXXRecordDecl.
1295 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001296 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001297
1298 return Invalid;
1299}
1300
1301/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1302/// class, after checking whether there are any duplicate base
1303/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001304void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001305 unsigned NumBases) {
1306 if (!ClassDecl || !Bases || !NumBases)
1307 return;
1308
1309 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001310 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001312}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001313
John McCall3cb0ebd2010-03-10 03:28:59 +00001314static CXXRecordDecl *GetClassForType(QualType T) {
1315 if (const RecordType *RT = T->getAs<RecordType>())
1316 return cast<CXXRecordDecl>(RT->getDecl());
1317 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1318 return ICT->getDecl();
1319 else
1320 return 0;
1321}
1322
Douglas Gregora8f32e02009-10-06 17:59:45 +00001323/// \brief Determine whether the type \p Derived is a C++ class that is
1324/// derived from the type \p Base.
1325bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001326 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001327 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001328
1329 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1330 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001331 return false;
1332
John McCall3cb0ebd2010-03-10 03:28:59 +00001333 CXXRecordDecl *BaseRD = GetClassForType(Base);
1334 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001335 return false;
1336
John McCall86ff3082010-02-04 22:26:26 +00001337 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1338 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001339}
1340
1341/// \brief Determine whether the type \p Derived is a C++ class that is
1342/// derived from the type \p Base.
1343bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001344 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001345 return false;
1346
John McCall3cb0ebd2010-03-10 03:28:59 +00001347 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1348 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001349 return false;
1350
John McCall3cb0ebd2010-03-10 03:28:59 +00001351 CXXRecordDecl *BaseRD = GetClassForType(Base);
1352 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001353 return false;
1354
Douglas Gregora8f32e02009-10-06 17:59:45 +00001355 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1356}
1357
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001358void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001359 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001360 assert(BasePathArray.empty() && "Base path array must be empty!");
1361 assert(Paths.isRecordingPaths() && "Must record paths!");
1362
1363 const CXXBasePath &Path = Paths.front();
1364
1365 // We first go backward and check if we have a virtual base.
1366 // FIXME: It would be better if CXXBasePath had the base specifier for
1367 // the nearest virtual base.
1368 unsigned Start = 0;
1369 for (unsigned I = Path.size(); I != 0; --I) {
1370 if (Path[I - 1].Base->isVirtual()) {
1371 Start = I - 1;
1372 break;
1373 }
1374 }
1375
1376 // Now add all bases.
1377 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001378 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001379}
1380
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001381/// \brief Determine whether the given base path includes a virtual
1382/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001383bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1384 for (CXXCastPath::const_iterator B = BasePath.begin(),
1385 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001386 B != BEnd; ++B)
1387 if ((*B)->isVirtual())
1388 return true;
1389
1390 return false;
1391}
1392
Douglas Gregora8f32e02009-10-06 17:59:45 +00001393/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1394/// conversion (where Derived and Base are class types) is
1395/// well-formed, meaning that the conversion is unambiguous (and
1396/// that all of the base classes are accessible). Returns true
1397/// and emits a diagnostic if the code is ill-formed, returns false
1398/// otherwise. Loc is the location where this routine should point to
1399/// if there is an error, and Range is the source range to highlight
1400/// if there is an error.
1401bool
1402Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001403 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001404 unsigned AmbigiousBaseConvID,
1405 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001406 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001407 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001408 // First, determine whether the path from Derived to Base is
1409 // ambiguous. This is slightly more expensive than checking whether
1410 // the Derived to Base conversion exists, because here we need to
1411 // explore multiple paths to determine if there is an ambiguity.
1412 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1413 /*DetectVirtual=*/false);
1414 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1415 assert(DerivationOkay &&
1416 "Can only be used with a derived-to-base conversion");
1417 (void)DerivationOkay;
1418
1419 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001420 if (InaccessibleBaseID) {
1421 // Check that the base class can be accessed.
1422 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1423 InaccessibleBaseID)) {
1424 case AR_inaccessible:
1425 return true;
1426 case AR_accessible:
1427 case AR_dependent:
1428 case AR_delayed:
1429 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001430 }
John McCall6b2accb2010-02-10 09:31:12 +00001431 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001432
1433 // Build a base path if necessary.
1434 if (BasePath)
1435 BuildBasePathArray(Paths, *BasePath);
1436 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001437 }
1438
1439 // We know that the derived-to-base conversion is ambiguous, and
1440 // we're going to produce a diagnostic. Perform the derived-to-base
1441 // search just one more time to compute all of the possible paths so
1442 // that we can print them out. This is more expensive than any of
1443 // the previous derived-to-base checks we've done, but at this point
1444 // performance isn't as much of an issue.
1445 Paths.clear();
1446 Paths.setRecordingPaths(true);
1447 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1448 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1449 (void)StillOkay;
1450
1451 // Build up a textual representation of the ambiguous paths, e.g.,
1452 // D -> B -> A, that will be used to illustrate the ambiguous
1453 // conversions in the diagnostic. We only print one of the paths
1454 // to each base class subobject.
1455 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1456
1457 Diag(Loc, AmbigiousBaseConvID)
1458 << Derived << Base << PathDisplayStr << Range << Name;
1459 return true;
1460}
1461
1462bool
1463Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001464 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001465 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001466 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001467 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001468 IgnoreAccess ? 0
1469 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001470 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001471 Loc, Range, DeclarationName(),
1472 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001473}
1474
1475
1476/// @brief Builds a string representing ambiguous paths from a
1477/// specific derived class to different subobjects of the same base
1478/// class.
1479///
1480/// This function builds a string that can be used in error messages
1481/// to show the different paths that one can take through the
1482/// inheritance hierarchy to go from the derived class to different
1483/// subobjects of a base class. The result looks something like this:
1484/// @code
1485/// struct D -> struct B -> struct A
1486/// struct D -> struct C -> struct A
1487/// @endcode
1488std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1489 std::string PathDisplayStr;
1490 std::set<unsigned> DisplayedPaths;
1491 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1492 Path != Paths.end(); ++Path) {
1493 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1494 // We haven't displayed a path to this particular base
1495 // class subobject yet.
1496 PathDisplayStr += "\n ";
1497 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1498 for (CXXBasePath::const_iterator Element = Path->begin();
1499 Element != Path->end(); ++Element)
1500 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1501 }
1502 }
1503
1504 return PathDisplayStr;
1505}
1506
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001507//===----------------------------------------------------------------------===//
1508// C++ class member Handling
1509//===----------------------------------------------------------------------===//
1510
Abramo Bagnara6206d532010-06-05 05:09:32 +00001511/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001512bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1513 SourceLocation ASLoc,
1514 SourceLocation ColonLoc,
1515 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001516 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001517 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001518 ASLoc, ColonLoc);
1519 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001520 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001521}
1522
Richard Smitha4b39652012-08-06 03:25:17 +00001523/// CheckOverrideControl - Check C++11 override control semantics.
1524void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001525 if (D->isInvalidDecl())
1526 return;
1527
Chris Lattner5f9e2722011-07-23 10:55:15 +00001528 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001529
Richard Smitha4b39652012-08-06 03:25:17 +00001530 // Do we know which functions this declaration might be overriding?
1531 bool OverridesAreKnown = !MD ||
1532 (!MD->getParent()->hasAnyDependentBases() &&
1533 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001534
Richard Smitha4b39652012-08-06 03:25:17 +00001535 if (!MD || !MD->isVirtual()) {
1536 if (OverridesAreKnown) {
1537 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1538 Diag(OA->getLocation(),
1539 diag::override_keyword_only_allowed_on_virtual_member_functions)
1540 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1541 D->dropAttr<OverrideAttr>();
1542 }
1543 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1544 Diag(FA->getLocation(),
1545 diag::override_keyword_only_allowed_on_virtual_member_functions)
1546 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1547 D->dropAttr<FinalAttr>();
1548 }
1549 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001550 return;
1551 }
Richard Smitha4b39652012-08-06 03:25:17 +00001552
1553 if (!OverridesAreKnown)
1554 return;
1555
1556 // C++11 [class.virtual]p5:
1557 // If a virtual function is marked with the virt-specifier override and
1558 // does not override a member function of a base class, the program is
1559 // ill-formed.
1560 bool HasOverriddenMethods =
1561 MD->begin_overridden_methods() != MD->end_overridden_methods();
1562 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1563 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1564 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001565}
1566
Richard Smitha4b39652012-08-06 03:25:17 +00001567/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001568/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001569/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001570bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1571 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001572 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001573 return false;
1574
1575 Diag(New->getLocation(), diag::err_final_function_overridden)
1576 << New->getDeclName();
1577 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1578 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001579}
1580
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001581static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001582 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1583 // FIXME: Destruction of ObjC lifetime types has side-effects.
1584 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1585 return !RD->isCompleteDefinition() ||
1586 !RD->hasTrivialDefaultConstructor() ||
1587 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001588 return false;
1589}
1590
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001591/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1592/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001593/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001594/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1595/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001596NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001597Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001598 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001599 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001600 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001601 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001602 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1603 DeclarationName Name = NameInfo.getName();
1604 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001605
1606 // For anonymous bitfields, the location should point to the type.
1607 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001608 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001609
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001610 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001611
John McCall4bde1e12010-06-04 08:34:12 +00001612 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001613 assert(!DS.isFriendSpecified());
1614
Richard Smith1ab0d902011-06-25 02:28:38 +00001615 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001616
John McCalle402e722012-09-25 07:32:39 +00001617 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1618 // The Microsoft extension __interface only permits public member functions
1619 // and prohibits constructors, destructors, operators, non-public member
1620 // functions, static methods and data members.
1621 unsigned InvalidDecl;
1622 bool ShowDeclName = true;
1623 if (!isFunc)
1624 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1625 else if (AS != AS_public)
1626 InvalidDecl = 2;
1627 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1628 InvalidDecl = 3;
1629 else switch (Name.getNameKind()) {
1630 case DeclarationName::CXXConstructorName:
1631 InvalidDecl = 4;
1632 ShowDeclName = false;
1633 break;
1634
1635 case DeclarationName::CXXDestructorName:
1636 InvalidDecl = 5;
1637 ShowDeclName = false;
1638 break;
1639
1640 case DeclarationName::CXXOperatorName:
1641 case DeclarationName::CXXConversionFunctionName:
1642 InvalidDecl = 6;
1643 break;
1644
1645 default:
1646 InvalidDecl = 0;
1647 break;
1648 }
1649
1650 if (InvalidDecl) {
1651 if (ShowDeclName)
1652 Diag(Loc, diag::err_invalid_member_in_interface)
1653 << (InvalidDecl-1) << Name;
1654 else
1655 Diag(Loc, diag::err_invalid_member_in_interface)
1656 << (InvalidDecl-1) << "";
1657 return 0;
1658 }
1659 }
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661 // C++ 9.2p6: A member shall not be declared to have automatic storage
1662 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001663 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1664 // data members and cannot be applied to names declared const or static,
1665 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001666 switch (DS.getStorageClassSpec()) {
1667 case DeclSpec::SCS_unspecified:
1668 case DeclSpec::SCS_typedef:
1669 case DeclSpec::SCS_static:
1670 // FALL THROUGH.
1671 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001672 case DeclSpec::SCS_mutable:
1673 if (isFunc) {
1674 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001675 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001676 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001677 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Sebastian Redla11f42f2008-11-17 23:24:37 +00001679 // FIXME: It would be nicer if the keyword was ignored only for this
1680 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001681 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001682 }
1683 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001684 default:
1685 if (DS.getStorageClassSpecLoc().isValid())
1686 Diag(DS.getStorageClassSpecLoc(),
1687 diag::err_storageclass_invalid_for_member);
1688 else
1689 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1690 D.getMutableDeclSpec().ClearStorageClassSpecs();
1691 }
1692
Sebastian Redl669d5d72008-11-14 23:42:31 +00001693 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1694 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001695 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001696
David Blaikie1d87fba2013-01-30 01:22:18 +00001697 if (DS.isConstexprSpecified() && isInstField) {
1698 SemaDiagnosticBuilder B =
1699 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1700 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1701 if (InitStyle == ICIS_NoInit) {
1702 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1703 D.getMutableDeclSpec().ClearConstexprSpec();
1704 const char *PrevSpec;
1705 unsigned DiagID;
1706 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1707 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001708 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001709 assert(!Failed && "Making a constexpr member const shouldn't fail");
1710 } else {
1711 B << 1;
1712 const char *PrevSpec;
1713 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001714 if (D.getMutableDeclSpec().SetStorageClassSpec(
1715 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001716 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001717 "This is the only DeclSpec that should fail to be applied");
1718 B << 1;
1719 } else {
1720 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1721 isInstField = false;
1722 }
1723 }
1724 }
1725
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001726 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001727 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001728 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001729
1730 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001731 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001732 Diag(Loc, diag::err_bad_variable_name)
1733 << Name;
1734 return 0;
1735 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001736
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001737 IdentifierInfo *II = Name.getAsIdentifierInfo();
1738
Douglas Gregorf2503652011-09-21 14:40:46 +00001739 // Member field could not be with "template" keyword.
1740 // So TemplateParameterLists should be empty in this case.
1741 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001742 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001743 if (TemplateParams->size()) {
1744 // There is no such thing as a member field template.
1745 Diag(D.getIdentifierLoc(), diag::err_template_member)
1746 << II
1747 << SourceRange(TemplateParams->getTemplateLoc(),
1748 TemplateParams->getRAngleLoc());
1749 } else {
1750 // There is an extraneous 'template<>' for this member.
1751 Diag(TemplateParams->getTemplateLoc(),
1752 diag::err_template_member_noparams)
1753 << II
1754 << SourceRange(TemplateParams->getTemplateLoc(),
1755 TemplateParams->getRAngleLoc());
1756 }
1757 return 0;
1758 }
1759
Douglas Gregor922fff22010-10-13 22:19:53 +00001760 if (SS.isSet() && !SS.isInvalid()) {
1761 // The user provided a superfluous scope specifier inside a class
1762 // definition:
1763 //
1764 // class X {
1765 // int X::member;
1766 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001767 if (DeclContext *DC = computeDeclContext(SS, false))
1768 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001769 else
1770 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1771 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001772
Douglas Gregor922fff22010-10-13 22:19:53 +00001773 SS.clear();
1774 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001775
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001776 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001777 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001778 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001779 } else {
David Blaikie1d87fba2013-01-30 01:22:18 +00001780 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Richard Smith7a614d82011-06-11 17:19:42 +00001781
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001782 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001783 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001784 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001785 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001786
1787 // Non-instance-fields can't have a bitfield.
1788 if (BitWidth) {
1789 if (Member->isInvalidDecl()) {
1790 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001791 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001792 // C++ 9.6p3: A bit-field shall not be a static member.
1793 // "static member 'A' cannot be a bit-field"
1794 Diag(Loc, diag::err_static_not_bitfield)
1795 << Name << BitWidth->getSourceRange();
1796 } else if (isa<TypedefDecl>(Member)) {
1797 // "typedef member 'x' cannot be a bit-field"
1798 Diag(Loc, diag::err_typedef_not_bitfield)
1799 << Name << BitWidth->getSourceRange();
1800 } else {
1801 // A function typedef ("typedef int f(); f a;").
1802 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1803 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001804 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001805 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001806 }
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Chris Lattner8b963ef2009-03-05 23:01:03 +00001808 BitWidth = 0;
1809 Member->setInvalidDecl();
1810 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001811
1812 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregor37b372b2009-08-20 22:52:58 +00001814 // If we have declared a member function template, set the access of the
1815 // templated declaration as well.
1816 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1817 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001818 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001819
Richard Smitha4b39652012-08-06 03:25:17 +00001820 if (VS.isOverrideSpecified())
1821 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1822 if (VS.isFinalSpecified())
1823 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001824
Douglas Gregorf5251602011-03-08 17:10:18 +00001825 if (VS.getLastLocation().isValid()) {
1826 // Update the end location of a method that has a virt-specifiers.
1827 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1828 MD->setRangeEnd(VS.getLastLocation());
1829 }
Richard Smitha4b39652012-08-06 03:25:17 +00001830
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001831 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001832
Douglas Gregor10bd3682008-11-17 22:58:34 +00001833 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001834
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001835 if (isInstField) {
1836 FieldDecl *FD = cast<FieldDecl>(Member);
1837 FieldCollector->Add(FD);
1838
1839 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1840 FD->getLocation())
1841 != DiagnosticsEngine::Ignored) {
1842 // Remember all explicit private FieldDecls that have a name, no side
1843 // effects and are not part of a dependent type declaration.
1844 if (!FD->isImplicit() && FD->getDeclName() &&
1845 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001846 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001847 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001848 !InitializationHasSideEffects(*FD))
1849 UnusedPrivateFields.insert(FD);
1850 }
1851 }
1852
John McCalld226f652010-08-21 09:40:31 +00001853 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001854}
1855
Hans Wennborg471f9852012-09-18 15:58:06 +00001856namespace {
1857 class UninitializedFieldVisitor
1858 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1859 Sema &S;
1860 ValueDecl *VD;
1861 public:
1862 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1863 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001864 S(S) {
1865 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1866 this->VD = IFD->getAnonField();
1867 else
1868 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001869 }
1870
1871 void HandleExpr(Expr *E) {
1872 if (!E) return;
1873
1874 // Expressions like x(x) sometimes lack the surrounding expressions
1875 // but need to be checked anyways.
1876 HandleValue(E);
1877 Visit(E);
1878 }
1879
1880 void HandleValue(Expr *E) {
1881 E = E->IgnoreParens();
1882
1883 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1884 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001885 return;
1886
1887 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1888 // or union.
1889 MemberExpr *FieldME = ME;
1890
Hans Wennborg471f9852012-09-18 15:58:06 +00001891 Expr *Base = E;
1892 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001893 ME = cast<MemberExpr>(Base);
1894
1895 if (isa<VarDecl>(ME->getMemberDecl()))
1896 return;
1897
1898 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1899 if (!FD->isAnonymousStructOrUnion())
1900 FieldME = ME;
1901
Hans Wennborg471f9852012-09-18 15:58:06 +00001902 Base = ME->getBase();
1903 }
1904
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001905 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001906 unsigned diag = VD->getType()->isReferenceType()
1907 ? diag::warn_reference_field_is_uninit
1908 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001909 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001910 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001911 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001912 }
1913
1914 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1915 HandleValue(CO->getTrueExpr());
1916 HandleValue(CO->getFalseExpr());
1917 return;
1918 }
1919
1920 if (BinaryConditionalOperator *BCO =
1921 dyn_cast<BinaryConditionalOperator>(E)) {
1922 HandleValue(BCO->getCommon());
1923 HandleValue(BCO->getFalseExpr());
1924 return;
1925 }
1926
1927 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1928 switch (BO->getOpcode()) {
1929 default:
1930 return;
1931 case(BO_PtrMemD):
1932 case(BO_PtrMemI):
1933 HandleValue(BO->getLHS());
1934 return;
1935 case(BO_Comma):
1936 HandleValue(BO->getRHS());
1937 return;
1938 }
1939 }
1940 }
1941
1942 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1943 if (E->getCastKind() == CK_LValueToRValue)
1944 HandleValue(E->getSubExpr());
1945
1946 Inherited::VisitImplicitCastExpr(E);
1947 }
1948
1949 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1950 Expr *Callee = E->getCallee();
1951 if (isa<MemberExpr>(Callee))
1952 HandleValue(Callee);
1953
1954 Inherited::VisitCXXMemberCallExpr(E);
1955 }
1956 };
1957 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1958 ValueDecl *VD) {
1959 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1960 }
1961} // namespace
1962
Richard Smith7a614d82011-06-11 17:19:42 +00001963/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001964/// in-class initializer for a non-static C++ class member, and after
1965/// instantiating an in-class initializer in a class template. Such actions
1966/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001967void
Richard Smithca523302012-06-10 03:12:00 +00001968Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001969 Expr *InitExpr) {
1970 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001971 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1972 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001973
1974 if (!InitExpr) {
1975 FD->setInvalidDecl();
1976 FD->removeInClassInitializer();
1977 return;
1978 }
1979
Peter Collingbournefef21892011-10-23 18:59:44 +00001980 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1981 FD->setInvalidDecl();
1982 FD->removeInClassInitializer();
1983 return;
1984 }
1985
Hans Wennborg471f9852012-09-18 15:58:06 +00001986 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1987 != DiagnosticsEngine::Ignored) {
1988 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1989 }
1990
Richard Smith7a614d82011-06-11 17:19:42 +00001991 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00001992 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001993 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001994 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001995 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1996 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001997 Expr **Inits = &InitExpr;
1998 unsigned NumInits = 1;
1999 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002000 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002001 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002002 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00002003 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2004 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00002005 if (Init.isInvalid()) {
2006 FD->setInvalidDecl();
2007 return;
2008 }
Richard Smith7a614d82011-06-11 17:19:42 +00002009 }
2010
Richard Smith41956372013-01-14 22:39:08 +00002011 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002012 // The initialization of each base and member constitutes a
2013 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002014 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002015 if (Init.isInvalid()) {
2016 FD->setInvalidDecl();
2017 return;
2018 }
2019
2020 InitExpr = Init.release();
2021
2022 FD->setInClassInitializer(InitExpr);
2023}
2024
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002025/// \brief Find the direct and/or virtual base specifiers that
2026/// correspond to the given base type, for use in base initialization
2027/// within a constructor.
2028static bool FindBaseInitializer(Sema &SemaRef,
2029 CXXRecordDecl *ClassDecl,
2030 QualType BaseType,
2031 const CXXBaseSpecifier *&DirectBaseSpec,
2032 const CXXBaseSpecifier *&VirtualBaseSpec) {
2033 // First, check for a direct base class.
2034 DirectBaseSpec = 0;
2035 for (CXXRecordDecl::base_class_const_iterator Base
2036 = ClassDecl->bases_begin();
2037 Base != ClassDecl->bases_end(); ++Base) {
2038 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2039 // We found a direct base of this type. That's what we're
2040 // initializing.
2041 DirectBaseSpec = &*Base;
2042 break;
2043 }
2044 }
2045
2046 // Check for a virtual base class.
2047 // FIXME: We might be able to short-circuit this if we know in advance that
2048 // there are no virtual bases.
2049 VirtualBaseSpec = 0;
2050 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2051 // We haven't found a base yet; search the class hierarchy for a
2052 // virtual base class.
2053 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2054 /*DetectVirtual=*/false);
2055 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2056 BaseType, Paths)) {
2057 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2058 Path != Paths.end(); ++Path) {
2059 if (Path->back().Base->isVirtual()) {
2060 VirtualBaseSpec = Path->back().Base;
2061 break;
2062 }
2063 }
2064 }
2065 }
2066
2067 return DirectBaseSpec || VirtualBaseSpec;
2068}
2069
Sebastian Redl6df65482011-09-24 17:48:25 +00002070/// \brief Handle a C++ member initializer using braced-init-list syntax.
2071MemInitResult
2072Sema::ActOnMemInitializer(Decl *ConstructorD,
2073 Scope *S,
2074 CXXScopeSpec &SS,
2075 IdentifierInfo *MemberOrBase,
2076 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002077 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002078 SourceLocation IdLoc,
2079 Expr *InitList,
2080 SourceLocation EllipsisLoc) {
2081 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002082 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002083 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002084}
2085
2086/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002087MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002088Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002089 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002090 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002091 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002092 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002093 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002094 SourceLocation IdLoc,
2095 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002096 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002097 SourceLocation RParenLoc,
2098 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002099 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2100 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002101 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002102 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002103 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002104}
2105
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002106namespace {
2107
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002108// Callback to only accept typo corrections that can be a valid C++ member
2109// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002110class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2111 public:
2112 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2113 : ClassDecl(ClassDecl) {}
2114
2115 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2116 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2117 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2118 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2119 else
2120 return isa<TypeDecl>(ND);
2121 }
2122 return false;
2123 }
2124
2125 private:
2126 CXXRecordDecl *ClassDecl;
2127};
2128
2129}
2130
Sebastian Redl6df65482011-09-24 17:48:25 +00002131/// \brief Handle a C++ member initializer.
2132MemInitResult
2133Sema::BuildMemInitializer(Decl *ConstructorD,
2134 Scope *S,
2135 CXXScopeSpec &SS,
2136 IdentifierInfo *MemberOrBase,
2137 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002138 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002139 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002140 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002141 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002142 if (!ConstructorD)
2143 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002145 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002146
2147 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002148 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002149 if (!Constructor) {
2150 // The user wrote a constructor initializer on a function that is
2151 // not a C++ constructor. Ignore the error for now, because we may
2152 // have more member initializers coming; we'll diagnose it just
2153 // once in ActOnMemInitializers.
2154 return true;
2155 }
2156
2157 CXXRecordDecl *ClassDecl = Constructor->getParent();
2158
2159 // C++ [class.base.init]p2:
2160 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002161 // constructor's class and, if not found in that scope, are looked
2162 // up in the scope containing the constructor's definition.
2163 // [Note: if the constructor's class contains a member with the
2164 // same name as a direct or virtual base class of the class, a
2165 // mem-initializer-id naming the member or base class and composed
2166 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002167 // mem-initializer-id for the hidden base class may be specified
2168 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002169 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002170 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002171 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002172 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002173 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002174 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002175 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2176 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002177 if (EllipsisLoc.isValid())
2178 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002179 << MemberOrBase
2180 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002181
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002182 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002183 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002184 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002185 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002186 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002187 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002188 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002189
2190 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002191 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002192 } else if (DS.getTypeSpecType() == TST_decltype) {
2193 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002194 } else {
2195 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2196 LookupParsedName(R, S, &SS);
2197
2198 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2199 if (!TyD) {
2200 if (R.isAmbiguous()) return true;
2201
John McCallfd225442010-04-09 19:01:14 +00002202 // We don't want access-control diagnostics here.
2203 R.suppressDiagnostics();
2204
Douglas Gregor7a886e12010-01-19 06:46:48 +00002205 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2206 bool NotUnknownSpecialization = false;
2207 DeclContext *DC = computeDeclContext(SS, false);
2208 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2209 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2210
2211 if (!NotUnknownSpecialization) {
2212 // When the scope specifier can refer to a member of an unknown
2213 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002214 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2215 SS.getWithLocInContext(Context),
2216 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002217 if (BaseType.isNull())
2218 return true;
2219
Douglas Gregor7a886e12010-01-19 06:46:48 +00002220 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002221 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002222 }
2223 }
2224
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002225 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002226 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002227 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002228 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002229 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002230 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002231 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2232 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002233 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002234 // We have found a non-static data member with a similar
2235 // name to what was typed; complain and initialize that
2236 // member.
2237 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2238 << MemberOrBase << true << CorrectedQuotedStr
2239 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2240 Diag(Member->getLocation(), diag::note_previous_decl)
2241 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002242
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002243 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002244 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002245 const CXXBaseSpecifier *DirectBaseSpec;
2246 const CXXBaseSpecifier *VirtualBaseSpec;
2247 if (FindBaseInitializer(*this, ClassDecl,
2248 Context.getTypeDeclType(Type),
2249 DirectBaseSpec, VirtualBaseSpec)) {
2250 // We have found a direct or virtual base class with a
2251 // similar name to what was typed; complain and initialize
2252 // that base class.
2253 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002254 << MemberOrBase << false << CorrectedQuotedStr
2255 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002256
2257 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2258 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002259 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002260 diag::note_base_class_specified_here)
2261 << BaseSpec->getType()
2262 << BaseSpec->getSourceRange();
2263
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002264 TyD = Type;
2265 }
2266 }
2267 }
2268
Douglas Gregor7a886e12010-01-19 06:46:48 +00002269 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002270 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002271 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002272 return true;
2273 }
John McCall2b194412009-12-21 10:41:20 +00002274 }
2275
Douglas Gregor7a886e12010-01-19 06:46:48 +00002276 if (BaseType.isNull()) {
2277 BaseType = Context.getTypeDeclType(TyD);
2278 if (SS.isSet()) {
2279 NestedNameSpecifier *Qualifier =
2280 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002281
Douglas Gregor7a886e12010-01-19 06:46:48 +00002282 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002283 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002284 }
John McCall2b194412009-12-21 10:41:20 +00002285 }
2286 }
Mike Stump1eb44332009-09-09 15:08:12 +00002287
John McCalla93c9342009-12-07 02:54:59 +00002288 if (!TInfo)
2289 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002290
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002291 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002292}
2293
Chandler Carruth81c64772011-09-03 01:14:15 +00002294/// Checks a member initializer expression for cases where reference (or
2295/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002296static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2297 Expr *Init,
2298 SourceLocation IdLoc) {
2299 QualType MemberTy = Member->getType();
2300
2301 // We only handle pointers and references currently.
2302 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2303 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2304 return;
2305
2306 const bool IsPointer = MemberTy->isPointerType();
2307 if (IsPointer) {
2308 if (const UnaryOperator *Op
2309 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2310 // The only case we're worried about with pointers requires taking the
2311 // address.
2312 if (Op->getOpcode() != UO_AddrOf)
2313 return;
2314
2315 Init = Op->getSubExpr();
2316 } else {
2317 // We only handle address-of expression initializers for pointers.
2318 return;
2319 }
2320 }
2321
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002322 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2323 // Taking the address of a temporary will be diagnosed as a hard error.
2324 if (IsPointer)
2325 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002326
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002327 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2328 << Member << Init->getSourceRange();
2329 } else if (const DeclRefExpr *DRE
2330 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2331 // We only warn when referring to a non-reference parameter declaration.
2332 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2333 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002334 return;
2335
2336 S.Diag(Init->getExprLoc(),
2337 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2338 : diag::warn_bind_ref_member_to_parameter)
2339 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002340 } else {
2341 // Other initializers are fine.
2342 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002343 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002344
2345 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2346 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002347}
2348
John McCallf312b1e2010-08-26 23:41:50 +00002349MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002350Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002351 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002352 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2353 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2354 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002355 "Member must be a FieldDecl or IndirectFieldDecl");
2356
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002357 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002358 return true;
2359
Douglas Gregor464b2f02010-11-05 22:21:31 +00002360 if (Member->isInvalidDecl())
2361 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002362
John McCallb4190042009-11-04 23:02:40 +00002363 // Diagnose value-uses of fields to initialize themselves, e.g.
2364 // foo(foo)
2365 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002366 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002367 Expr **Args;
2368 unsigned NumArgs;
2369 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2370 Args = ParenList->getExprs();
2371 NumArgs = ParenList->getNumExprs();
Richard Smithc83c2302012-12-19 01:39:02 +00002372 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002373 Args = InitList->getInits();
2374 NumArgs = InitList->getNumInits();
Richard Smithc83c2302012-12-19 01:39:02 +00002375 } else {
2376 // Template instantiation doesn't reconstruct ParenListExprs for us.
2377 Args = &Init;
2378 NumArgs = 1;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002379 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002380
Richard Trieude5e75c2012-06-14 23:11:34 +00002381 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2382 != DiagnosticsEngine::Ignored)
2383 for (unsigned i = 0; i < NumArgs; ++i)
2384 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002385 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002386 // initializing the i'th field, throw a warning if any of the >= i'th
2387 // fields are used, as they are not yet initialized.
2388 // Right now we are only handling the case where the i'th field uses
2389 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002390 // Also need to take into account that some fields may be initialized by
2391 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002392 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002393
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002394 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002395
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002396 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002397 // Can't check initialization for a member of dependent type or when
2398 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002399 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002400 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002401 bool InitList = false;
2402 if (isa<InitListExpr>(Init)) {
2403 InitList = true;
2404 Args = &Init;
2405 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002406
2407 if (isStdInitializerList(Member->getType(), 0)) {
2408 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2409 << /*at end of ctor*/1 << InitRange;
2410 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002411 }
2412
Chandler Carruth894aed92010-12-06 09:23:57 +00002413 // Initialize the member.
2414 InitializedEntity MemberEntity =
2415 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2416 : InitializedEntity::InitializeMember(IndirectMember, 0);
2417 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002418 InitList ? InitializationKind::CreateDirectList(IdLoc)
2419 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2420 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002421
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002422 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2423 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002424 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002425 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002426 if (MemberInit.isInvalid())
2427 return true;
2428
Richard Smith41956372013-01-14 22:39:08 +00002429 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002430 // The initialization of each base and member constitutes a
2431 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002432 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002433 if (MemberInit.isInvalid())
2434 return true;
2435
Richard Smithc83c2302012-12-19 01:39:02 +00002436 Init = MemberInit.get();
2437 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002438 }
2439
Chandler Carruth894aed92010-12-06 09:23:57 +00002440 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002441 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2442 InitRange.getBegin(), Init,
2443 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002444 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002445 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2446 InitRange.getBegin(), Init,
2447 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002448 }
Eli Friedman59c04372009-07-29 19:44:27 +00002449}
2450
John McCallf312b1e2010-08-26 23:41:50 +00002451MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002452Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002453 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002454 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002455 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002456 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002457 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002458 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002459
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002460 bool InitList = true;
2461 Expr **Args = &Init;
2462 unsigned NumArgs = 1;
2463 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2464 InitList = false;
2465 Args = ParenList->getExprs();
2466 NumArgs = ParenList->getNumExprs();
2467 }
2468
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002469 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002470 // Initialize the object.
2471 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2472 QualType(ClassDecl->getTypeForDecl(), 0));
2473 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002474 InitList ? InitializationKind::CreateDirectList(NameLoc)
2475 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2476 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002477 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2478 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002479 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002480 0);
Sean Hunt41717662011-02-26 19:13:13 +00002481 if (DelegationInit.isInvalid())
2482 return true;
2483
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002484 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2485 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002486
Richard Smith41956372013-01-14 22:39:08 +00002487 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002488 // The initialization of each base and member constitutes a
2489 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002490 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2491 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002492 if (DelegationInit.isInvalid())
2493 return true;
2494
Eli Friedmand21016f2012-05-19 23:35:23 +00002495 // If we are in a dependent context, template instantiation will
2496 // perform this type-checking again. Just save the arguments that we
2497 // received in a ParenListExpr.
2498 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2499 // of the information that we have about the base
2500 // initializer. However, deconstructing the ASTs is a dicey process,
2501 // and this approach is far more likely to get the corner cases right.
2502 if (CurContext->isDependentContext())
2503 DelegationInit = Owned(Init);
2504
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002505 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002506 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002507 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002508}
2509
2510MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002511Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002512 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002513 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002514 SourceLocation BaseLoc
2515 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002516
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002517 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2518 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2519 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2520
2521 // C++ [class.base.init]p2:
2522 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002523 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002524 // of that class, the mem-initializer is ill-formed. A
2525 // mem-initializer-list can initialize a base class using any
2526 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002527 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002528
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002529 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002530 if (EllipsisLoc.isValid()) {
2531 // This is a pack expansion.
2532 if (!BaseType->containsUnexpandedParameterPack()) {
2533 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002534 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002535
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002536 EllipsisLoc = SourceLocation();
2537 }
2538 } else {
2539 // Check for any unexpanded parameter packs.
2540 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2541 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002542
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002544 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002545 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002546
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002547 // Check for direct and virtual base classes.
2548 const CXXBaseSpecifier *DirectBaseSpec = 0;
2549 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2550 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002551 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2552 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002553 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002554
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002555 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2556 VirtualBaseSpec);
2557
2558 // C++ [base.class.init]p2:
2559 // Unless the mem-initializer-id names a nonstatic data member of the
2560 // constructor's class or a direct or virtual base of that class, the
2561 // mem-initializer is ill-formed.
2562 if (!DirectBaseSpec && !VirtualBaseSpec) {
2563 // If the class has any dependent bases, then it's possible that
2564 // one of those types will resolve to the same type as
2565 // BaseType. Therefore, just treat this as a dependent base
2566 // class initialization. FIXME: Should we try to check the
2567 // initialization anyway? It seems odd.
2568 if (ClassDecl->hasAnyDependentBases())
2569 Dependent = true;
2570 else
2571 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2572 << BaseType << Context.getTypeDeclType(ClassDecl)
2573 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2574 }
2575 }
2576
2577 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002578 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Sebastian Redl6df65482011-09-24 17:48:25 +00002580 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2581 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002582 InitRange.getBegin(), Init,
2583 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002584 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002585
2586 // C++ [base.class.init]p2:
2587 // If a mem-initializer-id is ambiguous because it designates both
2588 // a direct non-virtual base class and an inherited virtual base
2589 // class, the mem-initializer is ill-formed.
2590 if (DirectBaseSpec && VirtualBaseSpec)
2591 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002592 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002593
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002594 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002595 if (!BaseSpec)
2596 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2597
2598 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002599 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002600 Expr **Args = &Init;
2601 unsigned NumArgs = 1;
2602 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002603 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002604 Args = ParenList->getExprs();
2605 NumArgs = ParenList->getNumExprs();
2606 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002607
2608 InitializedEntity BaseEntity =
2609 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2610 InitializationKind Kind =
2611 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2612 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2613 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002614 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2615 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002616 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002617 if (BaseInit.isInvalid())
2618 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002619
Richard Smith41956372013-01-14 22:39:08 +00002620 // C++11 [class.base.init]p7:
2621 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002622 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002623 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002624 if (BaseInit.isInvalid())
2625 return true;
2626
2627 // If we are in a dependent context, template instantiation will
2628 // perform this type-checking again. Just save the arguments that we
2629 // received in a ParenListExpr.
2630 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2631 // of the information that we have about the base
2632 // initializer. However, deconstructing the ASTs is a dicey process,
2633 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002634 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002635 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002636
Sean Huntcbb67482011-01-08 20:30:50 +00002637 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002638 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002639 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002640 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002641 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002642}
2643
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002644// Create a static_cast\<T&&>(expr).
2645static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2646 QualType ExprType = E->getType();
2647 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2648 SourceLocation ExprLoc = E->getLocStart();
2649 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2650 TargetType, ExprLoc);
2651
2652 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2653 SourceRange(ExprLoc, ExprLoc),
2654 E->getSourceRange()).take();
2655}
2656
Anders Carlssone5ef7402010-04-23 03:10:23 +00002657/// ImplicitInitializerKind - How an implicit base or member initializer should
2658/// initialize its base or member.
2659enum ImplicitInitializerKind {
2660 IIK_Default,
2661 IIK_Copy,
2662 IIK_Move
2663};
2664
Anders Carlssondefefd22010-04-23 02:00:02 +00002665static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002666BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002667 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002668 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002669 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002670 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002671 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002672 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2673 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002674
John McCall60d7b3a2010-08-24 06:29:42 +00002675 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002676
2677 switch (ImplicitInitKind) {
2678 case IIK_Default: {
2679 InitializationKind InitKind
2680 = InitializationKind::CreateDefault(Constructor->getLocation());
2681 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002682 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002683 break;
2684 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002685
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002686 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002687 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002688 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002689 ParmVarDecl *Param = Constructor->getParamDecl(0);
2690 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002691
Anders Carlssone5ef7402010-04-23 03:10:23 +00002692 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002693 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002694 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002695 Constructor->getLocation(), ParamType,
2696 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002697
Eli Friedman5f2987c2012-02-02 03:46:19 +00002698 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2699
Anders Carlssonc7957502010-04-24 22:02:54 +00002700 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002701 QualType ArgTy =
2702 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2703 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002704
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002705 if (Moving) {
2706 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2707 }
2708
John McCallf871d0c2010-08-07 06:22:56 +00002709 CXXCastPath BasePath;
2710 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002711 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2712 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002713 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002714 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002715
Anders Carlssone5ef7402010-04-23 03:10:23 +00002716 InitializationKind InitKind
2717 = InitializationKind::CreateDirect(Constructor->getLocation(),
2718 SourceLocation(), SourceLocation());
2719 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2720 &CopyCtorArg, 1);
2721 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002722 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002723 break;
2724 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002725 }
John McCall9ae2f072010-08-23 23:25:46 +00002726
Douglas Gregor53c374f2010-12-07 00:41:46 +00002727 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002728 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002729 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002730
Anders Carlssondefefd22010-04-23 02:00:02 +00002731 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002732 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002733 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2734 SourceLocation()),
2735 BaseSpec->isVirtual(),
2736 SourceLocation(),
2737 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002738 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002739 SourceLocation());
2740
Anders Carlssondefefd22010-04-23 02:00:02 +00002741 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002742}
2743
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002744static bool RefersToRValueRef(Expr *MemRef) {
2745 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2746 return Referenced->getType()->isRValueReferenceType();
2747}
2748
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002749static bool
2750BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002751 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002752 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002753 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002754 if (Field->isInvalidDecl())
2755 return true;
2756
Chandler Carruthf186b542010-06-29 23:50:44 +00002757 SourceLocation Loc = Constructor->getLocation();
2758
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002759 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2760 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002761 ParmVarDecl *Param = Constructor->getParamDecl(0);
2762 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002763
2764 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002765 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2766 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002767
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002768 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002769 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002770 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002771 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002772
Eli Friedman5f2987c2012-02-02 03:46:19 +00002773 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2774
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002775 if (Moving) {
2776 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2777 }
2778
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002779 // Build a reference to this field within the parameter.
2780 CXXScopeSpec SS;
2781 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2782 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002783 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2784 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002785 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002786 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002787 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002788 ParamType, Loc,
2789 /*IsArrow=*/false,
2790 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002791 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002792 /*FirstQualifierInScope=*/0,
2793 MemberLookup,
2794 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002795 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002796 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002797
2798 // C++11 [class.copy]p15:
2799 // - if a member m has rvalue reference type T&&, it is direct-initialized
2800 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002801 if (RefersToRValueRef(CtorArg.get())) {
2802 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002803 }
2804
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002805 // When the field we are copying is an array, create index variables for
2806 // each dimension of the array. We use these index variables to subscript
2807 // the source array, and other clients (e.g., CodeGen) will perform the
2808 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002809 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002810 QualType BaseType = Field->getType();
2811 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002812 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002813 while (const ConstantArrayType *Array
2814 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002815 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002816 // Create the iteration variable for this array index.
2817 IdentifierInfo *IterationVarName = 0;
2818 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002819 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002820 llvm::raw_svector_ostream OS(Str);
2821 OS << "__i" << IndexVariables.size();
2822 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2823 }
2824 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002825 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002826 IterationVarName, SizeType,
2827 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002828 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002829 IndexVariables.push_back(IterationVar);
2830
2831 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002832 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002833 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002834 assert(!IterationVarRef.isInvalid() &&
2835 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002836 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2837 assert(!IterationVarRef.isInvalid() &&
2838 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002839
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002840 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002841 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002842 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002843 Loc);
2844 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002845 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002846
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002847 BaseType = Array->getElementType();
2848 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002849
2850 // The array subscript expression is an lvalue, which is wrong for moving.
2851 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002852 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002853
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002854 // Construct the entity that we will be initializing. For an array, this
2855 // will be first element in the array, which may require several levels
2856 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002857 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002858 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002859 if (Indirect)
2860 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2861 else
2862 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002863 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2864 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2865 0,
2866 Entities.back()));
2867
2868 // Direct-initialize to use the copy constructor.
2869 InitializationKind InitKind =
2870 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2871
Sebastian Redl74e611a2011-09-04 18:14:28 +00002872 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002873 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002874 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002875
John McCall60d7b3a2010-08-24 06:29:42 +00002876 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002877 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002878 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002879 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002880 if (MemberInit.isInvalid())
2881 return true;
2882
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002883 if (Indirect) {
2884 assert(IndexVariables.size() == 0 &&
2885 "Indirect field improperly initialized");
2886 CXXMemberInit
2887 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2888 Loc, Loc,
2889 MemberInit.takeAs<Expr>(),
2890 Loc);
2891 } else
2892 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2893 Loc, MemberInit.takeAs<Expr>(),
2894 Loc,
2895 IndexVariables.data(),
2896 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002897 return false;
2898 }
2899
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002900 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2901
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002902 QualType FieldBaseElementType =
2903 SemaRef.Context.getBaseElementType(Field->getType());
2904
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002905 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002906 InitializedEntity InitEntity
2907 = Indirect? InitializedEntity::InitializeMember(Indirect)
2908 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002909 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002910 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002911
2912 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002913 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002914 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002915
Douglas Gregor53c374f2010-12-07 00:41:46 +00002916 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002917 if (MemberInit.isInvalid())
2918 return true;
2919
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002920 if (Indirect)
2921 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2922 Indirect, Loc,
2923 Loc,
2924 MemberInit.get(),
2925 Loc);
2926 else
2927 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2928 Field, Loc, Loc,
2929 MemberInit.get(),
2930 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002931 return false;
2932 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002933
Sean Hunt1f2f3842011-05-17 00:19:05 +00002934 if (!Field->getParent()->isUnion()) {
2935 if (FieldBaseElementType->isReferenceType()) {
2936 SemaRef.Diag(Constructor->getLocation(),
2937 diag::err_uninitialized_member_in_ctor)
2938 << (int)Constructor->isImplicit()
2939 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2940 << 0 << Field->getDeclName();
2941 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2942 return true;
2943 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002944
Sean Hunt1f2f3842011-05-17 00:19:05 +00002945 if (FieldBaseElementType.isConstQualified()) {
2946 SemaRef.Diag(Constructor->getLocation(),
2947 diag::err_uninitialized_member_in_ctor)
2948 << (int)Constructor->isImplicit()
2949 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2950 << 1 << Field->getDeclName();
2951 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2952 return true;
2953 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002954 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002955
David Blaikie4e4d0842012-03-11 07:00:24 +00002956 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002957 FieldBaseElementType->isObjCRetainableType() &&
2958 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2959 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002960 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002961 // Default-initialize Objective-C pointers to NULL.
2962 CXXMemberInit
2963 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2964 Loc, Loc,
2965 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2966 Loc);
2967 return false;
2968 }
2969
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002970 // Nothing to initialize.
2971 CXXMemberInit = 0;
2972 return false;
2973}
John McCallf1860e52010-05-20 23:23:51 +00002974
2975namespace {
2976struct BaseAndFieldInfo {
2977 Sema &S;
2978 CXXConstructorDecl *Ctor;
2979 bool AnyErrorsInInits;
2980 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002981 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002982 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002983
2984 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2985 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002986 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2987 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002988 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002989 else if (Generated && Ctor->isMoveConstructor())
2990 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002991 else
2992 IIK = IIK_Default;
2993 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002994
2995 bool isImplicitCopyOrMove() const {
2996 switch (IIK) {
2997 case IIK_Copy:
2998 case IIK_Move:
2999 return true;
3000
3001 case IIK_Default:
3002 return false;
3003 }
David Blaikie30263482012-01-20 21:50:17 +00003004
3005 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003006 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003007
3008 bool addFieldInitializer(CXXCtorInitializer *Init) {
3009 AllToInit.push_back(Init);
3010
3011 // Check whether this initializer makes the field "used".
3012 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3013 S.UnusedPrivateFields.remove(Init->getAnyMember());
3014
3015 return false;
3016 }
John McCallf1860e52010-05-20 23:23:51 +00003017};
3018}
3019
Richard Smitha4950662011-09-19 13:34:43 +00003020/// \brief Determine whether the given indirect field declaration is somewhere
3021/// within an anonymous union.
3022static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3023 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3024 CEnd = F->chain_end();
3025 C != CEnd; ++C)
3026 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3027 if (Record->isUnion())
3028 return true;
3029
3030 return false;
3031}
3032
Douglas Gregorddb21472011-11-02 23:04:16 +00003033/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3034/// array type.
3035static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3036 if (T->isIncompleteArrayType())
3037 return true;
3038
3039 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3040 if (!ArrayT->getSize())
3041 return true;
3042
3043 T = ArrayT->getElementType();
3044 }
3045
3046 return false;
3047}
3048
Richard Smith7a614d82011-06-11 17:19:42 +00003049static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003050 FieldDecl *Field,
3051 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003052
Chandler Carruthe861c602010-06-30 02:59:29 +00003053 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003054 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3055 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003056
Richard Smith0b8220a2012-08-07 21:30:42 +00003057 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003058 // has a brace-or-equal-initializer, the entity is initialized as specified
3059 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003060 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003061 CXXCtorInitializer *Init;
3062 if (Indirect)
3063 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3064 SourceLocation(),
3065 SourceLocation(), 0,
3066 SourceLocation());
3067 else
3068 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3069 SourceLocation(),
3070 SourceLocation(), 0,
3071 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003072 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003073 }
3074
Richard Smithc115f632011-09-18 11:14:50 +00003075 // Don't build an implicit initializer for union members if none was
3076 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003077 if (Field->getParent()->isUnion() ||
3078 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003079 return false;
3080
Douglas Gregorddb21472011-11-02 23:04:16 +00003081 // Don't initialize incomplete or zero-length arrays.
3082 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3083 return false;
3084
John McCallf1860e52010-05-20 23:23:51 +00003085 // Don't try to build an implicit initializer if there were semantic
3086 // errors in any of the initializers (and therefore we might be
3087 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003088 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003089 return false;
3090
Sean Huntcbb67482011-01-08 20:30:50 +00003091 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003092 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3093 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003094 return true;
John McCallf1860e52010-05-20 23:23:51 +00003095
Richard Smith0b8220a2012-08-07 21:30:42 +00003096 if (!Init)
3097 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003098
Richard Smith0b8220a2012-08-07 21:30:42 +00003099 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003100}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003101
3102bool
3103Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3104 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003105 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003106 Constructor->setNumCtorInitializers(1);
3107 CXXCtorInitializer **initializer =
3108 new (Context) CXXCtorInitializer*[1];
3109 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3110 Constructor->setCtorInitializers(initializer);
3111
Sean Huntb76af9c2011-05-03 23:05:34 +00003112 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003113 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003114 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3115 }
3116
Sean Huntc1598702011-05-05 00:05:47 +00003117 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003118
Sean Hunt059ce0d2011-05-01 07:04:31 +00003119 return false;
3120}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003121
David Blaikie93c86172013-01-17 05:26:25 +00003122bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3123 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003124 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003125 // Just store the initializers as written, they will be checked during
3126 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003127 if (!Initializers.empty()) {
3128 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003129 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003130 new (Context) CXXCtorInitializer*[Initializers.size()];
3131 memcpy(baseOrMemberInitializers, Initializers.data(),
3132 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003133 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003134 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003135
3136 // Let template instantiation know whether we had errors.
3137 if (AnyErrors)
3138 Constructor->setInvalidDecl();
3139
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003140 return false;
3141 }
3142
John McCallf1860e52010-05-20 23:23:51 +00003143 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003144
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003145 // We need to build the initializer AST according to order of construction
3146 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003147 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003148 if (!ClassDecl)
3149 return true;
3150
Eli Friedman80c30da2009-11-09 19:20:36 +00003151 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003152
David Blaikie93c86172013-01-17 05:26:25 +00003153 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003154 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003155
3156 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003157 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003158 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003159 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003160 }
3161
Anders Carlsson711f34a2010-04-21 19:52:01 +00003162 // Keep track of the direct virtual bases.
3163 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3164 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3165 E = ClassDecl->bases_end(); I != E; ++I) {
3166 if (I->isVirtual())
3167 DirectVBases.insert(I);
3168 }
3169
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003170 // Push virtual bases before others.
3171 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3172 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3173
Sean Huntcbb67482011-01-08 20:30:50 +00003174 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003175 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3176 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003177 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003178 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003179 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003180 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003181 VBase, IsInheritedVirtualBase,
3182 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003183 HadError = true;
3184 continue;
3185 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003186
John McCallf1860e52010-05-20 23:23:51 +00003187 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003188 }
3189 }
Mike Stump1eb44332009-09-09 15:08:12 +00003190
John McCallf1860e52010-05-20 23:23:51 +00003191 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003192 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3193 E = ClassDecl->bases_end(); Base != E; ++Base) {
3194 // Virtuals are in the virtual base list and already constructed.
3195 if (Base->isVirtual())
3196 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003197
Sean Huntcbb67482011-01-08 20:30:50 +00003198 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003199 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3200 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003201 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003202 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003203 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003204 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003205 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003206 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003207 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003208 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003209
John McCallf1860e52010-05-20 23:23:51 +00003210 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003211 }
3212 }
Mike Stump1eb44332009-09-09 15:08:12 +00003213
John McCallf1860e52010-05-20 23:23:51 +00003214 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003215 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3216 MemEnd = ClassDecl->decls_end();
3217 Mem != MemEnd; ++Mem) {
3218 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003219 // C++ [class.bit]p2:
3220 // A declaration for a bit-field that omits the identifier declares an
3221 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3222 // initialized.
3223 if (F->isUnnamedBitfield())
3224 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003225
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003226 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003227 // handle anonymous struct/union fields based on their individual
3228 // indirect fields.
3229 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3230 continue;
3231
3232 if (CollectFieldInitializer(*this, Info, F))
3233 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003234 continue;
3235 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003236
3237 // Beyond this point, we only consider default initialization.
3238 if (Info.IIK != IIK_Default)
3239 continue;
3240
3241 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3242 if (F->getType()->isIncompleteArrayType()) {
3243 assert(ClassDecl->hasFlexibleArrayMember() &&
3244 "Incomplete array type is not valid");
3245 continue;
3246 }
3247
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003248 // Initialize each field of an anonymous struct individually.
3249 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3250 HadError = true;
3251
3252 continue;
3253 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003254 }
Mike Stump1eb44332009-09-09 15:08:12 +00003255
David Blaikie93c86172013-01-17 05:26:25 +00003256 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003257 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003258 Constructor->setNumCtorInitializers(NumInitializers);
3259 CXXCtorInitializer **baseOrMemberInitializers =
3260 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003261 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003262 NumInitializers * sizeof(CXXCtorInitializer*));
3263 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003264
John McCallef027fe2010-03-16 21:39:52 +00003265 // Constructors implicitly reference the base and member
3266 // destructors.
3267 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3268 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003269 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003270
3271 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003272}
3273
David Blaikieee000bb2013-01-17 08:49:22 +00003274static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003275 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003276 const RecordDecl *RD = RT->getDecl();
3277 if (RD->isAnonymousStructOrUnion()) {
3278 for (RecordDecl::field_iterator Field = RD->field_begin(),
3279 E = RD->field_end(); Field != E; ++Field)
3280 PopulateKeysForFields(*Field, IdealInits);
3281 return;
3282 }
Eli Friedman6347f422009-07-21 19:28:10 +00003283 }
David Blaikieee000bb2013-01-17 08:49:22 +00003284 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003285}
3286
Anders Carlssonea356fb2010-04-02 05:42:15 +00003287static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003288 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003289}
3290
Anders Carlssonea356fb2010-04-02 05:42:15 +00003291static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003292 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003293 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003294 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003295
David Blaikieee000bb2013-01-17 08:49:22 +00003296 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003297}
3298
David Blaikie93c86172013-01-17 05:26:25 +00003299static void DiagnoseBaseOrMemInitializerOrder(
3300 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3301 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003302 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003303 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003304
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003305 // Don't check initializers order unless the warning is enabled at the
3306 // location of at least one initializer.
3307 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003308 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003309 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003310 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3311 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003312 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003313 ShouldCheckOrder = true;
3314 break;
3315 }
3316 }
3317 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003318 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003319
John McCalld6ca8da2010-04-10 07:37:23 +00003320 // Build the list of bases and members in the order that they'll
3321 // actually be initialized. The explicit initializers should be in
3322 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003323 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Anders Carlsson071d6102010-04-02 03:38:04 +00003325 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3326
John McCalld6ca8da2010-04-10 07:37:23 +00003327 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003328 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003329 ClassDecl->vbases_begin(),
3330 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003331 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003332
John McCalld6ca8da2010-04-10 07:37:23 +00003333 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003334 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003335 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003336 if (Base->isVirtual())
3337 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003338 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003339 }
Mike Stump1eb44332009-09-09 15:08:12 +00003340
John McCalld6ca8da2010-04-10 07:37:23 +00003341 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003342 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003343 E = ClassDecl->field_end(); Field != E; ++Field) {
3344 if (Field->isUnnamedBitfield())
3345 continue;
3346
David Blaikieee000bb2013-01-17 08:49:22 +00003347 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003348 }
3349
John McCalld6ca8da2010-04-10 07:37:23 +00003350 unsigned NumIdealInits = IdealInitKeys.size();
3351 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003352
Sean Huntcbb67482011-01-08 20:30:50 +00003353 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003354 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003355 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003356 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003357
3358 // Scan forward to try to find this initializer in the idealized
3359 // initializers list.
3360 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3361 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003362 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003363
3364 // If we didn't find this initializer, it must be because we
3365 // scanned past it on a previous iteration. That can only
3366 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003367 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003368 Sema::SemaDiagnosticBuilder D =
3369 SemaRef.Diag(PrevInit->getSourceLocation(),
3370 diag::warn_initializer_out_of_order);
3371
Francois Pichet00eb3f92010-12-04 09:14:42 +00003372 if (PrevInit->isAnyMemberInitializer())
3373 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003374 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003375 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003376
Francois Pichet00eb3f92010-12-04 09:14:42 +00003377 if (Init->isAnyMemberInitializer())
3378 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003379 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003380 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003381
3382 // Move back to the initializer's location in the ideal list.
3383 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3384 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003385 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003386
3387 assert(IdealIndex != NumIdealInits &&
3388 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003389 }
John McCalld6ca8da2010-04-10 07:37:23 +00003390
3391 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003392 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003393}
3394
John McCall3c3ccdb2010-04-10 09:28:51 +00003395namespace {
3396bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003397 CXXCtorInitializer *Init,
3398 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003399 if (!PrevInit) {
3400 PrevInit = Init;
3401 return false;
3402 }
3403
3404 if (FieldDecl *Field = Init->getMember())
3405 S.Diag(Init->getSourceLocation(),
3406 diag::err_multiple_mem_initialization)
3407 << Field->getDeclName()
3408 << Init->getSourceRange();
3409 else {
John McCallf4c73712011-01-19 06:33:43 +00003410 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003411 assert(BaseClass && "neither field nor base");
3412 S.Diag(Init->getSourceLocation(),
3413 diag::err_multiple_base_initialization)
3414 << QualType(BaseClass, 0)
3415 << Init->getSourceRange();
3416 }
3417 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3418 << 0 << PrevInit->getSourceRange();
3419
3420 return true;
3421}
3422
Sean Huntcbb67482011-01-08 20:30:50 +00003423typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003424typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3425
3426bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003427 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003428 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003429 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003430 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003431 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003432
3433 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003434 if (Parent->isUnion()) {
3435 UnionEntry &En = Unions[Parent];
3436 if (En.first && En.first != Child) {
3437 S.Diag(Init->getSourceLocation(),
3438 diag::err_multiple_mem_union_initialization)
3439 << Field->getDeclName()
3440 << Init->getSourceRange();
3441 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3442 << 0 << En.second->getSourceRange();
3443 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003444 }
3445 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003446 En.first = Child;
3447 En.second = Init;
3448 }
David Blaikie6fe29652011-11-17 06:01:57 +00003449 if (!Parent->isAnonymousStructOrUnion())
3450 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003451 }
3452
3453 Child = Parent;
3454 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003455 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003456
3457 return false;
3458}
3459}
3460
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003461/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003462void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003463 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003464 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003465 bool AnyErrors) {
3466 if (!ConstructorDecl)
3467 return;
3468
3469 AdjustDeclIfTemplate(ConstructorDecl);
3470
3471 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003472 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003473
3474 if (!Constructor) {
3475 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3476 return;
3477 }
3478
John McCall3c3ccdb2010-04-10 09:28:51 +00003479 // Mapping for the duplicate initializers check.
3480 // For member initializers, this is keyed with a FieldDecl*.
3481 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003482 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003483
3484 // Mapping for the inconsistent anonymous-union initializers check.
3485 RedundantUnionMap MemberUnions;
3486
Anders Carlssonea356fb2010-04-02 05:42:15 +00003487 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003488 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003489 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003490
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003491 // Set the source order index.
3492 Init->setSourceOrder(i);
3493
Francois Pichet00eb3f92010-12-04 09:14:42 +00003494 if (Init->isAnyMemberInitializer()) {
3495 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003496 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3497 CheckRedundantUnionInit(*this, Init, MemberUnions))
3498 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003499 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003500 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3501 if (CheckRedundantInit(*this, Init, Members[Key]))
3502 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003503 } else {
3504 assert(Init->isDelegatingInitializer());
3505 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003506 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003507 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003508 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003509 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003510 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003511 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003512 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003513 // Return immediately as the initializer is set.
3514 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003515 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003516 }
3517
Anders Carlssonea356fb2010-04-02 05:42:15 +00003518 if (HadError)
3519 return;
3520
David Blaikie93c86172013-01-17 05:26:25 +00003521 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003522
David Blaikie93c86172013-01-17 05:26:25 +00003523 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003524}
3525
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003526void
John McCallef027fe2010-03-16 21:39:52 +00003527Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3528 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003529 // Ignore dependent contexts. Also ignore unions, since their members never
3530 // have destructors implicitly called.
3531 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003532 return;
John McCall58e6f342010-03-16 05:22:47 +00003533
3534 // FIXME: all the access-control diagnostics are positioned on the
3535 // field/base declaration. That's probably good; that said, the
3536 // user might reasonably want to know why the destructor is being
3537 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003538
Anders Carlsson9f853df2009-11-17 04:44:12 +00003539 // Non-static data members.
3540 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3541 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003542 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003543 if (Field->isInvalidDecl())
3544 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003545
3546 // Don't destroy incomplete or zero-length arrays.
3547 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3548 continue;
3549
Anders Carlsson9f853df2009-11-17 04:44:12 +00003550 QualType FieldType = Context.getBaseElementType(Field->getType());
3551
3552 const RecordType* RT = FieldType->getAs<RecordType>();
3553 if (!RT)
3554 continue;
3555
3556 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003557 if (FieldClassDecl->isInvalidDecl())
3558 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003559 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003560 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003561 // The destructor for an implicit anonymous union member is never invoked.
3562 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3563 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003564
Douglas Gregordb89f282010-07-01 22:47:18 +00003565 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003566 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003567 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003568 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003569 << Field->getDeclName()
3570 << FieldType);
3571
Eli Friedman5f2987c2012-02-02 03:46:19 +00003572 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003573 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003574 }
3575
John McCall58e6f342010-03-16 05:22:47 +00003576 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3577
Anders Carlsson9f853df2009-11-17 04:44:12 +00003578 // Bases.
3579 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3580 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003581 // Bases are always records in a well-formed non-dependent class.
3582 const RecordType *RT = Base->getType()->getAs<RecordType>();
3583
3584 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003585 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003586 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003587
John McCall58e6f342010-03-16 05:22:47 +00003588 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003589 // If our base class is invalid, we probably can't get its dtor anyway.
3590 if (BaseClassDecl->isInvalidDecl())
3591 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003592 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003593 continue;
John McCall58e6f342010-03-16 05:22:47 +00003594
Douglas Gregordb89f282010-07-01 22:47:18 +00003595 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003596 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003597
3598 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003599 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003600 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003601 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003602 << Base->getSourceRange(),
3603 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003604
Eli Friedman5f2987c2012-02-02 03:46:19 +00003605 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003606 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003607 }
3608
3609 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003610 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3611 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003612
3613 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003614 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003615
3616 // Ignore direct virtual bases.
3617 if (DirectVirtualBases.count(RT))
3618 continue;
3619
John McCall58e6f342010-03-16 05:22:47 +00003620 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003621 // If our base class is invalid, we probably can't get its dtor anyway.
3622 if (BaseClassDecl->isInvalidDecl())
3623 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003624 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003625 continue;
John McCall58e6f342010-03-16 05:22:47 +00003626
Douglas Gregordb89f282010-07-01 22:47:18 +00003627 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003628 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003629 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003630 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003631 << VBase->getType(),
3632 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003633
Eli Friedman5f2987c2012-02-02 03:46:19 +00003634 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003635 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003636 }
3637}
3638
John McCalld226f652010-08-21 09:40:31 +00003639void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003640 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003641 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003642
Mike Stump1eb44332009-09-09 15:08:12 +00003643 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003644 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003645 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003646}
3647
Mike Stump1eb44332009-09-09 15:08:12 +00003648bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003649 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003650 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3651 unsigned DiagID;
3652 AbstractDiagSelID SelID;
3653
3654 public:
3655 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3656 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3657
3658 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003659 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003660 if (SelID == -1)
3661 S.Diag(Loc, DiagID) << T;
3662 else
3663 S.Diag(Loc, DiagID) << SelID << T;
3664 }
3665 } Diagnoser(DiagID, SelID);
3666
3667 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003668}
3669
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003670bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003671 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003672 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003673 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Anders Carlsson11f21a02009-03-23 19:10:31 +00003675 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003676 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003677
Ted Kremenek6217b802009-07-29 21:53:49 +00003678 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003679 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003680 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003681 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003683 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003684 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003685 }
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Ted Kremenek6217b802009-07-29 21:53:49 +00003687 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003688 if (!RT)
3689 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003690
John McCall86ff3082010-02-04 22:26:26 +00003691 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003692
John McCall94c3b562010-08-18 09:41:07 +00003693 // We can't answer whether something is abstract until it has a
3694 // definition. If it's currently being defined, we'll walk back
3695 // over all the declarations when we have a full definition.
3696 const CXXRecordDecl *Def = RD->getDefinition();
3697 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003698 return false;
3699
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003700 if (!RD->isAbstract())
3701 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003703 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003704 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003705
John McCall94c3b562010-08-18 09:41:07 +00003706 return true;
3707}
3708
3709void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3710 // Check if we've already emitted the list of pure virtual functions
3711 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003712 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003713 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003715 CXXFinalOverriderMap FinalOverriders;
3716 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003718 // Keep a set of seen pure methods so we won't diagnose the same method
3719 // more than once.
3720 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3721
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003722 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3723 MEnd = FinalOverriders.end();
3724 M != MEnd;
3725 ++M) {
3726 for (OverridingMethods::iterator SO = M->second.begin(),
3727 SOEnd = M->second.end();
3728 SO != SOEnd; ++SO) {
3729 // C++ [class.abstract]p4:
3730 // A class is abstract if it contains or inherits at least one
3731 // pure virtual function for which the final overrider is pure
3732 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003734 //
3735 if (SO->second.size() != 1)
3736 continue;
3737
3738 if (!SO->second.front().Method->isPure())
3739 continue;
3740
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003741 if (!SeenPureMethods.insert(SO->second.front().Method))
3742 continue;
3743
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003744 Diag(SO->second.front().Method->getLocation(),
3745 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003746 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003747 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003748 }
3749
3750 if (!PureVirtualClassDiagSet)
3751 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3752 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003753}
3754
Anders Carlsson8211eff2009-03-24 01:19:16 +00003755namespace {
John McCall94c3b562010-08-18 09:41:07 +00003756struct AbstractUsageInfo {
3757 Sema &S;
3758 CXXRecordDecl *Record;
3759 CanQualType AbstractType;
3760 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003761
John McCall94c3b562010-08-18 09:41:07 +00003762 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3763 : S(S), Record(Record),
3764 AbstractType(S.Context.getCanonicalType(
3765 S.Context.getTypeDeclType(Record))),
3766 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003767
John McCall94c3b562010-08-18 09:41:07 +00003768 void DiagnoseAbstractType() {
3769 if (Invalid) return;
3770 S.DiagnoseAbstractType(Record);
3771 Invalid = true;
3772 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003773
John McCall94c3b562010-08-18 09:41:07 +00003774 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3775};
3776
3777struct CheckAbstractUsage {
3778 AbstractUsageInfo &Info;
3779 const NamedDecl *Ctx;
3780
3781 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3782 : Info(Info), Ctx(Ctx) {}
3783
3784 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3785 switch (TL.getTypeLocClass()) {
3786#define ABSTRACT_TYPELOC(CLASS, PARENT)
3787#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00003788 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00003789#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003790 }
John McCall94c3b562010-08-18 09:41:07 +00003791 }
Mike Stump1eb44332009-09-09 15:08:12 +00003792
John McCall94c3b562010-08-18 09:41:07 +00003793 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3794 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3795 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003796 if (!TL.getArg(I))
3797 continue;
3798
John McCall94c3b562010-08-18 09:41:07 +00003799 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3800 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003801 }
John McCall94c3b562010-08-18 09:41:07 +00003802 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003803
John McCall94c3b562010-08-18 09:41:07 +00003804 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3805 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3806 }
Mike Stump1eb44332009-09-09 15:08:12 +00003807
John McCall94c3b562010-08-18 09:41:07 +00003808 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3809 // Visit the type parameters from a permissive context.
3810 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3811 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3812 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3813 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3814 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3815 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003816 }
John McCall94c3b562010-08-18 09:41:07 +00003817 }
Mike Stump1eb44332009-09-09 15:08:12 +00003818
John McCall94c3b562010-08-18 09:41:07 +00003819 // Visit pointee types from a permissive context.
3820#define CheckPolymorphic(Type) \
3821 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3822 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3823 }
3824 CheckPolymorphic(PointerTypeLoc)
3825 CheckPolymorphic(ReferenceTypeLoc)
3826 CheckPolymorphic(MemberPointerTypeLoc)
3827 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003828 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003829
John McCall94c3b562010-08-18 09:41:07 +00003830 /// Handle all the types we haven't given a more specific
3831 /// implementation for above.
3832 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3833 // Every other kind of type that we haven't called out already
3834 // that has an inner type is either (1) sugar or (2) contains that
3835 // inner type in some way as a subobject.
3836 if (TypeLoc Next = TL.getNextTypeLoc())
3837 return Visit(Next, Sel);
3838
3839 // If there's no inner type and we're in a permissive context,
3840 // don't diagnose.
3841 if (Sel == Sema::AbstractNone) return;
3842
3843 // Check whether the type matches the abstract type.
3844 QualType T = TL.getType();
3845 if (T->isArrayType()) {
3846 Sel = Sema::AbstractArrayType;
3847 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003848 }
John McCall94c3b562010-08-18 09:41:07 +00003849 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3850 if (CT != Info.AbstractType) return;
3851
3852 // It matched; do some magic.
3853 if (Sel == Sema::AbstractArrayType) {
3854 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3855 << T << TL.getSourceRange();
3856 } else {
3857 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3858 << Sel << T << TL.getSourceRange();
3859 }
3860 Info.DiagnoseAbstractType();
3861 }
3862};
3863
3864void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3865 Sema::AbstractDiagSelID Sel) {
3866 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3867}
3868
3869}
3870
3871/// Check for invalid uses of an abstract type in a method declaration.
3872static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3873 CXXMethodDecl *MD) {
3874 // No need to do the check on definitions, which require that
3875 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003876 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003877 return;
3878
3879 // For safety's sake, just ignore it if we don't have type source
3880 // information. This should never happen for non-implicit methods,
3881 // but...
3882 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3883 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3884}
3885
3886/// Check for invalid uses of an abstract type within a class definition.
3887static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3888 CXXRecordDecl *RD) {
3889 for (CXXRecordDecl::decl_iterator
3890 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3891 Decl *D = *I;
3892 if (D->isImplicit()) continue;
3893
3894 // Methods and method templates.
3895 if (isa<CXXMethodDecl>(D)) {
3896 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3897 } else if (isa<FunctionTemplateDecl>(D)) {
3898 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3899 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3900
3901 // Fields and static variables.
3902 } else if (isa<FieldDecl>(D)) {
3903 FieldDecl *FD = cast<FieldDecl>(D);
3904 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3905 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3906 } else if (isa<VarDecl>(D)) {
3907 VarDecl *VD = cast<VarDecl>(D);
3908 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3909 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3910
3911 // Nested classes and class templates.
3912 } else if (isa<CXXRecordDecl>(D)) {
3913 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3914 } else if (isa<ClassTemplateDecl>(D)) {
3915 CheckAbstractClassUsage(Info,
3916 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3917 }
3918 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003919}
3920
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003921/// \brief Perform semantic checks on a class definition that has been
3922/// completing, introducing implicitly-declared members, checking for
3923/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003924void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003925 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003926 return;
3927
John McCall94c3b562010-08-18 09:41:07 +00003928 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3929 AbstractUsageInfo Info(*this, Record);
3930 CheckAbstractClassUsage(Info, Record);
3931 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003932
3933 // If this is not an aggregate type and has no user-declared constructor,
3934 // complain about any non-static data members of reference or const scalar
3935 // type, since they will never get initializers.
3936 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003937 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3938 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003939 bool Complained = false;
3940 for (RecordDecl::field_iterator F = Record->field_begin(),
3941 FEnd = Record->field_end();
3942 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003943 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003944 continue;
3945
Douglas Gregor325e5932010-04-15 00:00:53 +00003946 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003947 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003948 if (!Complained) {
3949 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3950 << Record->getTagKind() << Record;
3951 Complained = true;
3952 }
3953
3954 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3955 << F->getType()->isReferenceType()
3956 << F->getDeclName();
3957 }
3958 }
3959 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003960
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003961 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003962 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003963
3964 if (Record->getIdentifier()) {
3965 // C++ [class.mem]p13:
3966 // If T is the name of a class, then each of the following shall have a
3967 // name different from T:
3968 // - every member of every anonymous union that is a member of class T.
3969 //
3970 // C++ [class.mem]p14:
3971 // In addition, if class T has a user-declared constructor (12.1), every
3972 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00003973 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3974 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3975 ++I) {
3976 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00003977 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3978 isa<IndirectFieldDecl>(D)) {
3979 Diag(D->getLocation(), diag::err_member_name_of_class)
3980 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003981 break;
3982 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003983 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003984 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003985
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003986 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003987 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003988 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003989 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003990 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3991 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3992 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003993
David Blaikieb6b5b972012-09-21 03:21:07 +00003994 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3995 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3996 DiagnoseAbstractType(Record);
3997 }
3998
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003999 if (!Record->isDependentType()) {
4000 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4001 MEnd = Record->method_end();
4002 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004003 // See if a method overloads virtual methods in a base
4004 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004005 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004006 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004007
4008 // Check whether the explicitly-defaulted special members are valid.
4009 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4010 CheckExplicitlyDefaultedSpecialMember(*M);
4011
4012 // For an explicitly defaulted or deleted special member, we defer
4013 // determining triviality until the class is complete. That time is now!
4014 if (!M->isImplicit() && !M->isUserProvided()) {
4015 CXXSpecialMember CSM = getSpecialMember(*M);
4016 if (CSM != CXXInvalid) {
4017 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4018
4019 // Inform the class that we've finished declaring this member.
4020 Record->finishedDefaultedOrDeletedMember(*M);
4021 }
4022 }
4023 }
4024 }
4025
4026 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4027 // function that is not a constructor declares that member function to be
4028 // const. [...] The class of which that function is a member shall be
4029 // a literal type.
4030 //
4031 // If the class has virtual bases, any constexpr members will already have
4032 // been diagnosed by the checks performed on the member declaration, so
4033 // suppress this (less useful) diagnostic.
4034 //
4035 // We delay this until we know whether an explicitly-defaulted (or deleted)
4036 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004037 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004038 !Record->isLiteral() && !Record->getNumVBases()) {
4039 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4040 MEnd = Record->method_end();
4041 M != MEnd; ++M) {
4042 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4043 switch (Record->getTemplateSpecializationKind()) {
4044 case TSK_ImplicitInstantiation:
4045 case TSK_ExplicitInstantiationDeclaration:
4046 case TSK_ExplicitInstantiationDefinition:
4047 // If a template instantiates to a non-literal type, but its members
4048 // instantiate to constexpr functions, the template is technically
4049 // ill-formed, but we allow it for sanity.
4050 continue;
4051
4052 case TSK_Undeclared:
4053 case TSK_ExplicitSpecialization:
4054 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4055 diag::err_constexpr_method_non_literal);
4056 break;
4057 }
4058
4059 // Only produce one error per class.
4060 break;
4061 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004062 }
4063 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004064
4065 // Declare inherited constructors. We do this eagerly here because:
4066 // - The standard requires an eager diagnostic for conflicting inherited
4067 // constructors from different classes.
4068 // - The lazy declaration of the other implicit constructors is so as to not
4069 // waste space and performance on classes that are not meant to be
4070 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4071 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004072 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004073}
4074
Richard Smith7756afa2012-06-10 05:43:50 +00004075/// Is the special member function which would be selected to perform the
4076/// specified operation on the specified class type a constexpr constructor?
4077static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4078 Sema::CXXSpecialMember CSM,
4079 bool ConstArg) {
4080 Sema::SpecialMemberOverloadResult *SMOR =
4081 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4082 false, false, false, false);
4083 if (!SMOR || !SMOR->getMethod())
4084 // A constructor we wouldn't select can't be "involved in initializing"
4085 // anything.
4086 return true;
4087 return SMOR->getMethod()->isConstexpr();
4088}
4089
4090/// Determine whether the specified special member function would be constexpr
4091/// if it were implicitly defined.
4092static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4093 Sema::CXXSpecialMember CSM,
4094 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004095 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004096 return false;
4097
4098 // C++11 [dcl.constexpr]p4:
4099 // In the definition of a constexpr constructor [...]
4100 switch (CSM) {
4101 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004102 // Since default constructor lookup is essentially trivial (and cannot
4103 // involve, for instance, template instantiation), we compute whether a
4104 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4105 //
4106 // This is important for performance; we need to know whether the default
4107 // constructor is constexpr to determine whether the type is a literal type.
4108 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4109
Richard Smith7756afa2012-06-10 05:43:50 +00004110 case Sema::CXXCopyConstructor:
4111 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004112 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004113 break;
4114
4115 case Sema::CXXCopyAssignment:
4116 case Sema::CXXMoveAssignment:
4117 case Sema::CXXDestructor:
4118 case Sema::CXXInvalid:
4119 return false;
4120 }
4121
4122 // -- if the class is a non-empty union, or for each non-empty anonymous
4123 // union member of a non-union class, exactly one non-static data member
4124 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004125 //
4126 // If we squint, this is guaranteed, since exactly one non-static data member
4127 // will be initialized (if the constructor isn't deleted), we just don't know
4128 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004129 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004130 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004131
4132 // -- the class shall not have any virtual base classes;
4133 if (ClassDecl->getNumVBases())
4134 return false;
4135
4136 // -- every constructor involved in initializing [...] base class
4137 // sub-objects shall be a constexpr constructor;
4138 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4139 BEnd = ClassDecl->bases_end();
4140 B != BEnd; ++B) {
4141 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4142 if (!BaseType) continue;
4143
4144 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4145 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4146 return false;
4147 }
4148
4149 // -- every constructor involved in initializing non-static data members
4150 // [...] shall be a constexpr constructor;
4151 // -- every non-static data member and base class sub-object shall be
4152 // initialized
4153 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4154 FEnd = ClassDecl->field_end();
4155 F != FEnd; ++F) {
4156 if (F->isInvalidDecl())
4157 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004158 if (const RecordType *RecordTy =
4159 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004160 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4161 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4162 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004163 }
4164 }
4165
4166 // All OK, it's constexpr!
4167 return true;
4168}
4169
Richard Smithb9d0b762012-07-27 04:22:15 +00004170static Sema::ImplicitExceptionSpecification
4171computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4172 switch (S.getSpecialMember(MD)) {
4173 case Sema::CXXDefaultConstructor:
4174 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4175 case Sema::CXXCopyConstructor:
4176 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4177 case Sema::CXXCopyAssignment:
4178 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4179 case Sema::CXXMoveConstructor:
4180 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4181 case Sema::CXXMoveAssignment:
4182 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4183 case Sema::CXXDestructor:
4184 return S.ComputeDefaultedDtorExceptionSpec(MD);
4185 case Sema::CXXInvalid:
4186 break;
4187 }
4188 llvm_unreachable("only special members have implicit exception specs");
4189}
4190
Richard Smithdd25e802012-07-30 23:48:14 +00004191static void
4192updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4193 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4194 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4195 ExceptSpec.getEPI(EPI);
4196 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004197 S.Context.getFunctionType(FPT->getResultType(),
4198 ArrayRef<QualType>(FPT->arg_type_begin(),
4199 FPT->getNumArgs()),
4200 EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004201 FD->setType(QualType(NewFPT, 0));
4202}
4203
Richard Smithb9d0b762012-07-27 04:22:15 +00004204void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4205 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4206 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4207 return;
4208
Richard Smithdd25e802012-07-30 23:48:14 +00004209 // Evaluate the exception specification.
4210 ImplicitExceptionSpecification ExceptSpec =
4211 computeImplicitExceptionSpec(*this, Loc, MD);
4212
4213 // Update the type of the special member to use it.
4214 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4215
4216 // A user-provided destructor can be defined outside the class. When that
4217 // happens, be sure to update the exception specification on both
4218 // declarations.
4219 const FunctionProtoType *CanonicalFPT =
4220 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4221 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4222 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4223 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004224}
4225
Richard Smith3003e1d2012-05-15 04:39:51 +00004226void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4227 CXXRecordDecl *RD = MD->getParent();
4228 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004229
Richard Smith3003e1d2012-05-15 04:39:51 +00004230 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4231 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004232
4233 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004234 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004235 bool First = MD == MD->getCanonicalDecl();
4236
4237 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004238
4239 // C++11 [dcl.fct.def.default]p1:
4240 // A function that is explicitly defaulted shall
4241 // -- be a special member function (checked elsewhere),
4242 // -- have the same type (except for ref-qualifiers, and except that a
4243 // copy operation can take a non-const reference) as an implicit
4244 // declaration, and
4245 // -- not have default arguments.
4246 unsigned ExpectedParams = 1;
4247 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4248 ExpectedParams = 0;
4249 if (MD->getNumParams() != ExpectedParams) {
4250 // This also checks for default arguments: a copy or move constructor with a
4251 // default argument is classified as a default constructor, and assignment
4252 // operations and destructors can't have default arguments.
4253 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4254 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004255 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004256 } else if (MD->isVariadic()) {
4257 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4258 << CSM << MD->getSourceRange();
4259 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004260 }
4261
Richard Smith3003e1d2012-05-15 04:39:51 +00004262 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004263
Richard Smith7756afa2012-06-10 05:43:50 +00004264 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004265 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004266 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004267 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004268 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004269
Richard Smith3003e1d2012-05-15 04:39:51 +00004270 QualType ReturnType = Context.VoidTy;
4271 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4272 // Check for return type matching.
4273 ReturnType = Type->getResultType();
4274 QualType ExpectedReturnType =
4275 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4276 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4277 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4278 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4279 HadError = true;
4280 }
4281
4282 // A defaulted special member cannot have cv-qualifiers.
4283 if (Type->getTypeQuals()) {
4284 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4285 << (CSM == CXXMoveAssignment);
4286 HadError = true;
4287 }
4288 }
4289
4290 // Check for parameter type matching.
4291 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004292 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004293 if (ExpectedParams && ArgType->isReferenceType()) {
4294 // Argument must be reference to possibly-const T.
4295 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004296 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004297
4298 if (ReferentType.isVolatileQualified()) {
4299 Diag(MD->getLocation(),
4300 diag::err_defaulted_special_member_volatile_param) << CSM;
4301 HadError = true;
4302 }
4303
Richard Smith7756afa2012-06-10 05:43:50 +00004304 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004305 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4306 Diag(MD->getLocation(),
4307 diag::err_defaulted_special_member_copy_const_param)
4308 << (CSM == CXXCopyAssignment);
4309 // FIXME: Explain why this special member can't be const.
4310 } else {
4311 Diag(MD->getLocation(),
4312 diag::err_defaulted_special_member_move_const_param)
4313 << (CSM == CXXMoveAssignment);
4314 }
4315 HadError = true;
4316 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004317 } else if (ExpectedParams) {
4318 // A copy assignment operator can take its argument by value, but a
4319 // defaulted one cannot.
4320 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004321 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004322 HadError = true;
4323 }
Sean Huntbe631222011-05-17 20:44:43 +00004324
Richard Smith61802452011-12-22 02:22:31 +00004325 // C++11 [dcl.fct.def.default]p2:
4326 // An explicitly-defaulted function may be declared constexpr only if it
4327 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004328 // Do not apply this rule to members of class templates, since core issue 1358
4329 // makes such functions always instantiate to constexpr functions. For
4330 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004331 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4332 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004333 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4334 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4335 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004336 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004337 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004338 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004339
Richard Smith61802452011-12-22 02:22:31 +00004340 // and may have an explicit exception-specification only if it is compatible
4341 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004342 if (Type->hasExceptionSpec()) {
4343 // Delay the check if this is the first declaration of the special member,
4344 // since we may not have parsed some necessary in-class initializers yet.
4345 if (First)
4346 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4347 else
4348 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4349 }
Richard Smith61802452011-12-22 02:22:31 +00004350
4351 // If a function is explicitly defaulted on its first declaration,
4352 if (First) {
4353 // -- it is implicitly considered to be constexpr if the implicit
4354 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004355 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004356
Richard Smith3003e1d2012-05-15 04:39:51 +00004357 // -- it is implicitly considered to have the same exception-specification
4358 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004359 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4360 EPI.ExceptionSpecType = EST_Unevaluated;
4361 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004362 MD->setType(Context.getFunctionType(ReturnType,
4363 ArrayRef<QualType>(&ArgType,
4364 ExpectedParams),
4365 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004366 }
4367
Richard Smith3003e1d2012-05-15 04:39:51 +00004368 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004369 if (First) {
4370 MD->setDeletedAsWritten();
4371 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004372 // C++11 [dcl.fct.def.default]p4:
4373 // [For a] user-provided explicitly-defaulted function [...] if such a
4374 // function is implicitly defined as deleted, the program is ill-formed.
4375 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4376 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004377 }
4378 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004379
Richard Smith3003e1d2012-05-15 04:39:51 +00004380 if (HadError)
4381 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004382}
4383
Richard Smith1d28caf2012-12-11 01:14:52 +00004384/// Check whether the exception specification provided for an
4385/// explicitly-defaulted special member matches the exception specification
4386/// that would have been generated for an implicit special member, per
4387/// C++11 [dcl.fct.def.default]p2.
4388void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4389 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4390 // Compute the implicit exception specification.
4391 FunctionProtoType::ExtProtoInfo EPI;
4392 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4393 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Jordan Rosebea522f2013-03-08 21:51:21 +00004394 Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004395
4396 // Ensure that it matches.
4397 CheckEquivalentExceptionSpec(
4398 PDiag(diag::err_incorrect_defaulted_exception_spec)
4399 << getSpecialMember(MD), PDiag(),
4400 ImplicitType, SourceLocation(),
4401 SpecifiedType, MD->getLocation());
4402}
4403
4404void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4405 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4406 I != N; ++I)
4407 CheckExplicitlyDefaultedMemberExceptionSpec(
4408 DelayedDefaultedMemberExceptionSpecs[I].first,
4409 DelayedDefaultedMemberExceptionSpecs[I].second);
4410
4411 DelayedDefaultedMemberExceptionSpecs.clear();
4412}
4413
Richard Smith7d5088a2012-02-18 02:02:13 +00004414namespace {
4415struct SpecialMemberDeletionInfo {
4416 Sema &S;
4417 CXXMethodDecl *MD;
4418 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004419 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004420
4421 // Properties of the special member, computed for convenience.
4422 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4423 SourceLocation Loc;
4424
4425 bool AllFieldsAreConst;
4426
4427 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004428 Sema::CXXSpecialMember CSM, bool Diagnose)
4429 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004430 IsConstructor(false), IsAssignment(false), IsMove(false),
4431 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4432 AllFieldsAreConst(true) {
4433 switch (CSM) {
4434 case Sema::CXXDefaultConstructor:
4435 case Sema::CXXCopyConstructor:
4436 IsConstructor = true;
4437 break;
4438 case Sema::CXXMoveConstructor:
4439 IsConstructor = true;
4440 IsMove = true;
4441 break;
4442 case Sema::CXXCopyAssignment:
4443 IsAssignment = true;
4444 break;
4445 case Sema::CXXMoveAssignment:
4446 IsAssignment = true;
4447 IsMove = true;
4448 break;
4449 case Sema::CXXDestructor:
4450 break;
4451 case Sema::CXXInvalid:
4452 llvm_unreachable("invalid special member kind");
4453 }
4454
4455 if (MD->getNumParams()) {
4456 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4457 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4458 }
4459 }
4460
4461 bool inUnion() const { return MD->getParent()->isUnion(); }
4462
4463 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004464 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4465 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004466 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004467 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4468 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4469 Quals = 0;
4470 return S.LookupSpecialMember(Class, CSM,
4471 ConstArg || (Quals & Qualifiers::Const),
4472 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004473 MD->getRefQualifier() == RQ_RValue,
4474 TQ & Qualifiers::Const,
4475 TQ & Qualifiers::Volatile);
4476 }
4477
Richard Smith6c4c36c2012-03-30 20:53:28 +00004478 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004479
Richard Smith6c4c36c2012-03-30 20:53:28 +00004480 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004481 bool shouldDeleteForField(FieldDecl *FD);
4482 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004483
Richard Smith517bb842012-07-18 03:51:16 +00004484 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4485 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004486 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4487 Sema::SpecialMemberOverloadResult *SMOR,
4488 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004489
4490 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004491};
4492}
4493
John McCall12d8d802012-04-09 20:53:23 +00004494/// Is the given special member inaccessible when used on the given
4495/// sub-object.
4496bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4497 CXXMethodDecl *target) {
4498 /// If we're operating on a base class, the object type is the
4499 /// type of this special member.
4500 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004501 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004502 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4503 objectTy = S.Context.getTypeDeclType(MD->getParent());
4504 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4505
4506 // If we're operating on a field, the object type is the type of the field.
4507 } else {
4508 objectTy = S.Context.getTypeDeclType(target->getParent());
4509 }
4510
4511 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4512}
4513
Richard Smith6c4c36c2012-03-30 20:53:28 +00004514/// Check whether we should delete a special member due to the implicit
4515/// definition containing a call to a special member of a subobject.
4516bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4517 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4518 bool IsDtorCallInCtor) {
4519 CXXMethodDecl *Decl = SMOR->getMethod();
4520 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4521
4522 int DiagKind = -1;
4523
4524 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4525 DiagKind = !Decl ? 0 : 1;
4526 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4527 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004528 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004529 DiagKind = 3;
4530 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4531 !Decl->isTrivial()) {
4532 // A member of a union must have a trivial corresponding special member.
4533 // As a weird special case, a destructor call from a union's constructor
4534 // must be accessible and non-deleted, but need not be trivial. Such a
4535 // destructor is never actually called, but is semantically checked as
4536 // if it were.
4537 DiagKind = 4;
4538 }
4539
4540 if (DiagKind == -1)
4541 return false;
4542
4543 if (Diagnose) {
4544 if (Field) {
4545 S.Diag(Field->getLocation(),
4546 diag::note_deleted_special_member_class_subobject)
4547 << CSM << MD->getParent() << /*IsField*/true
4548 << Field << DiagKind << IsDtorCallInCtor;
4549 } else {
4550 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4551 S.Diag(Base->getLocStart(),
4552 diag::note_deleted_special_member_class_subobject)
4553 << CSM << MD->getParent() << /*IsField*/false
4554 << Base->getType() << DiagKind << IsDtorCallInCtor;
4555 }
4556
4557 if (DiagKind == 1)
4558 S.NoteDeletedFunction(Decl);
4559 // FIXME: Explain inaccessibility if DiagKind == 3.
4560 }
4561
4562 return true;
4563}
4564
Richard Smith9a561d52012-02-26 09:11:52 +00004565/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004566/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004567bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004568 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004569 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004570
4571 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004572 // -- any direct or virtual base class, or non-static data member with no
4573 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004574 // either M has no default constructor or overload resolution as applied
4575 // to M's default constructor results in an ambiguity or in a function
4576 // that is deleted or inaccessible
4577 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4578 // -- a direct or virtual base class B that cannot be copied/moved because
4579 // overload resolution, as applied to B's corresponding special member,
4580 // results in an ambiguity or a function that is deleted or inaccessible
4581 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004582 // C++11 [class.dtor]p5:
4583 // -- any direct or virtual base class [...] has a type with a destructor
4584 // that is deleted or inaccessible
4585 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004586 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004587 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004588 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004589
Richard Smith6c4c36c2012-03-30 20:53:28 +00004590 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4591 // -- any direct or virtual base class or non-static data member has a
4592 // type with a destructor that is deleted or inaccessible
4593 if (IsConstructor) {
4594 Sema::SpecialMemberOverloadResult *SMOR =
4595 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4596 false, false, false, false, false);
4597 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4598 return true;
4599 }
4600
Richard Smith9a561d52012-02-26 09:11:52 +00004601 return false;
4602}
4603
4604/// Check whether we should delete a special member function due to the class
4605/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004606bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004607 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004608 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004609}
4610
4611/// Check whether we should delete a special member function due to the class
4612/// having a particular non-static data member.
4613bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4614 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4615 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4616
4617 if (CSM == Sema::CXXDefaultConstructor) {
4618 // For a default constructor, all references must be initialized in-class
4619 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004620 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4621 if (Diagnose)
4622 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4623 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004624 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004625 }
Richard Smith79363f52012-02-27 06:07:25 +00004626 // C++11 [class.ctor]p5: any non-variant non-static data member of
4627 // const-qualified type (or array thereof) with no
4628 // brace-or-equal-initializer does not have a user-provided default
4629 // constructor.
4630 if (!inUnion() && FieldType.isConstQualified() &&
4631 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004632 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4633 if (Diagnose)
4634 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004635 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004636 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004637 }
4638
4639 if (inUnion() && !FieldType.isConstQualified())
4640 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004641 } else if (CSM == Sema::CXXCopyConstructor) {
4642 // For a copy constructor, data members must not be of rvalue reference
4643 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004644 if (FieldType->isRValueReferenceType()) {
4645 if (Diagnose)
4646 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4647 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004648 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004649 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004650 } else if (IsAssignment) {
4651 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004652 if (FieldType->isReferenceType()) {
4653 if (Diagnose)
4654 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4655 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004656 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004657 }
4658 if (!FieldRecord && FieldType.isConstQualified()) {
4659 // C++11 [class.copy]p23:
4660 // -- a non-static data member of const non-class type (or array thereof)
4661 if (Diagnose)
4662 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004663 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004664 return true;
4665 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004666 }
4667
4668 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004669 // Some additional restrictions exist on the variant members.
4670 if (!inUnion() && FieldRecord->isUnion() &&
4671 FieldRecord->isAnonymousStructOrUnion()) {
4672 bool AllVariantFieldsAreConst = true;
4673
Richard Smithdf8dc862012-03-29 19:00:10 +00004674 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004675 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4676 UE = FieldRecord->field_end();
4677 UI != UE; ++UI) {
4678 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004679
4680 if (!UnionFieldType.isConstQualified())
4681 AllVariantFieldsAreConst = false;
4682
Richard Smith9a561d52012-02-26 09:11:52 +00004683 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4684 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004685 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4686 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004687 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004688 }
4689
4690 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004691 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004692 FieldRecord->field_begin() != FieldRecord->field_end()) {
4693 if (Diagnose)
4694 S.Diag(FieldRecord->getLocation(),
4695 diag::note_deleted_default_ctor_all_const)
4696 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004697 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004698 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004699
Richard Smithdf8dc862012-03-29 19:00:10 +00004700 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004701 // This is technically non-conformant, but sanity demands it.
4702 return false;
4703 }
4704
Richard Smith517bb842012-07-18 03:51:16 +00004705 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4706 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004707 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004708 }
4709
4710 return false;
4711}
4712
4713/// C++11 [class.ctor] p5:
4714/// A defaulted default constructor for a class X is defined as deleted if
4715/// X is a union and all of its variant members are of const-qualified type.
4716bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004717 // This is a silly definition, because it gives an empty union a deleted
4718 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004719 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4720 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4721 if (Diagnose)
4722 S.Diag(MD->getParent()->getLocation(),
4723 diag::note_deleted_default_ctor_all_const)
4724 << MD->getParent() << /*not anonymous union*/0;
4725 return true;
4726 }
4727 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004728}
4729
4730/// Determine whether a defaulted special member function should be defined as
4731/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4732/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004733bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4734 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004735 if (MD->isInvalidDecl())
4736 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004737 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004738 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004739 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004740 return false;
4741
Richard Smith7d5088a2012-02-18 02:02:13 +00004742 // C++11 [expr.lambda.prim]p19:
4743 // The closure type associated with a lambda-expression has a
4744 // deleted (8.4.3) default constructor and a deleted copy
4745 // assignment operator.
4746 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004747 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4748 if (Diagnose)
4749 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004750 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004751 }
4752
Richard Smith5bdaac52012-04-02 20:59:25 +00004753 // For an anonymous struct or union, the copy and assignment special members
4754 // will never be used, so skip the check. For an anonymous union declared at
4755 // namespace scope, the constructor and destructor are used.
4756 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4757 RD->isAnonymousStructOrUnion())
4758 return false;
4759
Richard Smith6c4c36c2012-03-30 20:53:28 +00004760 // C++11 [class.copy]p7, p18:
4761 // If the class definition declares a move constructor or move assignment
4762 // operator, an implicitly declared copy constructor or copy assignment
4763 // operator is defined as deleted.
4764 if (MD->isImplicit() &&
4765 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4766 CXXMethodDecl *UserDeclaredMove = 0;
4767
4768 // In Microsoft mode, a user-declared move only causes the deletion of the
4769 // corresponding copy operation, not both copy operations.
4770 if (RD->hasUserDeclaredMoveConstructor() &&
4771 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4772 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004773
4774 // Find any user-declared move constructor.
4775 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4776 E = RD->ctor_end(); I != E; ++I) {
4777 if (I->isMoveConstructor()) {
4778 UserDeclaredMove = *I;
4779 break;
4780 }
4781 }
Richard Smith1c931be2012-04-02 18:40:40 +00004782 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004783 } else if (RD->hasUserDeclaredMoveAssignment() &&
4784 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4785 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004786
4787 // Find any user-declared move assignment operator.
4788 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4789 E = RD->method_end(); I != E; ++I) {
4790 if (I->isMoveAssignmentOperator()) {
4791 UserDeclaredMove = *I;
4792 break;
4793 }
4794 }
Richard Smith1c931be2012-04-02 18:40:40 +00004795 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004796 }
4797
4798 if (UserDeclaredMove) {
4799 Diag(UserDeclaredMove->getLocation(),
4800 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004801 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004802 << UserDeclaredMove->isMoveAssignmentOperator();
4803 return true;
4804 }
4805 }
Sean Hunte16da072011-10-10 06:18:57 +00004806
Richard Smith5bdaac52012-04-02 20:59:25 +00004807 // Do access control from the special member function
4808 ContextRAII MethodContext(*this, MD);
4809
Richard Smith9a561d52012-02-26 09:11:52 +00004810 // C++11 [class.dtor]p5:
4811 // -- for a virtual destructor, lookup of the non-array deallocation function
4812 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004813 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004814 FunctionDecl *OperatorDelete = 0;
4815 DeclarationName Name =
4816 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4817 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004818 OperatorDelete, false)) {
4819 if (Diagnose)
4820 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004821 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004822 }
Richard Smith9a561d52012-02-26 09:11:52 +00004823 }
4824
Richard Smith6c4c36c2012-03-30 20:53:28 +00004825 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004826
Sean Huntcdee3fe2011-05-11 22:34:38 +00004827 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004828 BE = RD->bases_end(); BI != BE; ++BI)
4829 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004830 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004831 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004832
4833 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004834 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004835 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004836 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004837
4838 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004839 FE = RD->field_end(); FI != FE; ++FI)
4840 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004841 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004842 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004843
Richard Smith7d5088a2012-02-18 02:02:13 +00004844 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004845 return true;
4846
4847 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004848}
4849
Richard Smithac713512012-12-08 02:53:02 +00004850/// Perform lookup for a special member of the specified kind, and determine
4851/// whether it is trivial. If the triviality can be determined without the
4852/// lookup, skip it. This is intended for use when determining whether a
4853/// special member of a containing object is trivial, and thus does not ever
4854/// perform overload resolution for default constructors.
4855///
4856/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4857/// member that was most likely to be intended to be trivial, if any.
4858static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4859 Sema::CXXSpecialMember CSM, unsigned Quals,
4860 CXXMethodDecl **Selected) {
4861 if (Selected)
4862 *Selected = 0;
4863
4864 switch (CSM) {
4865 case Sema::CXXInvalid:
4866 llvm_unreachable("not a special member");
4867
4868 case Sema::CXXDefaultConstructor:
4869 // C++11 [class.ctor]p5:
4870 // A default constructor is trivial if:
4871 // - all the [direct subobjects] have trivial default constructors
4872 //
4873 // Note, no overload resolution is performed in this case.
4874 if (RD->hasTrivialDefaultConstructor())
4875 return true;
4876
4877 if (Selected) {
4878 // If there's a default constructor which could have been trivial, dig it
4879 // out. Otherwise, if there's any user-provided default constructor, point
4880 // to that as an example of why there's not a trivial one.
4881 CXXConstructorDecl *DefCtor = 0;
4882 if (RD->needsImplicitDefaultConstructor())
4883 S.DeclareImplicitDefaultConstructor(RD);
4884 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4885 CE = RD->ctor_end(); CI != CE; ++CI) {
4886 if (!CI->isDefaultConstructor())
4887 continue;
4888 DefCtor = *CI;
4889 if (!DefCtor->isUserProvided())
4890 break;
4891 }
4892
4893 *Selected = DefCtor;
4894 }
4895
4896 return false;
4897
4898 case Sema::CXXDestructor:
4899 // C++11 [class.dtor]p5:
4900 // A destructor is trivial if:
4901 // - all the direct [subobjects] have trivial destructors
4902 if (RD->hasTrivialDestructor())
4903 return true;
4904
4905 if (Selected) {
4906 if (RD->needsImplicitDestructor())
4907 S.DeclareImplicitDestructor(RD);
4908 *Selected = RD->getDestructor();
4909 }
4910
4911 return false;
4912
4913 case Sema::CXXCopyConstructor:
4914 // C++11 [class.copy]p12:
4915 // A copy constructor is trivial if:
4916 // - the constructor selected to copy each direct [subobject] is trivial
4917 if (RD->hasTrivialCopyConstructor()) {
4918 if (Quals == Qualifiers::Const)
4919 // We must either select the trivial copy constructor or reach an
4920 // ambiguity; no need to actually perform overload resolution.
4921 return true;
4922 } else if (!Selected) {
4923 return false;
4924 }
4925 // In C++98, we are not supposed to perform overload resolution here, but we
4926 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4927 // cases like B as having a non-trivial copy constructor:
4928 // struct A { template<typename T> A(T&); };
4929 // struct B { mutable A a; };
4930 goto NeedOverloadResolution;
4931
4932 case Sema::CXXCopyAssignment:
4933 // C++11 [class.copy]p25:
4934 // A copy assignment operator is trivial if:
4935 // - the assignment operator selected to copy each direct [subobject] is
4936 // trivial
4937 if (RD->hasTrivialCopyAssignment()) {
4938 if (Quals == Qualifiers::Const)
4939 return true;
4940 } else if (!Selected) {
4941 return false;
4942 }
4943 // In C++98, we are not supposed to perform overload resolution here, but we
4944 // treat that as a language defect.
4945 goto NeedOverloadResolution;
4946
4947 case Sema::CXXMoveConstructor:
4948 case Sema::CXXMoveAssignment:
4949 NeedOverloadResolution:
4950 Sema::SpecialMemberOverloadResult *SMOR =
4951 S.LookupSpecialMember(RD, CSM,
4952 Quals & Qualifiers::Const,
4953 Quals & Qualifiers::Volatile,
4954 /*RValueThis*/false, /*ConstThis*/false,
4955 /*VolatileThis*/false);
4956
4957 // The standard doesn't describe how to behave if the lookup is ambiguous.
4958 // We treat it as not making the member non-trivial, just like the standard
4959 // mandates for the default constructor. This should rarely matter, because
4960 // the member will also be deleted.
4961 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4962 return true;
4963
4964 if (!SMOR->getMethod()) {
4965 assert(SMOR->getKind() ==
4966 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4967 return false;
4968 }
4969
4970 // We deliberately don't check if we found a deleted special member. We're
4971 // not supposed to!
4972 if (Selected)
4973 *Selected = SMOR->getMethod();
4974 return SMOR->getMethod()->isTrivial();
4975 }
4976
4977 llvm_unreachable("unknown special method kind");
4978}
4979
Benjamin Kramera574c892013-02-15 12:30:38 +00004980static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00004981 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4982 CI != CE; ++CI)
4983 if (!CI->isImplicit())
4984 return *CI;
4985
4986 // Look for constructor templates.
4987 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4988 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4989 if (CXXConstructorDecl *CD =
4990 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4991 return CD;
4992 }
4993
4994 return 0;
4995}
4996
4997/// The kind of subobject we are checking for triviality. The values of this
4998/// enumeration are used in diagnostics.
4999enum TrivialSubobjectKind {
5000 /// The subobject is a base class.
5001 TSK_BaseClass,
5002 /// The subobject is a non-static data member.
5003 TSK_Field,
5004 /// The object is actually the complete object.
5005 TSK_CompleteObject
5006};
5007
5008/// Check whether the special member selected for a given type would be trivial.
5009static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5010 QualType SubType,
5011 Sema::CXXSpecialMember CSM,
5012 TrivialSubobjectKind Kind,
5013 bool Diagnose) {
5014 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5015 if (!SubRD)
5016 return true;
5017
5018 CXXMethodDecl *Selected;
5019 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5020 Diagnose ? &Selected : 0))
5021 return true;
5022
5023 if (Diagnose) {
5024 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5025 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5026 << Kind << SubType.getUnqualifiedType();
5027 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5028 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5029 } else if (!Selected)
5030 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5031 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5032 else if (Selected->isUserProvided()) {
5033 if (Kind == TSK_CompleteObject)
5034 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5035 << Kind << SubType.getUnqualifiedType() << CSM;
5036 else {
5037 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5038 << Kind << SubType.getUnqualifiedType() << CSM;
5039 S.Diag(Selected->getLocation(), diag::note_declared_at);
5040 }
5041 } else {
5042 if (Kind != TSK_CompleteObject)
5043 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5044 << Kind << SubType.getUnqualifiedType() << CSM;
5045
5046 // Explain why the defaulted or deleted special member isn't trivial.
5047 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5048 }
5049 }
5050
5051 return false;
5052}
5053
5054/// Check whether the members of a class type allow a special member to be
5055/// trivial.
5056static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5057 Sema::CXXSpecialMember CSM,
5058 bool ConstArg, bool Diagnose) {
5059 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5060 FE = RD->field_end(); FI != FE; ++FI) {
5061 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5062 continue;
5063
5064 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5065
5066 // Pretend anonymous struct or union members are members of this class.
5067 if (FI->isAnonymousStructOrUnion()) {
5068 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5069 CSM, ConstArg, Diagnose))
5070 return false;
5071 continue;
5072 }
5073
5074 // C++11 [class.ctor]p5:
5075 // A default constructor is trivial if [...]
5076 // -- no non-static data member of its class has a
5077 // brace-or-equal-initializer
5078 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5079 if (Diagnose)
5080 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5081 return false;
5082 }
5083
5084 // Objective C ARC 4.3.5:
5085 // [...] nontrivally ownership-qualified types are [...] not trivially
5086 // default constructible, copy constructible, move constructible, copy
5087 // assignable, move assignable, or destructible [...]
5088 if (S.getLangOpts().ObjCAutoRefCount &&
5089 FieldType.hasNonTrivialObjCLifetime()) {
5090 if (Diagnose)
5091 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5092 << RD << FieldType.getObjCLifetime();
5093 return false;
5094 }
5095
5096 if (ConstArg && !FI->isMutable())
5097 FieldType.addConst();
5098 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5099 TSK_Field, Diagnose))
5100 return false;
5101 }
5102
5103 return true;
5104}
5105
5106/// Diagnose why the specified class does not have a trivial special member of
5107/// the given kind.
5108void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5109 QualType Ty = Context.getRecordType(RD);
5110 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5111 Ty.addConst();
5112
5113 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5114 TSK_CompleteObject, /*Diagnose*/true);
5115}
5116
5117/// Determine whether a defaulted or deleted special member function is trivial,
5118/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5119/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5120bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5121 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005122 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5123
5124 CXXRecordDecl *RD = MD->getParent();
5125
5126 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005127
5128 // C++11 [class.copy]p12, p25:
5129 // A [special member] is trivial if its declared parameter type is the same
5130 // as if it had been implicitly declared [...]
5131 switch (CSM) {
5132 case CXXDefaultConstructor:
5133 case CXXDestructor:
5134 // Trivial default constructors and destructors cannot have parameters.
5135 break;
5136
5137 case CXXCopyConstructor:
5138 case CXXCopyAssignment: {
5139 // Trivial copy operations always have const, non-volatile parameter types.
5140 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005141 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005142 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5143 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5144 if (Diagnose)
5145 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5146 << Param0->getSourceRange() << Param0->getType()
5147 << Context.getLValueReferenceType(
5148 Context.getRecordType(RD).withConst());
5149 return false;
5150 }
5151 break;
5152 }
5153
5154 case CXXMoveConstructor:
5155 case CXXMoveAssignment: {
5156 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005157 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005158 const RValueReferenceType *RT =
5159 Param0->getType()->getAs<RValueReferenceType>();
5160 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5161 if (Diagnose)
5162 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5163 << Param0->getSourceRange() << Param0->getType()
5164 << Context.getRValueReferenceType(Context.getRecordType(RD));
5165 return false;
5166 }
5167 break;
5168 }
5169
5170 case CXXInvalid:
5171 llvm_unreachable("not a special member");
5172 }
5173
5174 // FIXME: We require that the parameter-declaration-clause is equivalent to
5175 // that of an implicit declaration, not just that the declared parameter type
5176 // matches, in order to prevent absuridities like a function simultaneously
5177 // being a trivial copy constructor and a non-trivial default constructor.
5178 // This issue has not yet been assigned a core issue number.
5179 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5180 if (Diagnose)
5181 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5182 diag::note_nontrivial_default_arg)
5183 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5184 return false;
5185 }
5186 if (MD->isVariadic()) {
5187 if (Diagnose)
5188 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5189 return false;
5190 }
5191
5192 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5193 // A copy/move [constructor or assignment operator] is trivial if
5194 // -- the [member] selected to copy/move each direct base class subobject
5195 // is trivial
5196 //
5197 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5198 // A [default constructor or destructor] is trivial if
5199 // -- all the direct base classes have trivial [default constructors or
5200 // destructors]
5201 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5202 BE = RD->bases_end(); BI != BE; ++BI)
5203 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5204 ConstArg ? BI->getType().withConst()
5205 : BI->getType(),
5206 CSM, TSK_BaseClass, Diagnose))
5207 return false;
5208
5209 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5210 // A copy/move [constructor or assignment operator] for a class X is
5211 // trivial if
5212 // -- for each non-static data member of X that is of class type (or array
5213 // thereof), the constructor selected to copy/move that member is
5214 // trivial
5215 //
5216 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5217 // A [default constructor or destructor] is trivial if
5218 // -- for all of the non-static data members of its class that are of class
5219 // type (or array thereof), each such class has a trivial [default
5220 // constructor or destructor]
5221 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5222 return false;
5223
5224 // C++11 [class.dtor]p5:
5225 // A destructor is trivial if [...]
5226 // -- the destructor is not virtual
5227 if (CSM == CXXDestructor && MD->isVirtual()) {
5228 if (Diagnose)
5229 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5230 return false;
5231 }
5232
5233 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5234 // A [special member] for class X is trivial if [...]
5235 // -- class X has no virtual functions and no virtual base classes
5236 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5237 if (!Diagnose)
5238 return false;
5239
5240 if (RD->getNumVBases()) {
5241 // Check for virtual bases. We already know that the corresponding
5242 // member in all bases is trivial, so vbases must all be direct.
5243 CXXBaseSpecifier &BS = *RD->vbases_begin();
5244 assert(BS.isVirtual());
5245 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5246 return false;
5247 }
5248
5249 // Must have a virtual method.
5250 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5251 ME = RD->method_end(); MI != ME; ++MI) {
5252 if (MI->isVirtual()) {
5253 SourceLocation MLoc = MI->getLocStart();
5254 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5255 return false;
5256 }
5257 }
5258
5259 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5260 }
5261
5262 // Looks like it's trivial!
5263 return true;
5264}
5265
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005266/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005267namespace {
5268 struct FindHiddenVirtualMethodData {
5269 Sema *S;
5270 CXXMethodDecl *Method;
5271 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005272 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005273 };
5274}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005275
David Blaikie5f750682012-10-19 00:53:08 +00005276/// \brief Check whether any most overriden method from MD in Methods
5277static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5278 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5279 if (MD->size_overridden_methods() == 0)
5280 return Methods.count(MD->getCanonicalDecl());
5281 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5282 E = MD->end_overridden_methods();
5283 I != E; ++I)
5284 if (CheckMostOverridenMethods(*I, Methods))
5285 return true;
5286 return false;
5287}
5288
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005289/// \brief Member lookup function that determines whether a given C++
5290/// method overloads virtual methods in a base class without overriding any,
5291/// to be used with CXXRecordDecl::lookupInBases().
5292static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5293 CXXBasePath &Path,
5294 void *UserData) {
5295 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5296
5297 FindHiddenVirtualMethodData &Data
5298 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5299
5300 DeclarationName Name = Data.Method->getDeclName();
5301 assert(Name.getNameKind() == DeclarationName::Identifier);
5302
5303 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005304 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005305 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005306 !Path.Decls.empty();
5307 Path.Decls = Path.Decls.slice(1)) {
5308 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005309 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005310 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005311 foundSameNameMethod = true;
5312 // Interested only in hidden virtual methods.
5313 if (!MD->isVirtual())
5314 continue;
5315 // If the method we are checking overrides a method from its base
5316 // don't warn about the other overloaded methods.
5317 if (!Data.S->IsOverload(Data.Method, MD, false))
5318 return true;
5319 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005320 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005321 overloadedMethods.push_back(MD);
5322 }
5323 }
5324
5325 if (foundSameNameMethod)
5326 Data.OverloadedMethods.append(overloadedMethods.begin(),
5327 overloadedMethods.end());
5328 return foundSameNameMethod;
5329}
5330
David Blaikie5f750682012-10-19 00:53:08 +00005331/// \brief Add the most overriden methods from MD to Methods
5332static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5333 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5334 if (MD->size_overridden_methods() == 0)
5335 Methods.insert(MD->getCanonicalDecl());
5336 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5337 E = MD->end_overridden_methods();
5338 I != E; ++I)
5339 AddMostOverridenMethods(*I, Methods);
5340}
5341
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005342/// \brief See if a method overloads virtual methods in a base class without
5343/// overriding any.
5344void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5345 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005346 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005347 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005348 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005349 return;
5350
5351 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5352 /*bool RecordPaths=*/false,
5353 /*bool DetectVirtual=*/false);
5354 FindHiddenVirtualMethodData Data;
5355 Data.Method = MD;
5356 Data.S = this;
5357
5358 // Keep the base methods that were overriden or introduced in the subclass
5359 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005360 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5361 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5362 NamedDecl *ND = *I;
5363 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005364 ND = shad->getTargetDecl();
5365 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5366 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005367 }
5368
5369 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5370 !Data.OverloadedMethods.empty()) {
5371 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5372 << MD << (Data.OverloadedMethods.size() > 1);
5373
5374 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5375 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5376 Diag(overloadedMD->getLocation(),
5377 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5378 }
5379 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005380}
5381
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005382void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005383 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005384 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005385 SourceLocation RBrac,
5386 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005387 if (!TagDecl)
5388 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005389
Douglas Gregor42af25f2009-05-11 19:58:34 +00005390 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005391
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005392 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5393 if (l->getKind() != AttributeList::AT_Visibility)
5394 continue;
5395 l->setInvalid();
5396 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5397 l->getName();
5398 }
5399
David Blaikie77b6de02011-09-22 02:58:26 +00005400 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005401 // strict aliasing violation!
5402 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005403 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005404
Douglas Gregor23c94db2010-07-02 17:43:08 +00005405 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005406 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005407}
5408
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005409/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5410/// special functions, such as the default constructor, copy
5411/// constructor, or destructor, to the given C++ class (C++
5412/// [special]p1). This routine can only be executed just before the
5413/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005414void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005415 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005416 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005417
Richard Smithbc2a35d2012-12-08 08:32:28 +00005418 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005419 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005420
Richard Smithbc2a35d2012-12-08 08:32:28 +00005421 // If the properties or semantics of the copy constructor couldn't be
5422 // determined while the class was being declared, force a declaration
5423 // of it now.
5424 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5425 DeclareImplicitCopyConstructor(ClassDecl);
5426 }
5427
Richard Smith80ad52f2013-01-02 11:42:31 +00005428 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005429 ++ASTContext::NumImplicitMoveConstructors;
5430
Richard Smithbc2a35d2012-12-08 08:32:28 +00005431 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5432 DeclareImplicitMoveConstructor(ClassDecl);
5433 }
5434
Douglas Gregora376d102010-07-02 21:50:04 +00005435 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5436 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005437
5438 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005439 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005440 // it shows up in the right place in the vtable and that we diagnose
5441 // problems with the implicit exception specification.
5442 if (ClassDecl->isDynamicClass() ||
5443 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005444 DeclareImplicitCopyAssignment(ClassDecl);
5445 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005446
Richard Smith80ad52f2013-01-02 11:42:31 +00005447 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005448 ++ASTContext::NumImplicitMoveAssignmentOperators;
5449
5450 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005451 if (ClassDecl->isDynamicClass() ||
5452 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005453 DeclareImplicitMoveAssignment(ClassDecl);
5454 }
5455
Douglas Gregor4923aa22010-07-02 20:37:36 +00005456 if (!ClassDecl->hasUserDeclaredDestructor()) {
5457 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005458
5459 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005460 // have to declare the destructor immediately. This ensures that, e.g., it
5461 // shows up in the right place in the vtable and that we diagnose problems
5462 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005463 if (ClassDecl->isDynamicClass() ||
5464 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005465 DeclareImplicitDestructor(ClassDecl);
5466 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005467}
5468
Francois Pichet8387e2a2011-04-22 22:18:13 +00005469void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5470 if (!D)
5471 return;
5472
5473 int NumParamList = D->getNumTemplateParameterLists();
5474 for (int i = 0; i < NumParamList; i++) {
5475 TemplateParameterList* Params = D->getTemplateParameterList(i);
5476 for (TemplateParameterList::iterator Param = Params->begin(),
5477 ParamEnd = Params->end();
5478 Param != ParamEnd; ++Param) {
5479 NamedDecl *Named = cast<NamedDecl>(*Param);
5480 if (Named->getDeclName()) {
5481 S->AddDecl(Named);
5482 IdResolver.AddDecl(Named);
5483 }
5484 }
5485 }
5486}
5487
John McCalld226f652010-08-21 09:40:31 +00005488void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005489 if (!D)
5490 return;
5491
5492 TemplateParameterList *Params = 0;
5493 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5494 Params = Template->getTemplateParameters();
5495 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5496 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5497 Params = PartialSpec->getTemplateParameters();
5498 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005499 return;
5500
Douglas Gregor6569d682009-05-27 23:11:45 +00005501 for (TemplateParameterList::iterator Param = Params->begin(),
5502 ParamEnd = Params->end();
5503 Param != ParamEnd; ++Param) {
5504 NamedDecl *Named = cast<NamedDecl>(*Param);
5505 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005506 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005507 IdResolver.AddDecl(Named);
5508 }
5509 }
5510}
5511
John McCalld226f652010-08-21 09:40:31 +00005512void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005513 if (!RecordD) return;
5514 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005515 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005516 PushDeclContext(S, Record);
5517}
5518
John McCalld226f652010-08-21 09:40:31 +00005519void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005520 if (!RecordD) return;
5521 PopDeclContext();
5522}
5523
Douglas Gregor72b505b2008-12-16 21:30:33 +00005524/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5525/// parsing a top-level (non-nested) C++ class, and we are now
5526/// parsing those parts of the given Method declaration that could
5527/// not be parsed earlier (C++ [class.mem]p2), such as default
5528/// arguments. This action should enter the scope of the given
5529/// Method declaration as if we had just parsed the qualified method
5530/// name. However, it should not bring the parameters into scope;
5531/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005532void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005533}
5534
5535/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5536/// C++ method declaration. We're (re-)introducing the given
5537/// function parameter into scope for use in parsing later parts of
5538/// the method declaration. For example, we could see an
5539/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005540void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005541 if (!ParamD)
5542 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005543
John McCalld226f652010-08-21 09:40:31 +00005544 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005545
5546 // If this parameter has an unparsed default argument, clear it out
5547 // to make way for the parsed default argument.
5548 if (Param->hasUnparsedDefaultArg())
5549 Param->setDefaultArg(0);
5550
John McCalld226f652010-08-21 09:40:31 +00005551 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005552 if (Param->getDeclName())
5553 IdResolver.AddDecl(Param);
5554}
5555
5556/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5557/// processing the delayed method declaration for Method. The method
5558/// declaration is now considered finished. There may be a separate
5559/// ActOnStartOfFunctionDef action later (not necessarily
5560/// immediately!) for this method, if it was also defined inside the
5561/// class body.
John McCalld226f652010-08-21 09:40:31 +00005562void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005563 if (!MethodD)
5564 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005565
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005566 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005567
John McCalld226f652010-08-21 09:40:31 +00005568 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005569
5570 // Now that we have our default arguments, check the constructor
5571 // again. It could produce additional diagnostics or affect whether
5572 // the class has implicitly-declared destructors, among other
5573 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005574 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5575 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005576
5577 // Check the default arguments, which we may have added.
5578 if (!Method->isInvalidDecl())
5579 CheckCXXDefaultArguments(Method);
5580}
5581
Douglas Gregor42a552f2008-11-05 20:51:48 +00005582/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005583/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005584/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005585/// emit diagnostics and set the invalid bit to true. In any case, the type
5586/// will be updated to reflect a well-formed type for the constructor and
5587/// returned.
5588QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005589 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005590 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005591
5592 // C++ [class.ctor]p3:
5593 // A constructor shall not be virtual (10.3) or static (9.4). A
5594 // constructor can be invoked for a const, volatile or const
5595 // volatile object. A constructor shall not be declared const,
5596 // volatile, or const volatile (9.3.2).
5597 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005598 if (!D.isInvalidType())
5599 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5600 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5601 << SourceRange(D.getIdentifierLoc());
5602 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005603 }
John McCalld931b082010-08-26 03:08:43 +00005604 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005605 if (!D.isInvalidType())
5606 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5607 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5608 << SourceRange(D.getIdentifierLoc());
5609 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005610 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005611 }
Mike Stump1eb44332009-09-09 15:08:12 +00005612
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005613 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005614 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005615 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005616 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5617 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005618 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005619 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5620 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005621 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005622 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5623 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005624 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005625 }
Mike Stump1eb44332009-09-09 15:08:12 +00005626
Douglas Gregorc938c162011-01-26 05:01:58 +00005627 // C++0x [class.ctor]p4:
5628 // A constructor shall not be declared with a ref-qualifier.
5629 if (FTI.hasRefQualifier()) {
5630 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5631 << FTI.RefQualifierIsLValueRef
5632 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5633 D.setInvalidType();
5634 }
5635
Douglas Gregor42a552f2008-11-05 20:51:48 +00005636 // Rebuild the function type "R" without any type qualifiers (in
5637 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005638 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005639 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005640 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5641 return R;
5642
5643 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5644 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005645 EPI.RefQualifier = RQ_None;
5646
Jordan Rosebea522f2013-03-08 21:51:21 +00005647 return Context.getFunctionType(Context.VoidTy,
5648 ArrayRef<QualType>(Proto->arg_type_begin(),
5649 Proto->getNumArgs()),
5650 EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005651}
5652
Douglas Gregor72b505b2008-12-16 21:30:33 +00005653/// CheckConstructor - Checks a fully-formed constructor for
5654/// well-formedness, issuing any diagnostics required. Returns true if
5655/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005656void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005657 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005658 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5659 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005660 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005661
5662 // C++ [class.copy]p3:
5663 // A declaration of a constructor for a class X is ill-formed if
5664 // its first parameter is of type (optionally cv-qualified) X and
5665 // either there are no other parameters or else all other
5666 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005667 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005668 ((Constructor->getNumParams() == 1) ||
5669 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005670 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5671 Constructor->getTemplateSpecializationKind()
5672 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005673 QualType ParamType = Constructor->getParamDecl(0)->getType();
5674 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5675 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005676 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005677 const char *ConstRef
5678 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5679 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005680 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005681 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005682
5683 // FIXME: Rather that making the constructor invalid, we should endeavor
5684 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005685 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005686 }
5687 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005688}
5689
John McCall15442822010-08-04 01:04:25 +00005690/// CheckDestructor - Checks a fully-formed destructor definition for
5691/// well-formedness, issuing any diagnostics required. Returns true
5692/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005693bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005694 CXXRecordDecl *RD = Destructor->getParent();
5695
5696 if (Destructor->isVirtual()) {
5697 SourceLocation Loc;
5698
5699 if (!Destructor->isImplicit())
5700 Loc = Destructor->getLocation();
5701 else
5702 Loc = RD->getLocation();
5703
5704 // If we have a virtual destructor, look up the deallocation function
5705 FunctionDecl *OperatorDelete = 0;
5706 DeclarationName Name =
5707 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005708 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005709 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005710
Eli Friedman5f2987c2012-02-02 03:46:19 +00005711 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005712
5713 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005714 }
Anders Carlsson37909802009-11-30 21:24:50 +00005715
5716 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005717}
5718
Mike Stump1eb44332009-09-09 15:08:12 +00005719static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005720FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5721 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5722 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005723 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005724}
5725
Douglas Gregor42a552f2008-11-05 20:51:48 +00005726/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5727/// the well-formednes of the destructor declarator @p D with type @p
5728/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005729/// emit diagnostics and set the declarator to invalid. Even if this happens,
5730/// will be updated to reflect a well-formed type for the destructor and
5731/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005732QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005733 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005734 // C++ [class.dtor]p1:
5735 // [...] A typedef-name that names a class is a class-name
5736 // (7.1.3); however, a typedef-name that names a class shall not
5737 // be used as the identifier in the declarator for a destructor
5738 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005739 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005740 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005741 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005742 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005743 else if (const TemplateSpecializationType *TST =
5744 DeclaratorType->getAs<TemplateSpecializationType>())
5745 if (TST->isTypeAlias())
5746 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5747 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005748
5749 // C++ [class.dtor]p2:
5750 // A destructor is used to destroy objects of its class type. A
5751 // destructor takes no parameters, and no return type can be
5752 // specified for it (not even void). The address of a destructor
5753 // shall not be taken. A destructor shall not be static. A
5754 // destructor can be invoked for a const, volatile or const
5755 // volatile object. A destructor shall not be declared const,
5756 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005757 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005758 if (!D.isInvalidType())
5759 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5760 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005761 << SourceRange(D.getIdentifierLoc())
5762 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5763
John McCalld931b082010-08-26 03:08:43 +00005764 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005765 }
Chris Lattner65401802009-04-25 08:28:21 +00005766 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005767 // Destructors don't have return types, but the parser will
5768 // happily parse something like:
5769 //
5770 // class X {
5771 // float ~X();
5772 // };
5773 //
5774 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005775 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5776 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5777 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005778 }
Mike Stump1eb44332009-09-09 15:08:12 +00005779
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005780 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005781 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005782 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005783 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5784 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005785 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005786 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5787 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005788 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005789 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5790 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005791 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005792 }
5793
Douglas Gregorc938c162011-01-26 05:01:58 +00005794 // C++0x [class.dtor]p2:
5795 // A destructor shall not be declared with a ref-qualifier.
5796 if (FTI.hasRefQualifier()) {
5797 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5798 << FTI.RefQualifierIsLValueRef
5799 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5800 D.setInvalidType();
5801 }
5802
Douglas Gregor42a552f2008-11-05 20:51:48 +00005803 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005804 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005805 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5806
5807 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005808 FTI.freeArgs();
5809 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005810 }
5811
Mike Stump1eb44332009-09-09 15:08:12 +00005812 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005813 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005814 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005815 D.setInvalidType();
5816 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005817
5818 // Rebuild the function type "R" without any type qualifiers or
5819 // parameters (in case any of the errors above fired) and with
5820 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005821 // types.
John McCalle23cf432010-12-14 08:05:40 +00005822 if (!D.isInvalidType())
5823 return R;
5824
Douglas Gregord92ec472010-07-01 05:10:53 +00005825 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005826 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5827 EPI.Variadic = false;
5828 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005829 EPI.RefQualifier = RQ_None;
Jordan Rosebea522f2013-03-08 21:51:21 +00005830 return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005831}
5832
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005833/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5834/// well-formednes of the conversion function declarator @p D with
5835/// type @p R. If there are any errors in the declarator, this routine
5836/// will emit diagnostics and return true. Otherwise, it will return
5837/// false. Either way, the type @p R will be updated to reflect a
5838/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005839void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005840 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005841 // C++ [class.conv.fct]p1:
5842 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005843 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005844 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005845 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005846 if (!D.isInvalidType())
5847 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5848 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5849 << SourceRange(D.getIdentifierLoc());
5850 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005851 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005852 }
John McCalla3f81372010-04-13 00:04:31 +00005853
5854 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5855
Chris Lattner6e475012009-04-25 08:35:12 +00005856 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005857 // Conversion functions don't have return types, but the parser will
5858 // happily parse something like:
5859 //
5860 // class X {
5861 // float operator bool();
5862 // };
5863 //
5864 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005865 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5866 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5867 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005868 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005869 }
5870
John McCalla3f81372010-04-13 00:04:31 +00005871 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5872
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005873 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005874 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005875 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5876
5877 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005878 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005879 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005880 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005881 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005882 D.setInvalidType();
5883 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005884
John McCalla3f81372010-04-13 00:04:31 +00005885 // Diagnose "&operator bool()" and other such nonsense. This
5886 // is actually a gcc extension which we don't support.
5887 if (Proto->getResultType() != ConvType) {
5888 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5889 << Proto->getResultType();
5890 D.setInvalidType();
5891 ConvType = Proto->getResultType();
5892 }
5893
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005894 // C++ [class.conv.fct]p4:
5895 // The conversion-type-id shall not represent a function type nor
5896 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005897 if (ConvType->isArrayType()) {
5898 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5899 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005900 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005901 } else if (ConvType->isFunctionType()) {
5902 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5903 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005904 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005905 }
5906
5907 // Rebuild the function type "R" without any parameters (in case any
5908 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005909 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005910 if (D.isInvalidType())
Jordan Rosebea522f2013-03-08 21:51:21 +00005911 R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5912 Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005913
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005914 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005915 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005916 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00005917 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005918 diag::warn_cxx98_compat_explicit_conversion_functions :
5919 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005920 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005921}
5922
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005923/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5924/// the declaration of the given C++ conversion function. This routine
5925/// is responsible for recording the conversion function in the C++
5926/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005927Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005928 assert(Conversion && "Expected to receive a conversion function declaration");
5929
Douglas Gregor9d350972008-12-12 08:25:50 +00005930 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005931
5932 // Make sure we aren't redeclaring the conversion function.
5933 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005934
5935 // C++ [class.conv.fct]p1:
5936 // [...] A conversion function is never used to convert a
5937 // (possibly cv-qualified) object to the (possibly cv-qualified)
5938 // same object type (or a reference to it), to a (possibly
5939 // cv-qualified) base class of that type (or a reference to it),
5940 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005941 // FIXME: Suppress this warning if the conversion function ends up being a
5942 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005943 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005944 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005945 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005946 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005947 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5948 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005949 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005950 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005951 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5952 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005953 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005954 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005955 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005956 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005957 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005958 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005959 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005960 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005961 }
5962
Douglas Gregore80622f2010-09-29 04:25:11 +00005963 if (FunctionTemplateDecl *ConversionTemplate
5964 = Conversion->getDescribedFunctionTemplate())
5965 return ConversionTemplate;
5966
John McCalld226f652010-08-21 09:40:31 +00005967 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005968}
5969
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005970//===----------------------------------------------------------------------===//
5971// Namespace Handling
5972//===----------------------------------------------------------------------===//
5973
Richard Smithd1a55a62012-10-04 22:13:39 +00005974/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5975/// reopened.
5976static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5977 SourceLocation Loc,
5978 IdentifierInfo *II, bool *IsInline,
5979 NamespaceDecl *PrevNS) {
5980 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005981
Richard Smithc969e6a2012-10-05 01:46:25 +00005982 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5983 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5984 // inline namespaces, with the intention of bringing names into namespace std.
5985 //
5986 // We support this just well enough to get that case working; this is not
5987 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005988 if (*IsInline && II && II->getName().startswith("__atomic") &&
5989 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005990 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005991 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5992 NS = NS->getPreviousDecl())
5993 NS->setInline(*IsInline);
5994 // Patch up the lookup table for the containing namespace. This isn't really
5995 // correct, but it's good enough for this particular case.
5996 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5997 E = PrevNS->decls_end(); I != E; ++I)
5998 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5999 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6000 return;
6001 }
6002
6003 if (PrevNS->isInline())
6004 // The user probably just forgot the 'inline', so suggest that it
6005 // be added back.
6006 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6007 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6008 else
6009 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6010 << IsInline;
6011
6012 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6013 *IsInline = PrevNS->isInline();
6014}
John McCallea318642010-08-26 09:15:37 +00006015
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006016/// ActOnStartNamespaceDef - This is called at the start of a namespace
6017/// definition.
John McCalld226f652010-08-21 09:40:31 +00006018Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006019 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006020 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006021 SourceLocation IdentLoc,
6022 IdentifierInfo *II,
6023 SourceLocation LBrace,
6024 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006025 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6026 // For anonymous namespace, take the location of the left brace.
6027 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006028 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006029 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006030 bool IsStd = false;
6031 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006032 Scope *DeclRegionScope = NamespcScope->getParent();
6033
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006034 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006035 if (II) {
6036 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006037 // The identifier in an original-namespace-definition shall not
6038 // have been previously defined in the declarative region in
6039 // which the original-namespace-definition appears. The
6040 // identifier in an original-namespace-definition is the name of
6041 // the namespace. Subsequently in that declarative region, it is
6042 // treated as an original-namespace-name.
6043 //
6044 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006045 // look through using directives, just look for any ordinary names.
6046
6047 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006048 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6049 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006050 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006051 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6052 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6053 ++I) {
6054 if ((*I)->getIdentifierNamespace() & IDNS) {
6055 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006056 break;
6057 }
6058 }
6059
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006060 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6061
6062 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006063 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006064 if (IsInline != PrevNS->isInline())
6065 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6066 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006067 } else if (PrevDecl) {
6068 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006069 Diag(Loc, diag::err_redefinition_different_kind)
6070 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006071 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006072 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006073 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006074 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006075 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006076 // This is the first "real" definition of the namespace "std", so update
6077 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006078 PrevNS = getStdNamespace();
6079 IsStd = true;
6080 AddToKnown = !IsInline;
6081 } else {
6082 // We've seen this namespace for the first time.
6083 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006084 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006085 } else {
John McCall9aeed322009-10-01 00:25:31 +00006086 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006087
6088 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006089 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006090 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006091 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006092 } else {
6093 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006094 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006095 }
6096
Richard Smithd1a55a62012-10-04 22:13:39 +00006097 if (PrevNS && IsInline != PrevNS->isInline())
6098 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6099 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006100 }
6101
6102 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6103 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006104 if (IsInvalid)
6105 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006106
6107 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006108
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006109 // FIXME: Should we be merging attributes?
6110 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006111 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006112
6113 if (IsStd)
6114 StdNamespace = Namespc;
6115 if (AddToKnown)
6116 KnownNamespaces[Namespc] = false;
6117
6118 if (II) {
6119 PushOnScopeChains(Namespc, DeclRegionScope);
6120 } else {
6121 // Link the anonymous namespace into its parent.
6122 DeclContext *Parent = CurContext->getRedeclContext();
6123 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6124 TU->setAnonymousNamespace(Namespc);
6125 } else {
6126 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006127 }
John McCall9aeed322009-10-01 00:25:31 +00006128
Douglas Gregora4181472010-03-24 00:46:35 +00006129 CurContext->addDecl(Namespc);
6130
John McCall9aeed322009-10-01 00:25:31 +00006131 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6132 // behaves as if it were replaced by
6133 // namespace unique { /* empty body */ }
6134 // using namespace unique;
6135 // namespace unique { namespace-body }
6136 // where all occurrences of 'unique' in a translation unit are
6137 // replaced by the same identifier and this identifier differs
6138 // from all other identifiers in the entire program.
6139
6140 // We just create the namespace with an empty name and then add an
6141 // implicit using declaration, just like the standard suggests.
6142 //
6143 // CodeGen enforces the "universally unique" aspect by giving all
6144 // declarations semantically contained within an anonymous
6145 // namespace internal linkage.
6146
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006147 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006148 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006149 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006150 /* 'using' */ LBrace,
6151 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006152 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006153 /* identifier */ SourceLocation(),
6154 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006155 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006156 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006157 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006158 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006159 }
6160
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006161 ActOnDocumentableDecl(Namespc);
6162
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006163 // Although we could have an invalid decl (i.e. the namespace name is a
6164 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006165 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6166 // for the namespace has the declarations that showed up in that particular
6167 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006168 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006169 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006170}
6171
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006172/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6173/// is a namespace alias, returns the namespace it points to.
6174static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6175 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6176 return AD->getNamespace();
6177 return dyn_cast_or_null<NamespaceDecl>(D);
6178}
6179
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006180/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6181/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006182void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006183 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6184 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006185 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006186 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006187 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006188 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006189}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006190
John McCall384aff82010-08-25 07:42:41 +00006191CXXRecordDecl *Sema::getStdBadAlloc() const {
6192 return cast_or_null<CXXRecordDecl>(
6193 StdBadAlloc.get(Context.getExternalSource()));
6194}
6195
6196NamespaceDecl *Sema::getStdNamespace() const {
6197 return cast_or_null<NamespaceDecl>(
6198 StdNamespace.get(Context.getExternalSource()));
6199}
6200
Douglas Gregor66992202010-06-29 17:53:46 +00006201/// \brief Retrieve the special "std" namespace, which may require us to
6202/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006203NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006204 if (!StdNamespace) {
6205 // The "std" namespace has not yet been defined, so build one implicitly.
6206 StdNamespace = NamespaceDecl::Create(Context,
6207 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006208 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006209 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006210 &PP.getIdentifierTable().get("std"),
6211 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006212 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006213 }
6214
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006215 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006216}
6217
Sebastian Redl395e04d2012-01-17 22:49:33 +00006218bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006219 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006220 "Looking for std::initializer_list outside of C++.");
6221
6222 // We're looking for implicit instantiations of
6223 // template <typename E> class std::initializer_list.
6224
6225 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6226 return false;
6227
Sebastian Redl84760e32012-01-17 22:49:58 +00006228 ClassTemplateDecl *Template = 0;
6229 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006230
Sebastian Redl84760e32012-01-17 22:49:58 +00006231 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006232
Sebastian Redl84760e32012-01-17 22:49:58 +00006233 ClassTemplateSpecializationDecl *Specialization =
6234 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6235 if (!Specialization)
6236 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006237
Sebastian Redl84760e32012-01-17 22:49:58 +00006238 Template = Specialization->getSpecializedTemplate();
6239 Arguments = Specialization->getTemplateArgs().data();
6240 } else if (const TemplateSpecializationType *TST =
6241 Ty->getAs<TemplateSpecializationType>()) {
6242 Template = dyn_cast_or_null<ClassTemplateDecl>(
6243 TST->getTemplateName().getAsTemplateDecl());
6244 Arguments = TST->getArgs();
6245 }
6246 if (!Template)
6247 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006248
6249 if (!StdInitializerList) {
6250 // Haven't recognized std::initializer_list yet, maybe this is it.
6251 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6252 if (TemplateClass->getIdentifier() !=
6253 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006254 !getStdNamespace()->InEnclosingNamespaceSetOf(
6255 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006256 return false;
6257 // This is a template called std::initializer_list, but is it the right
6258 // template?
6259 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006260 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006261 return false;
6262 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6263 return false;
6264
6265 // It's the right template.
6266 StdInitializerList = Template;
6267 }
6268
6269 if (Template != StdInitializerList)
6270 return false;
6271
6272 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006273 if (Element)
6274 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006275 return true;
6276}
6277
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006278static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6279 NamespaceDecl *Std = S.getStdNamespace();
6280 if (!Std) {
6281 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6282 return 0;
6283 }
6284
6285 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6286 Loc, Sema::LookupOrdinaryName);
6287 if (!S.LookupQualifiedName(Result, Std)) {
6288 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6289 return 0;
6290 }
6291 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6292 if (!Template) {
6293 Result.suppressDiagnostics();
6294 // We found something weird. Complain about the first thing we found.
6295 NamedDecl *Found = *Result.begin();
6296 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6297 return 0;
6298 }
6299
6300 // We found some template called std::initializer_list. Now verify that it's
6301 // correct.
6302 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006303 if (Params->getMinRequiredArguments() != 1 ||
6304 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006305 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6306 return 0;
6307 }
6308
6309 return Template;
6310}
6311
6312QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6313 if (!StdInitializerList) {
6314 StdInitializerList = LookupStdInitializerList(*this, Loc);
6315 if (!StdInitializerList)
6316 return QualType();
6317 }
6318
6319 TemplateArgumentListInfo Args(Loc, Loc);
6320 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6321 Context.getTrivialTypeSourceInfo(Element,
6322 Loc)));
6323 return Context.getCanonicalType(
6324 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6325}
6326
Sebastian Redl98d36062012-01-17 22:50:14 +00006327bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6328 // C++ [dcl.init.list]p2:
6329 // A constructor is an initializer-list constructor if its first parameter
6330 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6331 // std::initializer_list<E> for some type E, and either there are no other
6332 // parameters or else all other parameters have default arguments.
6333 if (Ctor->getNumParams() < 1 ||
6334 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6335 return false;
6336
6337 QualType ArgType = Ctor->getParamDecl(0)->getType();
6338 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6339 ArgType = RT->getPointeeType().getUnqualifiedType();
6340
6341 return isStdInitializerList(ArgType, 0);
6342}
6343
Douglas Gregor9172aa62011-03-26 22:25:30 +00006344/// \brief Determine whether a using statement is in a context where it will be
6345/// apply in all contexts.
6346static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6347 switch (CurContext->getDeclKind()) {
6348 case Decl::TranslationUnit:
6349 return true;
6350 case Decl::LinkageSpec:
6351 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6352 default:
6353 return false;
6354 }
6355}
6356
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006357namespace {
6358
6359// Callback to only accept typo corrections that are namespaces.
6360class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6361 public:
6362 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6363 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6364 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6365 }
6366 return false;
6367 }
6368};
6369
6370}
6371
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006372static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6373 CXXScopeSpec &SS,
6374 SourceLocation IdentLoc,
6375 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006376 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006377 R.clear();
6378 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006379 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006380 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006381 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6382 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006383 if (DeclContext *DC = S.computeDeclContext(SS, false))
6384 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6385 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006386 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6387 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006388 else
6389 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6390 << Ident << CorrectedQuotedStr
6391 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006392
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006393 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6394 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006395
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006396 R.addDecl(Corrected.getCorrectionDecl());
6397 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006398 }
6399 return false;
6400}
6401
John McCalld226f652010-08-21 09:40:31 +00006402Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006403 SourceLocation UsingLoc,
6404 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006405 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006406 SourceLocation IdentLoc,
6407 IdentifierInfo *NamespcName,
6408 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006409 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6410 assert(NamespcName && "Invalid NamespcName.");
6411 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006412
6413 // This can only happen along a recovery path.
6414 while (S->getFlags() & Scope::TemplateParamScope)
6415 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006416 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006417
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006418 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006419 NestedNameSpecifier *Qualifier = 0;
6420 if (SS.isSet())
6421 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6422
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006423 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006424 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6425 LookupParsedName(R, S, &SS);
6426 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006427 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006428
Douglas Gregor66992202010-06-29 17:53:46 +00006429 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006430 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006431 // Allow "using namespace std;" or "using namespace ::std;" even if
6432 // "std" hasn't been defined yet, for GCC compatibility.
6433 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6434 NamespcName->isStr("std")) {
6435 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006436 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006437 R.resolveKind();
6438 }
6439 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006440 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006441 }
6442
John McCallf36e02d2009-10-09 21:13:30 +00006443 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006444 NamedDecl *Named = R.getFoundDecl();
6445 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6446 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006447 // C++ [namespace.udir]p1:
6448 // A using-directive specifies that the names in the nominated
6449 // namespace can be used in the scope in which the
6450 // using-directive appears after the using-directive. During
6451 // unqualified name lookup (3.4.1), the names appear as if they
6452 // were declared in the nearest enclosing namespace which
6453 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006454 // namespace. [Note: in this context, "contains" means "contains
6455 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006456
6457 // Find enclosing context containing both using-directive and
6458 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006459 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006460 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6461 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6462 CommonAncestor = CommonAncestor->getParent();
6463
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006464 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006465 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006466 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006467
Douglas Gregor9172aa62011-03-26 22:25:30 +00006468 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006469 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006470 Diag(IdentLoc, diag::warn_using_directive_in_header);
6471 }
6472
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006473 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006474 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006475 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006476 }
6477
Richard Smith6b3d3e52013-02-20 19:22:51 +00006478 if (UDir)
6479 ProcessDeclAttributeList(S, UDir, AttrList);
6480
John McCalld226f652010-08-21 09:40:31 +00006481 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006482}
6483
6484void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006485 // If the scope has an associated entity and the using directive is at
6486 // namespace or translation unit scope, add the UsingDirectiveDecl into
6487 // its lookup structure so qualified name lookup can find it.
6488 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6489 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006490 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006491 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006492 // Otherwise, it is at block sope. The using-directives will affect lookup
6493 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006494 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006495}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006496
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006497
John McCalld226f652010-08-21 09:40:31 +00006498Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006499 AccessSpecifier AS,
6500 bool HasUsingKeyword,
6501 SourceLocation UsingLoc,
6502 CXXScopeSpec &SS,
6503 UnqualifiedId &Name,
6504 AttributeList *AttrList,
6505 bool IsTypeName,
6506 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006507 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006508
Douglas Gregor12c118a2009-11-04 16:30:06 +00006509 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006510 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006511 case UnqualifiedId::IK_Identifier:
6512 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006513 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006514 case UnqualifiedId::IK_ConversionFunctionId:
6515 break;
6516
6517 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006518 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006519 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006520 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006521 getLangOpts().CPlusPlus11 ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006522 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6523 // instead once inheriting constructors work.
6524 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006525 diag::err_using_decl_constructor)
6526 << SS.getRange();
6527
Richard Smith80ad52f2013-01-02 11:42:31 +00006528 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006529
John McCalld226f652010-08-21 09:40:31 +00006530 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006531
6532 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006533 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006534 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006535 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006536
6537 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006538 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006539 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006540 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006541 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006542
6543 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6544 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006545 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006546 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006547
John McCall60fa3cf2009-12-11 02:10:03 +00006548 // Warn about using declarations.
6549 // TODO: store that the declaration was written without 'using' and
6550 // talk about access decls instead of using decls in the
6551 // diagnostics.
6552 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006553 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006554
6555 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006556 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006557 }
6558
Douglas Gregor56c04582010-12-16 00:46:58 +00006559 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6560 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6561 return 0;
6562
John McCall9488ea12009-11-17 05:59:44 +00006563 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006564 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006565 /* IsInstantiation */ false,
6566 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006567 if (UD)
6568 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006569
John McCalld226f652010-08-21 09:40:31 +00006570 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006571}
6572
Douglas Gregor09acc982010-07-07 23:08:52 +00006573/// \brief Determine whether a using declaration considers the given
6574/// declarations as "equivalent", e.g., if they are redeclarations of
6575/// the same entity or are both typedefs of the same type.
6576static bool
6577IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6578 bool &SuppressRedeclaration) {
6579 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6580 SuppressRedeclaration = false;
6581 return true;
6582 }
6583
Richard Smith162e1c12011-04-15 14:24:37 +00006584 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6585 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006586 SuppressRedeclaration = true;
6587 return Context.hasSameType(TD1->getUnderlyingType(),
6588 TD2->getUnderlyingType());
6589 }
6590
6591 return false;
6592}
6593
6594
John McCall9f54ad42009-12-10 09:41:52 +00006595/// Determines whether to create a using shadow decl for a particular
6596/// decl, given the set of decls existing prior to this using lookup.
6597bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6598 const LookupResult &Previous) {
6599 // Diagnose finding a decl which is not from a base class of the
6600 // current class. We do this now because there are cases where this
6601 // function will silently decide not to build a shadow decl, which
6602 // will pre-empt further diagnostics.
6603 //
6604 // We don't need to do this in C++0x because we do the check once on
6605 // the qualifier.
6606 //
6607 // FIXME: diagnose the following if we care enough:
6608 // struct A { int foo; };
6609 // struct B : A { using A::foo; };
6610 // template <class T> struct C : A {};
6611 // template <class T> struct D : C<T> { using B::foo; } // <---
6612 // This is invalid (during instantiation) in C++03 because B::foo
6613 // resolves to the using decl in B, which is not a base class of D<T>.
6614 // We can't diagnose it immediately because C<T> is an unknown
6615 // specialization. The UsingShadowDecl in D<T> then points directly
6616 // to A::foo, which will look well-formed when we instantiate.
6617 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006618 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006619 DeclContext *OrigDC = Orig->getDeclContext();
6620
6621 // Handle enums and anonymous structs.
6622 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6623 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6624 while (OrigRec->isAnonymousStructOrUnion())
6625 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6626
6627 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6628 if (OrigDC == CurContext) {
6629 Diag(Using->getLocation(),
6630 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006631 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006632 Diag(Orig->getLocation(), diag::note_using_decl_target);
6633 return true;
6634 }
6635
Douglas Gregordc355712011-02-25 00:36:19 +00006636 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006637 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006638 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006639 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006640 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006641 Diag(Orig->getLocation(), diag::note_using_decl_target);
6642 return true;
6643 }
6644 }
6645
6646 if (Previous.empty()) return false;
6647
6648 NamedDecl *Target = Orig;
6649 if (isa<UsingShadowDecl>(Target))
6650 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6651
John McCalld7533ec2009-12-11 02:33:26 +00006652 // If the target happens to be one of the previous declarations, we
6653 // don't have a conflict.
6654 //
6655 // FIXME: but we might be increasing its access, in which case we
6656 // should redeclare it.
6657 NamedDecl *NonTag = 0, *Tag = 0;
6658 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6659 I != E; ++I) {
6660 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006661 bool Result;
6662 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6663 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006664
6665 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6666 }
6667
John McCall9f54ad42009-12-10 09:41:52 +00006668 if (Target->isFunctionOrFunctionTemplate()) {
6669 FunctionDecl *FD;
6670 if (isa<FunctionTemplateDecl>(Target))
6671 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6672 else
6673 FD = cast<FunctionDecl>(Target);
6674
6675 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006676 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006677 case Ovl_Overload:
6678 return false;
6679
6680 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006681 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006682 break;
6683
6684 // We found a decl with the exact signature.
6685 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006686 // If we're in a record, we want to hide the target, so we
6687 // return true (without a diagnostic) to tell the caller not to
6688 // build a shadow decl.
6689 if (CurContext->isRecord())
6690 return true;
6691
6692 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006693 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006694 break;
6695 }
6696
6697 Diag(Target->getLocation(), diag::note_using_decl_target);
6698 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6699 return true;
6700 }
6701
6702 // Target is not a function.
6703
John McCall9f54ad42009-12-10 09:41:52 +00006704 if (isa<TagDecl>(Target)) {
6705 // No conflict between a tag and a non-tag.
6706 if (!Tag) return false;
6707
John McCall41ce66f2009-12-10 19:51:03 +00006708 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006709 Diag(Target->getLocation(), diag::note_using_decl_target);
6710 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6711 return true;
6712 }
6713
6714 // No conflict between a tag and a non-tag.
6715 if (!NonTag) return false;
6716
John McCall41ce66f2009-12-10 19:51:03 +00006717 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006718 Diag(Target->getLocation(), diag::note_using_decl_target);
6719 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6720 return true;
6721}
6722
John McCall9488ea12009-11-17 05:59:44 +00006723/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006724UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006725 UsingDecl *UD,
6726 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006727
6728 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006729 NamedDecl *Target = Orig;
6730 if (isa<UsingShadowDecl>(Target)) {
6731 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6732 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006733 }
6734
6735 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006736 = UsingShadowDecl::Create(Context, CurContext,
6737 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006738 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006739
6740 Shadow->setAccess(UD->getAccess());
6741 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6742 Shadow->setInvalidDecl();
6743
John McCall9488ea12009-11-17 05:59:44 +00006744 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006745 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006746 else
John McCall604e7f12009-12-08 07:46:18 +00006747 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006748
John McCall604e7f12009-12-08 07:46:18 +00006749
John McCall9f54ad42009-12-10 09:41:52 +00006750 return Shadow;
6751}
John McCall604e7f12009-12-08 07:46:18 +00006752
John McCall9f54ad42009-12-10 09:41:52 +00006753/// Hides a using shadow declaration. This is required by the current
6754/// using-decl implementation when a resolvable using declaration in a
6755/// class is followed by a declaration which would hide or override
6756/// one or more of the using decl's targets; for example:
6757///
6758/// struct Base { void foo(int); };
6759/// struct Derived : Base {
6760/// using Base::foo;
6761/// void foo(int);
6762/// };
6763///
6764/// The governing language is C++03 [namespace.udecl]p12:
6765///
6766/// When a using-declaration brings names from a base class into a
6767/// derived class scope, member functions in the derived class
6768/// override and/or hide member functions with the same name and
6769/// parameter types in a base class (rather than conflicting).
6770///
6771/// There are two ways to implement this:
6772/// (1) optimistically create shadow decls when they're not hidden
6773/// by existing declarations, or
6774/// (2) don't create any shadow decls (or at least don't make them
6775/// visible) until we've fully parsed/instantiated the class.
6776/// The problem with (1) is that we might have to retroactively remove
6777/// a shadow decl, which requires several O(n) operations because the
6778/// decl structures are (very reasonably) not designed for removal.
6779/// (2) avoids this but is very fiddly and phase-dependent.
6780void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006781 if (Shadow->getDeclName().getNameKind() ==
6782 DeclarationName::CXXConversionFunctionName)
6783 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6784
John McCall9f54ad42009-12-10 09:41:52 +00006785 // Remove it from the DeclContext...
6786 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006787
John McCall9f54ad42009-12-10 09:41:52 +00006788 // ...and the scope, if applicable...
6789 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006790 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006791 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006792 }
6793
John McCall9f54ad42009-12-10 09:41:52 +00006794 // ...and the using decl.
6795 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6796
6797 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006798 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006799}
6800
John McCall7ba107a2009-11-18 02:36:19 +00006801/// Builds a using declaration.
6802///
6803/// \param IsInstantiation - Whether this call arises from an
6804/// instantiation of an unresolved using declaration. We treat
6805/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006806NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6807 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006808 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006809 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006810 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006811 bool IsInstantiation,
6812 bool IsTypeName,
6813 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006814 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006815 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006816 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006817
Anders Carlsson550b14b2009-08-28 05:49:21 +00006818 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006819
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006820 if (SS.isEmpty()) {
6821 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006822 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006823 }
Mike Stump1eb44332009-09-09 15:08:12 +00006824
John McCall9f54ad42009-12-10 09:41:52 +00006825 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006826 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006827 ForRedeclaration);
6828 Previous.setHideTags(false);
6829 if (S) {
6830 LookupName(Previous, S);
6831
6832 // It is really dumb that we have to do this.
6833 LookupResult::Filter F = Previous.makeFilter();
6834 while (F.hasNext()) {
6835 NamedDecl *D = F.next();
6836 if (!isDeclInScope(D, CurContext, S))
6837 F.erase();
6838 }
6839 F.done();
6840 } else {
6841 assert(IsInstantiation && "no scope in non-instantiation");
6842 assert(CurContext->isRecord() && "scope not record in instantiation");
6843 LookupQualifiedName(Previous, CurContext);
6844 }
6845
John McCall9f54ad42009-12-10 09:41:52 +00006846 // Check for invalid redeclarations.
6847 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6848 return 0;
6849
6850 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006851 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6852 return 0;
6853
John McCallaf8e6ed2009-11-12 03:15:40 +00006854 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006855 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006856 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006857 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006858 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006859 // FIXME: not all declaration name kinds are legal here
6860 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6861 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006862 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006863 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006864 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006865 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6866 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006867 }
John McCalled976492009-12-04 22:46:56 +00006868 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006869 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6870 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006871 }
John McCalled976492009-12-04 22:46:56 +00006872 D->setAccess(AS);
6873 CurContext->addDecl(D);
6874
6875 if (!LookupContext) return D;
6876 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006877
John McCall77bb1aa2010-05-01 00:40:08 +00006878 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006879 UD->setInvalidDecl();
6880 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006881 }
6882
Richard Smithc5a89a12012-04-02 01:30:27 +00006883 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006884 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006885 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006886 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006887 return UD;
6888 }
6889
6890 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006891
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006892 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006893
John McCall604e7f12009-12-08 07:46:18 +00006894 // Unlike most lookups, we don't always want to hide tag
6895 // declarations: tag names are visible through the using declaration
6896 // even if hidden by ordinary names, *except* in a dependent context
6897 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006898 if (!IsInstantiation)
6899 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006900
John McCallb9abd8722012-04-07 03:04:20 +00006901 // For the purposes of this lookup, we have a base object type
6902 // equal to that of the current context.
6903 if (CurContext->isRecord()) {
6904 R.setBaseObjectType(
6905 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6906 }
6907
John McCalla24dc2e2009-11-17 02:14:36 +00006908 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006909
John McCallf36e02d2009-10-09 21:13:30 +00006910 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006911 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006912 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006913 UD->setInvalidDecl();
6914 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006915 }
6916
John McCalled976492009-12-04 22:46:56 +00006917 if (R.isAmbiguous()) {
6918 UD->setInvalidDecl();
6919 return UD;
6920 }
Mike Stump1eb44332009-09-09 15:08:12 +00006921
John McCall7ba107a2009-11-18 02:36:19 +00006922 if (IsTypeName) {
6923 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006924 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006925 Diag(IdentLoc, diag::err_using_typename_non_type);
6926 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6927 Diag((*I)->getUnderlyingDecl()->getLocation(),
6928 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006929 UD->setInvalidDecl();
6930 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006931 }
6932 } else {
6933 // If we asked for a non-typename and we got a type, error out,
6934 // but only if this is an instantiation of an unresolved using
6935 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006936 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006937 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6938 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006939 UD->setInvalidDecl();
6940 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006941 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006942 }
6943
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006944 // C++0x N2914 [namespace.udecl]p6:
6945 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006946 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006947 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6948 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006949 UD->setInvalidDecl();
6950 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006951 }
Mike Stump1eb44332009-09-09 15:08:12 +00006952
John McCall9f54ad42009-12-10 09:41:52 +00006953 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6954 if (!CheckUsingShadowDecl(UD, *I, Previous))
6955 BuildUsingShadowDecl(S, UD, *I);
6956 }
John McCall9488ea12009-11-17 05:59:44 +00006957
6958 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006959}
6960
Sebastian Redlf677ea32011-02-05 19:23:19 +00006961/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006962bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6963 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006964
Douglas Gregordc355712011-02-25 00:36:19 +00006965 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006966 assert(SourceType &&
6967 "Using decl naming constructor doesn't have type in scope spec.");
6968 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6969
6970 // Check whether the named type is a direct base class.
6971 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6972 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6973 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6974 BaseIt != BaseE; ++BaseIt) {
6975 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6976 if (CanonicalSourceType == BaseType)
6977 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006978 if (BaseIt->getType()->isDependentType())
6979 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006980 }
6981
6982 if (BaseIt == BaseE) {
6983 // Did not find SourceType in the bases.
6984 Diag(UD->getUsingLocation(),
6985 diag::err_using_decl_constructor_not_in_direct_base)
6986 << UD->getNameInfo().getSourceRange()
6987 << QualType(SourceType, 0) << TargetClass;
6988 return true;
6989 }
6990
Richard Smithc5a89a12012-04-02 01:30:27 +00006991 if (!CurContext->isDependentContext())
6992 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006993
6994 return false;
6995}
6996
John McCall9f54ad42009-12-10 09:41:52 +00006997/// Checks that the given using declaration is not an invalid
6998/// redeclaration. Note that this is checking only for the using decl
6999/// itself, not for any ill-formedness among the UsingShadowDecls.
7000bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7001 bool isTypeName,
7002 const CXXScopeSpec &SS,
7003 SourceLocation NameLoc,
7004 const LookupResult &Prev) {
7005 // C++03 [namespace.udecl]p8:
7006 // C++0x [namespace.udecl]p10:
7007 // A using-declaration is a declaration and can therefore be used
7008 // repeatedly where (and only where) multiple declarations are
7009 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007010 //
John McCall8a726212010-11-29 18:01:58 +00007011 // That's in non-member contexts.
7012 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007013 return false;
7014
7015 NestedNameSpecifier *Qual
7016 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7017
7018 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7019 NamedDecl *D = *I;
7020
7021 bool DTypename;
7022 NestedNameSpecifier *DQual;
7023 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7024 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00007025 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007026 } else if (UnresolvedUsingValueDecl *UD
7027 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7028 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007029 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007030 } else if (UnresolvedUsingTypenameDecl *UD
7031 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7032 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007033 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007034 } else continue;
7035
7036 // using decls differ if one says 'typename' and the other doesn't.
7037 // FIXME: non-dependent using decls?
7038 if (isTypeName != DTypename) continue;
7039
7040 // using decls differ if they name different scopes (but note that
7041 // template instantiation can cause this check to trigger when it
7042 // didn't before instantiation).
7043 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7044 Context.getCanonicalNestedNameSpecifier(DQual))
7045 continue;
7046
7047 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007048 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007049 return true;
7050 }
7051
7052 return false;
7053}
7054
John McCall604e7f12009-12-08 07:46:18 +00007055
John McCalled976492009-12-04 22:46:56 +00007056/// Checks that the given nested-name qualifier used in a using decl
7057/// in the current context is appropriately related to the current
7058/// scope. If an error is found, diagnoses it and returns true.
7059bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7060 const CXXScopeSpec &SS,
7061 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007062 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007063
John McCall604e7f12009-12-08 07:46:18 +00007064 if (!CurContext->isRecord()) {
7065 // C++03 [namespace.udecl]p3:
7066 // C++0x [namespace.udecl]p8:
7067 // A using-declaration for a class member shall be a member-declaration.
7068
7069 // If we weren't able to compute a valid scope, it must be a
7070 // dependent class scope.
7071 if (!NamedContext || NamedContext->isRecord()) {
7072 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7073 << SS.getRange();
7074 return true;
7075 }
7076
7077 // Otherwise, everything is known to be fine.
7078 return false;
7079 }
7080
7081 // The current scope is a record.
7082
7083 // If the named context is dependent, we can't decide much.
7084 if (!NamedContext) {
7085 // FIXME: in C++0x, we can diagnose if we can prove that the
7086 // nested-name-specifier does not refer to a base class, which is
7087 // still possible in some cases.
7088
7089 // Otherwise we have to conservatively report that things might be
7090 // okay.
7091 return false;
7092 }
7093
7094 if (!NamedContext->isRecord()) {
7095 // Ideally this would point at the last name in the specifier,
7096 // but we don't have that level of source info.
7097 Diag(SS.getRange().getBegin(),
7098 diag::err_using_decl_nested_name_specifier_is_not_class)
7099 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7100 return true;
7101 }
7102
Douglas Gregor6fb07292010-12-21 07:41:49 +00007103 if (!NamedContext->isDependentContext() &&
7104 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7105 return true;
7106
Richard Smith80ad52f2013-01-02 11:42:31 +00007107 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007108 // C++0x [namespace.udecl]p3:
7109 // In a using-declaration used as a member-declaration, the
7110 // nested-name-specifier shall name a base class of the class
7111 // being defined.
7112
7113 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7114 cast<CXXRecordDecl>(NamedContext))) {
7115 if (CurContext == NamedContext) {
7116 Diag(NameLoc,
7117 diag::err_using_decl_nested_name_specifier_is_current_class)
7118 << SS.getRange();
7119 return true;
7120 }
7121
7122 Diag(SS.getRange().getBegin(),
7123 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7124 << (NestedNameSpecifier*) SS.getScopeRep()
7125 << cast<CXXRecordDecl>(CurContext)
7126 << SS.getRange();
7127 return true;
7128 }
7129
7130 return false;
7131 }
7132
7133 // C++03 [namespace.udecl]p4:
7134 // A using-declaration used as a member-declaration shall refer
7135 // to a member of a base class of the class being defined [etc.].
7136
7137 // Salient point: SS doesn't have to name a base class as long as
7138 // lookup only finds members from base classes. Therefore we can
7139 // diagnose here only if we can prove that that can't happen,
7140 // i.e. if the class hierarchies provably don't intersect.
7141
7142 // TODO: it would be nice if "definitely valid" results were cached
7143 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7144 // need to be repeated.
7145
7146 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007147 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007148
7149 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7150 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7151 Data->Bases.insert(Base);
7152 return true;
7153 }
7154
7155 bool hasDependentBases(const CXXRecordDecl *Class) {
7156 return !Class->forallBases(collect, this);
7157 }
7158
7159 /// Returns true if the base is dependent or is one of the
7160 /// accumulated base classes.
7161 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7162 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7163 return !Data->Bases.count(Base);
7164 }
7165
7166 bool mightShareBases(const CXXRecordDecl *Class) {
7167 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7168 }
7169 };
7170
7171 UserData Data;
7172
7173 // Returns false if we find a dependent base.
7174 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7175 return false;
7176
7177 // Returns false if the class has a dependent base or if it or one
7178 // of its bases is present in the base set of the current context.
7179 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7180 return false;
7181
7182 Diag(SS.getRange().getBegin(),
7183 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7184 << (NestedNameSpecifier*) SS.getScopeRep()
7185 << cast<CXXRecordDecl>(CurContext)
7186 << SS.getRange();
7187
7188 return true;
John McCalled976492009-12-04 22:46:56 +00007189}
7190
Richard Smith162e1c12011-04-15 14:24:37 +00007191Decl *Sema::ActOnAliasDeclaration(Scope *S,
7192 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007193 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007194 SourceLocation UsingLoc,
7195 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007196 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007197 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007198 // Skip up to the relevant declaration scope.
7199 while (S->getFlags() & Scope::TemplateParamScope)
7200 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007201 assert((S->getFlags() & Scope::DeclScope) &&
7202 "got alias-declaration outside of declaration scope");
7203
7204 if (Type.isInvalid())
7205 return 0;
7206
7207 bool Invalid = false;
7208 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7209 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007210 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007211
7212 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7213 return 0;
7214
7215 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007216 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007217 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007218 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7219 TInfo->getTypeLoc().getBeginLoc());
7220 }
Richard Smith162e1c12011-04-15 14:24:37 +00007221
7222 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7223 LookupName(Previous, S);
7224
7225 // Warn about shadowing the name of a template parameter.
7226 if (Previous.isSingleResult() &&
7227 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007228 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007229 Previous.clear();
7230 }
7231
7232 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7233 "name in alias declaration must be an identifier");
7234 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7235 Name.StartLocation,
7236 Name.Identifier, TInfo);
7237
7238 NewTD->setAccess(AS);
7239
7240 if (Invalid)
7241 NewTD->setInvalidDecl();
7242
Richard Smith6b3d3e52013-02-20 19:22:51 +00007243 ProcessDeclAttributeList(S, NewTD, AttrList);
7244
Richard Smith3e4c6c42011-05-05 21:57:07 +00007245 CheckTypedefForVariablyModifiedType(S, NewTD);
7246 Invalid |= NewTD->isInvalidDecl();
7247
Richard Smith162e1c12011-04-15 14:24:37 +00007248 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007249
7250 NamedDecl *NewND;
7251 if (TemplateParamLists.size()) {
7252 TypeAliasTemplateDecl *OldDecl = 0;
7253 TemplateParameterList *OldTemplateParams = 0;
7254
7255 if (TemplateParamLists.size() != 1) {
7256 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007257 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7258 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007259 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007260 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007261
7262 // Only consider previous declarations in the same scope.
7263 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7264 /*ExplicitInstantiationOrSpecialization*/false);
7265 if (!Previous.empty()) {
7266 Redeclaration = true;
7267
7268 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7269 if (!OldDecl && !Invalid) {
7270 Diag(UsingLoc, diag::err_redefinition_different_kind)
7271 << Name.Identifier;
7272
7273 NamedDecl *OldD = Previous.getRepresentativeDecl();
7274 if (OldD->getLocation().isValid())
7275 Diag(OldD->getLocation(), diag::note_previous_definition);
7276
7277 Invalid = true;
7278 }
7279
7280 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7281 if (TemplateParameterListsAreEqual(TemplateParams,
7282 OldDecl->getTemplateParameters(),
7283 /*Complain=*/true,
7284 TPL_TemplateMatch))
7285 OldTemplateParams = OldDecl->getTemplateParameters();
7286 else
7287 Invalid = true;
7288
7289 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7290 if (!Invalid &&
7291 !Context.hasSameType(OldTD->getUnderlyingType(),
7292 NewTD->getUnderlyingType())) {
7293 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7294 // but we can't reasonably accept it.
7295 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7296 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7297 if (OldTD->getLocation().isValid())
7298 Diag(OldTD->getLocation(), diag::note_previous_definition);
7299 Invalid = true;
7300 }
7301 }
7302 }
7303
7304 // Merge any previous default template arguments into our parameters,
7305 // and check the parameter list.
7306 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7307 TPC_TypeAliasTemplate))
7308 return 0;
7309
7310 TypeAliasTemplateDecl *NewDecl =
7311 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7312 Name.Identifier, TemplateParams,
7313 NewTD);
7314
7315 NewDecl->setAccess(AS);
7316
7317 if (Invalid)
7318 NewDecl->setInvalidDecl();
7319 else if (OldDecl)
7320 NewDecl->setPreviousDeclaration(OldDecl);
7321
7322 NewND = NewDecl;
7323 } else {
7324 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7325 NewND = NewTD;
7326 }
Richard Smith162e1c12011-04-15 14:24:37 +00007327
7328 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007329 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007330
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007331 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007332 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007333}
7334
John McCalld226f652010-08-21 09:40:31 +00007335Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007336 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007337 SourceLocation AliasLoc,
7338 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007339 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007340 SourceLocation IdentLoc,
7341 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007342
Anders Carlsson81c85c42009-03-28 23:53:49 +00007343 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007344 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7345 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007346
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007347 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007348 NamedDecl *PrevDecl
7349 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7350 ForRedeclaration);
7351 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7352 PrevDecl = 0;
7353
7354 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007355 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007356 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007357 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007358 // FIXME: At some point, we'll want to create the (redundant)
7359 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007360 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007361 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007362 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007363 }
Mike Stump1eb44332009-09-09 15:08:12 +00007364
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007365 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7366 diag::err_redefinition_different_kind;
7367 Diag(AliasLoc, DiagID) << Alias;
7368 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007369 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007370 }
7371
John McCalla24dc2e2009-11-17 02:14:36 +00007372 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007373 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007374
John McCallf36e02d2009-10-09 21:13:30 +00007375 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007376 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007377 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007378 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007379 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007380 }
Mike Stump1eb44332009-09-09 15:08:12 +00007381
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007382 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007383 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007384 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007385 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007386
John McCall3dbd3d52010-02-16 06:53:13 +00007387 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007388 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007389}
7390
Sean Hunt001cad92011-05-10 00:49:42 +00007391Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007392Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7393 CXXMethodDecl *MD) {
7394 CXXRecordDecl *ClassDecl = MD->getParent();
7395
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007396 // C++ [except.spec]p14:
7397 // An implicitly declared special member function (Clause 12) shall have an
7398 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007399 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007400 if (ClassDecl->isInvalidDecl())
7401 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007402
Sebastian Redl60618fa2011-03-12 11:50:43 +00007403 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007404 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7405 BEnd = ClassDecl->bases_end();
7406 B != BEnd; ++B) {
7407 if (B->isVirtual()) // Handled below.
7408 continue;
7409
Douglas Gregor18274032010-07-03 00:47:00 +00007410 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7411 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007412 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7413 // If this is a deleted function, add it anyway. This might be conformant
7414 // with the standard. This might not. I'm not sure. It might not matter.
7415 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007416 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007417 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007418 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007419
7420 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007421 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7422 BEnd = ClassDecl->vbases_end();
7423 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007424 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7425 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007426 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7427 // If this is a deleted function, add it anyway. This might be conformant
7428 // with the standard. This might not. I'm not sure. It might not matter.
7429 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007430 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007431 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007432 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007433
7434 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007435 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7436 FEnd = ClassDecl->field_end();
7437 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007438 if (F->hasInClassInitializer()) {
7439 if (Expr *E = F->getInClassInitializer())
7440 ExceptSpec.CalledExpr(E);
7441 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007442 // DR1351:
7443 // If the brace-or-equal-initializer of a non-static data member
7444 // invokes a defaulted default constructor of its class or of an
7445 // enclosing class in a potentially evaluated subexpression, the
7446 // program is ill-formed.
7447 //
7448 // This resolution is unworkable: the exception specification of the
7449 // default constructor can be needed in an unevaluated context, in
7450 // particular, in the operand of a noexcept-expression, and we can be
7451 // unable to compute an exception specification for an enclosed class.
7452 //
7453 // We do not allow an in-class initializer to require the evaluation
7454 // of the exception specification for any in-class initializer whose
7455 // definition is not lexically complete.
7456 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007457 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007458 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007459 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7460 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7461 // If this is a deleted function, add it anyway. This might be conformant
7462 // with the standard. This might not. I'm not sure. It might not matter.
7463 // In particular, the problem is that this function never gets called. It
7464 // might just be ill-formed because this function attempts to refer to
7465 // a deleted function here.
7466 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007467 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007468 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007469 }
John McCalle23cf432010-12-14 08:05:40 +00007470
Sean Hunt001cad92011-05-10 00:49:42 +00007471 return ExceptSpec;
7472}
7473
Richard Smithafb49182012-11-29 01:34:07 +00007474namespace {
7475/// RAII object to register a special member as being currently declared.
7476struct DeclaringSpecialMember {
7477 Sema &S;
7478 Sema::SpecialMemberDecl D;
7479 bool WasAlreadyBeingDeclared;
7480
7481 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7482 : S(S), D(RD, CSM) {
7483 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7484 if (WasAlreadyBeingDeclared)
7485 // This almost never happens, but if it does, ensure that our cache
7486 // doesn't contain a stale result.
7487 S.SpecialMemberCache.clear();
7488
7489 // FIXME: Register a note to be produced if we encounter an error while
7490 // declaring the special member.
7491 }
7492 ~DeclaringSpecialMember() {
7493 if (!WasAlreadyBeingDeclared)
7494 S.SpecialMembersBeingDeclared.erase(D);
7495 }
7496
7497 /// \brief Are we already trying to declare this special member?
7498 bool isAlreadyBeingDeclared() const {
7499 return WasAlreadyBeingDeclared;
7500 }
7501};
7502}
7503
Sean Hunt001cad92011-05-10 00:49:42 +00007504CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7505 CXXRecordDecl *ClassDecl) {
7506 // C++ [class.ctor]p5:
7507 // A default constructor for a class X is a constructor of class X
7508 // that can be called without an argument. If there is no
7509 // user-declared constructor for class X, a default constructor is
7510 // implicitly declared. An implicitly-declared default constructor
7511 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007512 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007513 "Should not build implicit default constructor!");
7514
Richard Smithafb49182012-11-29 01:34:07 +00007515 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7516 if (DSM.isAlreadyBeingDeclared())
7517 return 0;
7518
Richard Smith7756afa2012-06-10 05:43:50 +00007519 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7520 CXXDefaultConstructor,
7521 false);
7522
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007523 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007524 CanQualType ClassType
7525 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007526 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007527 DeclarationName Name
7528 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007529 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007530 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007531 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007532 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007533 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007534 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007535 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007536 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007537
7538 // Build an exception specification pointing back at this constructor.
7539 FunctionProtoType::ExtProtoInfo EPI;
7540 EPI.ExceptionSpecType = EST_Unevaluated;
7541 EPI.ExceptionSpecDecl = DefaultCon;
Jordan Rosebea522f2013-03-08 21:51:21 +00007542 DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7543 ArrayRef<QualType>(),
7544 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007545
Richard Smithbc2a35d2012-12-08 08:32:28 +00007546 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7547 // constructors is easy to compute.
7548 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7549
7550 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7551 DefaultCon->setDeletedAsWritten();
7552
Douglas Gregor18274032010-07-03 00:47:00 +00007553 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007554 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007555
Douglas Gregor23c94db2010-07-02 17:43:08 +00007556 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007557 PushOnScopeChains(DefaultCon, S, false);
7558 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007559
Douglas Gregor32df23e2010-07-01 22:02:46 +00007560 return DefaultCon;
7561}
7562
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007563void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7564 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007565 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007566 !Constructor->doesThisDeclarationHaveABody() &&
7567 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007568 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007569
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007570 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007571 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007572
Eli Friedman9a14db32012-10-18 20:14:08 +00007573 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007574 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007575 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007576 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007577 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007578 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007579 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007580 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007581 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007582
7583 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007584 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007585
7586 Constructor->setUsed();
7587 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007588
7589 if (ASTMutationListener *L = getASTMutationListener()) {
7590 L->CompletedImplicitDefinition(Constructor);
7591 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007592}
7593
Richard Smith7a614d82011-06-11 17:19:42 +00007594void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007595 // Check that any explicitly-defaulted methods have exception specifications
7596 // compatible with their implicit exception specifications.
7597 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007598}
7599
Sebastian Redlf677ea32011-02-05 19:23:19 +00007600void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7601 // We start with an initial pass over the base classes to collect those that
7602 // inherit constructors from. If there are none, we can forgo all further
7603 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007604 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007605 BasesVector BasesToInheritFrom;
7606 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7607 BaseE = ClassDecl->bases_end();
7608 BaseIt != BaseE; ++BaseIt) {
7609 if (BaseIt->getInheritConstructors()) {
7610 QualType Base = BaseIt->getType();
7611 if (Base->isDependentType()) {
7612 // If we inherit constructors from anything that is dependent, just
7613 // abort processing altogether. We'll get another chance for the
7614 // instantiations.
7615 return;
7616 }
7617 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7618 }
7619 }
7620 if (BasesToInheritFrom.empty())
7621 return;
7622
7623 // Now collect the constructors that we already have in the current class.
7624 // Those take precedence over inherited constructors.
7625 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7626 // unless there is a user-declared constructor with the same signature in
7627 // the class where the using-declaration appears.
7628 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7629 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7630 CtorE = ClassDecl->ctor_end();
7631 CtorIt != CtorE; ++CtorIt) {
7632 ExistingConstructors.insert(
7633 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7634 }
7635
Sebastian Redlf677ea32011-02-05 19:23:19 +00007636 DeclarationName CreatedCtorName =
7637 Context.DeclarationNames.getCXXConstructorName(
7638 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7639
7640 // Now comes the true work.
7641 // First, we keep a map from constructor types to the base that introduced
7642 // them. Needed for finding conflicting constructors. We also keep the
7643 // actually inserted declarations in there, for pretty diagnostics.
7644 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7645 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7646 ConstructorToSourceMap InheritedConstructors;
7647 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7648 BaseE = BasesToInheritFrom.end();
7649 BaseIt != BaseE; ++BaseIt) {
7650 const RecordType *Base = *BaseIt;
7651 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7652 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7653 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7654 CtorE = BaseDecl->ctor_end();
7655 CtorIt != CtorE; ++CtorIt) {
7656 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007657 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007658 DeclarationName Name =
7659 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007660 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7661 LookupQualifiedName(Result, CurContext);
7662 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007663 SourceLocation UsingLoc = UD ? UD->getLocation() :
7664 ClassDecl->getLocation();
7665
7666 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7667 // from the class X named in the using-declaration consists of actual
7668 // constructors and notional constructors that result from the
7669 // transformation of defaulted parameters as follows:
7670 // - all non-template default constructors of X, and
7671 // - for each non-template constructor of X that has at least one
7672 // parameter with a default argument, the set of constructors that
7673 // results from omitting any ellipsis parameter specification and
7674 // successively omitting parameters with a default argument from the
7675 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007676 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007677 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7678 const FunctionProtoType *BaseCtorType =
7679 BaseCtor->getType()->getAs<FunctionProtoType>();
7680
7681 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7682 maxParams = BaseCtor->getNumParams();
7683 params <= maxParams; ++params) {
7684 // Skip default constructors. They're never inherited.
7685 if (params == 0)
7686 continue;
7687 // Skip copy and move constructors for the same reason.
7688 if (CanBeCopyOrMove && params == 1)
7689 continue;
7690
7691 // Build up a function type for this particular constructor.
7692 // FIXME: The working paper does not consider that the exception spec
7693 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007694 // source. This code doesn't yet, either. When it does, this code will
7695 // need to be delayed until after exception specifications and in-class
7696 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007697 const Type *NewCtorType;
7698 if (params == maxParams)
7699 NewCtorType = BaseCtorType;
7700 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007701 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007702 for (unsigned i = 0; i < params; ++i) {
7703 Args.push_back(BaseCtorType->getArgType(i));
7704 }
7705 FunctionProtoType::ExtProtoInfo ExtInfo =
7706 BaseCtorType->getExtProtoInfo();
7707 ExtInfo.Variadic = false;
7708 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00007709 Args, ExtInfo)
Sebastian Redlf677ea32011-02-05 19:23:19 +00007710 .getTypePtr();
7711 }
7712 const Type *CanonicalNewCtorType =
7713 Context.getCanonicalType(NewCtorType);
7714
7715 // Now that we have the type, first check if the class already has a
7716 // constructor with this signature.
7717 if (ExistingConstructors.count(CanonicalNewCtorType))
7718 continue;
7719
7720 // Then we check if we have already declared an inherited constructor
7721 // with this signature.
7722 std::pair<ConstructorToSourceMap::iterator, bool> result =
7723 InheritedConstructors.insert(std::make_pair(
7724 CanonicalNewCtorType,
7725 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7726 if (!result.second) {
7727 // Already in the map. If it came from a different class, that's an
7728 // error. Not if it's from the same.
7729 CanQualType PreviousBase = result.first->second.first;
7730 if (CanonicalBase != PreviousBase) {
7731 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7732 const CXXConstructorDecl *PrevBaseCtor =
7733 PrevCtor->getInheritedConstructor();
7734 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7735
7736 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7737 Diag(BaseCtor->getLocation(),
7738 diag::note_using_decl_constructor_conflict_current_ctor);
7739 Diag(PrevBaseCtor->getLocation(),
7740 diag::note_using_decl_constructor_conflict_previous_ctor);
7741 Diag(PrevCtor->getLocation(),
7742 diag::note_using_decl_constructor_conflict_previous_using);
7743 }
7744 continue;
7745 }
7746
7747 // OK, we're there, now add the constructor.
7748 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007749 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007750 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7751 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007752 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7753 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007754 /*ImplicitlyDeclared=*/true,
7755 // FIXME: Due to a defect in the standard, we treat inherited
7756 // constructors as constexpr even if that makes them ill-formed.
7757 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007758 NewCtor->setAccess(BaseCtor->getAccess());
7759
7760 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007761 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007762 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007763 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7764 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007765 /*IdentifierInfo=*/0,
7766 BaseCtorType->getArgType(i),
7767 /*TInfo=*/0, SC_None,
7768 SC_None, /*DefaultArg=*/0));
7769 }
David Blaikie4278c652011-09-21 18:16:56 +00007770 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007771 NewCtor->setInheritedConstructor(BaseCtor);
7772
Sebastian Redlf677ea32011-02-05 19:23:19 +00007773 ClassDecl->addDecl(NewCtor);
7774 result.first->second.second = NewCtor;
7775 }
7776 }
7777 }
7778}
7779
Sean Huntcb45a0f2011-05-12 22:46:25 +00007780Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007781Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7782 CXXRecordDecl *ClassDecl = MD->getParent();
7783
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007784 // C++ [except.spec]p14:
7785 // An implicitly declared special member function (Clause 12) shall have
7786 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007787 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007788 if (ClassDecl->isInvalidDecl())
7789 return ExceptSpec;
7790
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007791 // Direct base-class destructors.
7792 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7793 BEnd = ClassDecl->bases_end();
7794 B != BEnd; ++B) {
7795 if (B->isVirtual()) // Handled below.
7796 continue;
7797
7798 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007799 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007800 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007801 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007802
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007803 // Virtual base-class destructors.
7804 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7805 BEnd = ClassDecl->vbases_end();
7806 B != BEnd; ++B) {
7807 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007808 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007809 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007810 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007811
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007812 // Field destructors.
7813 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7814 FEnd = ClassDecl->field_end();
7815 F != FEnd; ++F) {
7816 if (const RecordType *RecordTy
7817 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007818 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007819 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007820 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007821
Sean Huntcb45a0f2011-05-12 22:46:25 +00007822 return ExceptSpec;
7823}
7824
7825CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7826 // C++ [class.dtor]p2:
7827 // If a class has no user-declared destructor, a destructor is
7828 // declared implicitly. An implicitly-declared destructor is an
7829 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007830 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007831
Richard Smithafb49182012-11-29 01:34:07 +00007832 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7833 if (DSM.isAlreadyBeingDeclared())
7834 return 0;
7835
Douglas Gregor4923aa22010-07-02 20:37:36 +00007836 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007837 CanQualType ClassType
7838 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007839 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007840 DeclarationName Name
7841 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007842 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007843 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007844 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7845 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007846 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007847 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007848 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007849 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007850
7851 // Build an exception specification pointing back at this destructor.
7852 FunctionProtoType::ExtProtoInfo EPI;
7853 EPI.ExceptionSpecType = EST_Unevaluated;
7854 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00007855 Destructor->setType(Context.getFunctionType(Context.VoidTy,
7856 ArrayRef<QualType>(),
7857 EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007858
Richard Smithbc2a35d2012-12-08 08:32:28 +00007859 AddOverriddenMethods(ClassDecl, Destructor);
7860
7861 // We don't need to use SpecialMemberIsTrivial here; triviality for
7862 // destructors is easy to compute.
7863 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7864
7865 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7866 Destructor->setDeletedAsWritten();
7867
Douglas Gregor4923aa22010-07-02 20:37:36 +00007868 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007869 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007870
Douglas Gregor4923aa22010-07-02 20:37:36 +00007871 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007872 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007873 PushOnScopeChains(Destructor, S, false);
7874 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007875
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007876 return Destructor;
7877}
7878
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007879void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007880 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007881 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007882 !Destructor->doesThisDeclarationHaveABody() &&
7883 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007884 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007885 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007886 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007887
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007888 if (Destructor->isInvalidDecl())
7889 return;
7890
Eli Friedman9a14db32012-10-18 20:14:08 +00007891 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007892
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007893 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007894 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7895 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007896
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007897 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007898 Diag(CurrentLocation, diag::note_member_synthesized_at)
7899 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7900
7901 Destructor->setInvalidDecl();
7902 return;
7903 }
7904
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007905 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007906 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007907 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007908 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007909 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007910
7911 if (ASTMutationListener *L = getASTMutationListener()) {
7912 L->CompletedImplicitDefinition(Destructor);
7913 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007914}
7915
Richard Smitha4156b82012-04-21 18:42:51 +00007916/// \brief Perform any semantic analysis which needs to be delayed until all
7917/// pending class member declarations have been parsed.
7918void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00007919 // If the context is an invalid C++ class, just suppress these checks.
7920 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
7921 if (Record->isInvalidDecl()) {
7922 DelayedDestructorExceptionSpecChecks.clear();
7923 return;
7924 }
7925 }
7926
Richard Smitha4156b82012-04-21 18:42:51 +00007927 // Perform any deferred checking of exception specifications for virtual
7928 // destructors.
7929 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7930 i != e; ++i) {
7931 const CXXDestructorDecl *Dtor =
7932 DelayedDestructorExceptionSpecChecks[i].first;
7933 assert(!Dtor->getParent()->isDependentType() &&
7934 "Should not ever add destructors of templates into the list.");
7935 CheckOverridingFunctionExceptionSpec(Dtor,
7936 DelayedDestructorExceptionSpecChecks[i].second);
7937 }
7938 DelayedDestructorExceptionSpecChecks.clear();
7939}
7940
Richard Smithb9d0b762012-07-27 04:22:15 +00007941void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7942 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00007943 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00007944 "adjusting dtor exception specs was introduced in c++11");
7945
Sebastian Redl0ee33912011-05-19 05:13:44 +00007946 // C++11 [class.dtor]p3:
7947 // A declaration of a destructor that does not have an exception-
7948 // specification is implicitly considered to have the same exception-
7949 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007950 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007951 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007952 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007953 return;
7954
Chandler Carruth3f224b22011-09-20 04:55:26 +00007955 // Replace the destructor's type, building off the existing one. Fortunately,
7956 // the only thing of interest in the destructor type is its extended info.
7957 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007958 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7959 EPI.ExceptionSpecType = EST_Unevaluated;
7960 EPI.ExceptionSpecDecl = Destructor;
Jordan Rosebea522f2013-03-08 21:51:21 +00007961 Destructor->setType(Context.getFunctionType(Context.VoidTy,
7962 ArrayRef<QualType>(),
7963 EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007964
Sebastian Redl0ee33912011-05-19 05:13:44 +00007965 // FIXME: If the destructor has a body that could throw, and the newly created
7966 // spec doesn't allow exceptions, we should emit a warning, because this
7967 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007968 // However, we don't have a body or an exception specification yet, so it
7969 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007970}
7971
Richard Smith8c889532012-11-14 00:50:40 +00007972/// When generating a defaulted copy or move assignment operator, if a field
7973/// should be copied with __builtin_memcpy rather than via explicit assignments,
7974/// do so. This optimization only applies for arrays of scalars, and for arrays
7975/// of class type where the selected copy/move-assignment operator is trivial.
7976static StmtResult
7977buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7978 Expr *To, Expr *From) {
7979 // Compute the size of the memory buffer to be copied.
7980 QualType SizeType = S.Context.getSizeType();
7981 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7982 S.Context.getTypeSizeInChars(T).getQuantity());
7983
7984 // Take the address of the field references for "from" and "to". We
7985 // directly construct UnaryOperators here because semantic analysis
7986 // does not permit us to take the address of an xvalue.
7987 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7988 S.Context.getPointerType(From->getType()),
7989 VK_RValue, OK_Ordinary, Loc);
7990 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7991 S.Context.getPointerType(To->getType()),
7992 VK_RValue, OK_Ordinary, Loc);
7993
7994 const Type *E = T->getBaseElementTypeUnsafe();
7995 bool NeedsCollectableMemCpy =
7996 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7997
7998 // Create a reference to the __builtin_objc_memmove_collectable function
7999 StringRef MemCpyName = NeedsCollectableMemCpy ?
8000 "__builtin_objc_memmove_collectable" :
8001 "__builtin_memcpy";
8002 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8003 Sema::LookupOrdinaryName);
8004 S.LookupName(R, S.TUScope, true);
8005
8006 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8007 if (!MemCpy)
8008 // Something went horribly wrong earlier, and we will have complained
8009 // about it.
8010 return StmtError();
8011
8012 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8013 VK_RValue, Loc, 0);
8014 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8015
8016 Expr *CallArgs[] = {
8017 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8018 };
8019 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8020 Loc, CallArgs, Loc);
8021
8022 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8023 return S.Owned(Call.takeAs<Stmt>());
8024}
8025
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008026/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008027/// \c To.
8028///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008029/// This routine is used to copy/move the members of a class with an
8030/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008031/// copied are arrays, this routine builds for loops to copy them.
8032///
8033/// \param S The Sema object used for type-checking.
8034///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008035/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008036///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008037/// \param T The type of the expressions being copied/moved. Both expressions
8038/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008039///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008040/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008041///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008042/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008043///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008044/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008045/// Otherwise, it's a non-static member subobject.
8046///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008047/// \param Copying Whether we're copying or moving.
8048///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008049/// \param Depth Internal parameter recording the depth of the recursion.
8050///
Richard Smith8c889532012-11-14 00:50:40 +00008051/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8052/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008053static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008054buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8055 Expr *To, Expr *From,
8056 bool CopyingBaseSubobject, bool Copying,
8057 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008058 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008059 // Each subobject is assigned in the manner appropriate to its type:
8060 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008061 // - if the subobject is of class type, as if by a call to operator= with
8062 // the subobject as the object expression and the corresponding
8063 // subobject of x as a single function argument (as if by explicit
8064 // qualification; that is, ignoring any possible virtual overriding
8065 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008066 //
8067 // C++03 [class.copy]p13:
8068 // - if the subobject is of class type, the copy assignment operator for
8069 // the class is used (as if by explicit qualification; that is,
8070 // ignoring any possible virtual overriding functions in more derived
8071 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008072 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8073 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008074
Douglas Gregor06a9f362010-05-01 20:49:11 +00008075 // Look for operator=.
8076 DeclarationName Name
8077 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8078 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8079 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008080
Richard Smith044c8aa2012-11-13 00:54:12 +00008081 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8082 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008083 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008084 LookupResult::Filter F = OpLookup.makeFilter();
8085 while (F.hasNext()) {
8086 NamedDecl *D = F.next();
8087 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8088 if (Method->isCopyAssignmentOperator() ||
8089 (!Copying && Method->isMoveAssignmentOperator()))
8090 continue;
8091
8092 F.erase();
8093 }
8094 F.done();
John McCallb0207482010-03-16 06:11:48 +00008095 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008096
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008097 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008098 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008099 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008100 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008101 // ambiguities), we need to cast "this" to that subobject type; to
8102 // ensure that we don't go through the virtual call mechanism, we need
8103 // to qualify the operator= name with the base class (see below). However,
8104 // this means that if the base class has a protected copy assignment
8105 // operator, the protected member access check will fail. So, we
8106 // rewrite "protected" access to "public" access in this case, since we
8107 // know by construction that we're calling from a derived class.
8108 if (CopyingBaseSubobject) {
8109 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8110 L != LEnd; ++L) {
8111 if (L.getAccess() == AS_protected)
8112 L.setAccess(AS_public);
8113 }
8114 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008115
Douglas Gregor06a9f362010-05-01 20:49:11 +00008116 // Create the nested-name-specifier that will be used to qualify the
8117 // reference to operator=; this is required to suppress the virtual
8118 // call mechanism.
8119 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008120 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008121 SS.MakeTrivial(S.Context,
8122 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008123 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008124 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008125
Douglas Gregor06a9f362010-05-01 20:49:11 +00008126 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008127 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008128 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008129 /*TemplateKWLoc=*/SourceLocation(),
8130 /*FirstQualifierInScope=*/0,
8131 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008132 /*TemplateArgs=*/0,
8133 /*SuppressQualifierCheck=*/true);
8134 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008135 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008136
Douglas Gregor06a9f362010-05-01 20:49:11 +00008137 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008138
Richard Smith044c8aa2012-11-13 00:54:12 +00008139 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008140 OpEqualRef.takeAs<Expr>(),
8141 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008142 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008143 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008144
Richard Smith8c889532012-11-14 00:50:40 +00008145 // If we built a call to a trivial 'operator=' while copying an array,
8146 // bail out. We'll replace the whole shebang with a memcpy.
8147 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8148 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8149 return StmtResult((Stmt*)0);
8150
Richard Smith044c8aa2012-11-13 00:54:12 +00008151 // Convert to an expression-statement, and clean up any produced
8152 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008153 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008154 }
John McCallb0207482010-03-16 06:11:48 +00008155
Richard Smith044c8aa2012-11-13 00:54:12 +00008156 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008157 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008158 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008159 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008160 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008161 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008162 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008163 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008164 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008165
8166 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008167 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008168
Douglas Gregor06a9f362010-05-01 20:49:11 +00008169 // Construct a loop over the array bounds, e.g.,
8170 //
8171 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8172 //
8173 // that will copy each of the array elements.
8174 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008175
Douglas Gregor06a9f362010-05-01 20:49:11 +00008176 // Create the iteration variable.
8177 IdentifierInfo *IterationVarName = 0;
8178 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008179 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008180 llvm::raw_svector_ostream OS(Str);
8181 OS << "__i" << Depth;
8182 IterationVarName = &S.Context.Idents.get(OS.str());
8183 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008184 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008185 IterationVarName, SizeType,
8186 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008187 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008188
Douglas Gregor06a9f362010-05-01 20:49:11 +00008189 // Initialize the iteration variable to zero.
8190 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008191 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008192
8193 // Create a reference to the iteration variable; we'll use this several
8194 // times throughout.
8195 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008196 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008197 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008198 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8199 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8200
Douglas Gregor06a9f362010-05-01 20:49:11 +00008201 // Create the DeclStmt that holds the iteration variable.
8202 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008203
Douglas Gregor06a9f362010-05-01 20:49:11 +00008204 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008205 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008206 IterationVarRefRVal,
8207 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008208 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008209 IterationVarRefRVal,
8210 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008211 if (!Copying) // Cast to rvalue
8212 From = CastForMoving(S, From);
8213
8214 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008215 StmtResult Copy =
8216 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8217 To, From, CopyingBaseSubobject,
8218 Copying, Depth + 1);
8219 // Bail out if copying fails or if we determined that we should use memcpy.
8220 if (Copy.isInvalid() || !Copy.get())
8221 return Copy;
8222
8223 // Create the comparison against the array bound.
8224 llvm::APInt Upper
8225 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8226 Expr *Comparison
8227 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8228 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8229 BO_NE, S.Context.BoolTy,
8230 VK_RValue, OK_Ordinary, Loc, false);
8231
8232 // Create the pre-increment of the iteration variable.
8233 Expr *Increment
8234 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8235 VK_LValue, OK_Ordinary, Loc);
8236
Douglas Gregor06a9f362010-05-01 20:49:11 +00008237 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008238 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008239 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008240 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008241 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008242}
8243
Richard Smith8c889532012-11-14 00:50:40 +00008244static StmtResult
8245buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8246 Expr *To, Expr *From,
8247 bool CopyingBaseSubobject, bool Copying) {
8248 // Maybe we should use a memcpy?
8249 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8250 T.isTriviallyCopyableType(S.Context))
8251 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8252
8253 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8254 CopyingBaseSubobject,
8255 Copying, 0));
8256
8257 // If we ended up picking a trivial assignment operator for an array of a
8258 // non-trivially-copyable class type, just emit a memcpy.
8259 if (!Result.isInvalid() && !Result.get())
8260 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8261
8262 return Result;
8263}
8264
Richard Smithb9d0b762012-07-27 04:22:15 +00008265Sema::ImplicitExceptionSpecification
8266Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8267 CXXRecordDecl *ClassDecl = MD->getParent();
8268
8269 ImplicitExceptionSpecification ExceptSpec(*this);
8270 if (ClassDecl->isInvalidDecl())
8271 return ExceptSpec;
8272
8273 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8274 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8275 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8276
Douglas Gregorb87786f2010-07-01 17:48:08 +00008277 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008278 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008279 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008280
8281 // It is unspecified whether or not an implicit copy assignment operator
8282 // attempts to deduplicate calls to assignment operators of virtual bases are
8283 // made. As such, this exception specification is effectively unspecified.
8284 // Based on a similar decision made for constness in C++0x, we're erring on
8285 // the side of assuming such calls to be made regardless of whether they
8286 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008287 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8288 BaseEnd = ClassDecl->bases_end();
8289 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008290 if (Base->isVirtual())
8291 continue;
8292
Douglas Gregora376d102010-07-02 21:50:04 +00008293 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008294 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008295 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8296 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008297 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008298 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008299
8300 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8301 BaseEnd = ClassDecl->vbases_end();
8302 Base != BaseEnd; ++Base) {
8303 CXXRecordDecl *BaseClassDecl
8304 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8305 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8306 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008307 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008308 }
8309
Douglas Gregorb87786f2010-07-01 17:48:08 +00008310 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8311 FieldEnd = ClassDecl->field_end();
8312 Field != FieldEnd;
8313 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008314 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008315 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8316 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008317 LookupCopyingAssignment(FieldClassDecl,
8318 ArgQuals | FieldType.getCVRQualifiers(),
8319 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008320 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008321 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008322 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008323
Richard Smithb9d0b762012-07-27 04:22:15 +00008324 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008325}
8326
8327CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8328 // Note: The following rules are largely analoguous to the copy
8329 // constructor rules. Note that virtual bases are not taken into account
8330 // for determining the argument type of the operator. Note also that
8331 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008332 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008333
Richard Smithafb49182012-11-29 01:34:07 +00008334 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8335 if (DSM.isAlreadyBeingDeclared())
8336 return 0;
8337
Sean Hunt30de05c2011-05-14 05:23:20 +00008338 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8339 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008340 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008341 ArgType = ArgType.withConst();
8342 ArgType = Context.getLValueReferenceType(ArgType);
8343
Douglas Gregord3c35902010-07-01 16:36:15 +00008344 // An implicitly-declared copy assignment operator is an inline public
8345 // member of its class.
8346 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008347 SourceLocation ClassLoc = ClassDecl->getLocation();
8348 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008349 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008350 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008351 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008352 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008353 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008354 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008355 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008356 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008357 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008358
8359 // Build an exception specification pointing back at this member.
8360 FunctionProtoType::ExtProtoInfo EPI;
8361 EPI.ExceptionSpecType = EST_Unevaluated;
8362 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008363 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008364
Douglas Gregord3c35902010-07-01 16:36:15 +00008365 // Add the parameter to the operator.
8366 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008367 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008368 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008369 SC_None,
8370 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008371 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008372
Richard Smithbc2a35d2012-12-08 08:32:28 +00008373 AddOverriddenMethods(ClassDecl, CopyAssignment);
8374
8375 CopyAssignment->setTrivial(
8376 ClassDecl->needsOverloadResolutionForCopyAssignment()
8377 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8378 : ClassDecl->hasTrivialCopyAssignment());
8379
Nico Weberafcc96a2012-01-23 03:19:29 +00008380 // C++0x [class.copy]p19:
8381 // .... If the class definition does not explicitly declare a copy
8382 // assignment operator, there is no user-declared move constructor, and
8383 // there is no user-declared move assignment operator, a copy assignment
8384 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008385 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008386 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008387
Richard Smithbc2a35d2012-12-08 08:32:28 +00008388 // Note that we have added this copy-assignment operator.
8389 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8390
8391 if (Scope *S = getScopeForContext(ClassDecl))
8392 PushOnScopeChains(CopyAssignment, S, false);
8393 ClassDecl->addDecl(CopyAssignment);
8394
Douglas Gregord3c35902010-07-01 16:36:15 +00008395 return CopyAssignment;
8396}
8397
Douglas Gregor06a9f362010-05-01 20:49:11 +00008398void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8399 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008400 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008401 CopyAssignOperator->isOverloadedOperator() &&
8402 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008403 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8404 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008405 "DefineImplicitCopyAssignment called for wrong function");
8406
8407 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8408
8409 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8410 CopyAssignOperator->setInvalidDecl();
8411 return;
8412 }
8413
8414 CopyAssignOperator->setUsed();
8415
Eli Friedman9a14db32012-10-18 20:14:08 +00008416 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008417 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008418
8419 // C++0x [class.copy]p30:
8420 // The implicitly-defined or explicitly-defaulted copy assignment operator
8421 // for a non-union class X performs memberwise copy assignment of its
8422 // subobjects. The direct base classes of X are assigned first, in the
8423 // order of their declaration in the base-specifier-list, and then the
8424 // immediate non-static data members of X are assigned, in the order in
8425 // which they were declared in the class definition.
8426
8427 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008428 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008429
8430 // The parameter for the "other" object, which we are copying from.
8431 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8432 Qualifiers OtherQuals = Other->getType().getQualifiers();
8433 QualType OtherRefType = Other->getType();
8434 if (const LValueReferenceType *OtherRef
8435 = OtherRefType->getAs<LValueReferenceType>()) {
8436 OtherRefType = OtherRef->getPointeeType();
8437 OtherQuals = OtherRefType.getQualifiers();
8438 }
8439
8440 // Our location for everything implicitly-generated.
8441 SourceLocation Loc = CopyAssignOperator->getLocation();
8442
8443 // Construct a reference to the "other" object. We'll be using this
8444 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008445 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008446 assert(OtherRef && "Reference to parameter cannot fail!");
8447
8448 // Construct the "this" pointer. We'll be using this throughout the generated
8449 // ASTs.
8450 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8451 assert(This && "Reference to this cannot fail!");
8452
8453 // Assign base classes.
8454 bool Invalid = false;
8455 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8456 E = ClassDecl->bases_end(); Base != E; ++Base) {
8457 // Form the assignment:
8458 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8459 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008460 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008461 Invalid = true;
8462 continue;
8463 }
8464
John McCallf871d0c2010-08-07 06:22:56 +00008465 CXXCastPath BasePath;
8466 BasePath.push_back(Base);
8467
Douglas Gregor06a9f362010-05-01 20:49:11 +00008468 // Construct the "from" expression, which is an implicit cast to the
8469 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008470 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008471 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8472 CK_UncheckedDerivedToBase,
8473 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008474
8475 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008476 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008477
8478 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008479 To = ImpCastExprToType(To.take(),
8480 Context.getCVRQualifiedType(BaseType,
8481 CopyAssignOperator->getTypeQualifiers()),
8482 CK_UncheckedDerivedToBase,
8483 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008484
8485 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008486 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008487 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008488 /*CopyingBaseSubobject=*/true,
8489 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008490 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008491 Diag(CurrentLocation, diag::note_member_synthesized_at)
8492 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8493 CopyAssignOperator->setInvalidDecl();
8494 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008495 }
8496
8497 // Success! Record the copy.
8498 Statements.push_back(Copy.takeAs<Expr>());
8499 }
8500
Douglas Gregor06a9f362010-05-01 20:49:11 +00008501 // Assign non-static members.
8502 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8503 FieldEnd = ClassDecl->field_end();
8504 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008505 if (Field->isUnnamedBitfield())
8506 continue;
8507
Douglas Gregor06a9f362010-05-01 20:49:11 +00008508 // Check for members of reference type; we can't copy those.
8509 if (Field->getType()->isReferenceType()) {
8510 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8511 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8512 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008513 Diag(CurrentLocation, diag::note_member_synthesized_at)
8514 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008515 Invalid = true;
8516 continue;
8517 }
8518
8519 // Check for members of const-qualified, non-class type.
8520 QualType BaseType = Context.getBaseElementType(Field->getType());
8521 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8522 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8523 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8524 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008525 Diag(CurrentLocation, diag::note_member_synthesized_at)
8526 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008527 Invalid = true;
8528 continue;
8529 }
John McCallb77115d2011-06-17 00:18:42 +00008530
8531 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008532 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8533 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008534
8535 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008536 if (FieldType->isIncompleteArrayType()) {
8537 assert(ClassDecl->hasFlexibleArrayMember() &&
8538 "Incomplete array type is not valid");
8539 continue;
8540 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008541
8542 // Build references to the field in the object we're copying from and to.
8543 CXXScopeSpec SS; // Intentionally empty
8544 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8545 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008546 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008547 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008548 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008549 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008550 SS, SourceLocation(), 0,
8551 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008552 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008553 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008554 SS, SourceLocation(), 0,
8555 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008556 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8557 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008558
Douglas Gregor06a9f362010-05-01 20:49:11 +00008559 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008560 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008561 To.get(), From.get(),
8562 /*CopyingBaseSubobject=*/false,
8563 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008564 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008565 Diag(CurrentLocation, diag::note_member_synthesized_at)
8566 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8567 CopyAssignOperator->setInvalidDecl();
8568 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008569 }
8570
8571 // Success! Record the copy.
8572 Statements.push_back(Copy.takeAs<Stmt>());
8573 }
8574
8575 if (!Invalid) {
8576 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008577 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008578
John McCall60d7b3a2010-08-24 06:29:42 +00008579 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008580 if (Return.isInvalid())
8581 Invalid = true;
8582 else {
8583 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008584
8585 if (Trap.hasErrorOccurred()) {
8586 Diag(CurrentLocation, diag::note_member_synthesized_at)
8587 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8588 Invalid = true;
8589 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008590 }
8591 }
8592
8593 if (Invalid) {
8594 CopyAssignOperator->setInvalidDecl();
8595 return;
8596 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008597
8598 StmtResult Body;
8599 {
8600 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008601 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008602 /*isStmtExpr=*/false);
8603 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8604 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008605 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008606
8607 if (ASTMutationListener *L = getASTMutationListener()) {
8608 L->CompletedImplicitDefinition(CopyAssignOperator);
8609 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008610}
8611
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008612Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008613Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8614 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008615
Richard Smithb9d0b762012-07-27 04:22:15 +00008616 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008617 if (ClassDecl->isInvalidDecl())
8618 return ExceptSpec;
8619
8620 // C++0x [except.spec]p14:
8621 // An implicitly declared special member function (Clause 12) shall have an
8622 // exception-specification. [...]
8623
8624 // It is unspecified whether or not an implicit move assignment operator
8625 // attempts to deduplicate calls to assignment operators of virtual bases are
8626 // made. As such, this exception specification is effectively unspecified.
8627 // Based on a similar decision made for constness in C++0x, we're erring on
8628 // the side of assuming such calls to be made regardless of whether they
8629 // actually happen.
8630 // Note that a move constructor is not implicitly declared when there are
8631 // virtual bases, but it can still be user-declared and explicitly defaulted.
8632 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8633 BaseEnd = ClassDecl->bases_end();
8634 Base != BaseEnd; ++Base) {
8635 if (Base->isVirtual())
8636 continue;
8637
8638 CXXRecordDecl *BaseClassDecl
8639 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8640 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008641 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008642 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008643 }
8644
8645 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8646 BaseEnd = ClassDecl->vbases_end();
8647 Base != BaseEnd; ++Base) {
8648 CXXRecordDecl *BaseClassDecl
8649 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8650 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008651 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008652 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008653 }
8654
8655 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8656 FieldEnd = ClassDecl->field_end();
8657 Field != FieldEnd;
8658 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008659 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008660 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008661 if (CXXMethodDecl *MoveAssign =
8662 LookupMovingAssignment(FieldClassDecl,
8663 FieldType.getCVRQualifiers(),
8664 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008665 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008666 }
8667 }
8668
8669 return ExceptSpec;
8670}
8671
Richard Smith1c931be2012-04-02 18:40:40 +00008672/// Determine whether the class type has any direct or indirect virtual base
8673/// classes which have a non-trivial move assignment operator.
8674static bool
8675hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8676 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8677 BaseEnd = ClassDecl->vbases_end();
8678 Base != BaseEnd; ++Base) {
8679 CXXRecordDecl *BaseClass =
8680 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8681
8682 // Try to declare the move assignment. If it would be deleted, then the
8683 // class does not have a non-trivial move assignment.
8684 if (BaseClass->needsImplicitMoveAssignment())
8685 S.DeclareImplicitMoveAssignment(BaseClass);
8686
Richard Smith426391c2012-11-16 00:53:38 +00008687 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008688 return true;
8689 }
8690
8691 return false;
8692}
8693
8694/// Determine whether the given type either has a move constructor or is
8695/// trivially copyable.
8696static bool
8697hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8698 Type = S.Context.getBaseElementType(Type);
8699
8700 // FIXME: Technically, non-trivially-copyable non-class types, such as
8701 // reference types, are supposed to return false here, but that appears
8702 // to be a standard defect.
8703 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008704 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008705 return true;
8706
8707 if (Type.isTriviallyCopyableType(S.Context))
8708 return true;
8709
8710 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008711 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8712 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008713 if (ClassDecl->needsImplicitMoveConstructor())
8714 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008715 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008716 }
8717
Richard Smithe5411b72012-12-01 02:35:44 +00008718 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8719 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008720 if (ClassDecl->needsImplicitMoveAssignment())
8721 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008722 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008723}
8724
8725/// Determine whether all non-static data members and direct or virtual bases
8726/// of class \p ClassDecl have either a move operation, or are trivially
8727/// copyable.
8728static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8729 bool IsConstructor) {
8730 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8731 BaseEnd = ClassDecl->bases_end();
8732 Base != BaseEnd; ++Base) {
8733 if (Base->isVirtual())
8734 continue;
8735
8736 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8737 return false;
8738 }
8739
8740 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8741 BaseEnd = ClassDecl->vbases_end();
8742 Base != BaseEnd; ++Base) {
8743 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8744 return false;
8745 }
8746
8747 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8748 FieldEnd = ClassDecl->field_end();
8749 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008750 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008751 return false;
8752 }
8753
8754 return true;
8755}
8756
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008757CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008758 // C++11 [class.copy]p20:
8759 // If the definition of a class X does not explicitly declare a move
8760 // assignment operator, one will be implicitly declared as defaulted
8761 // if and only if:
8762 //
8763 // - [first 4 bullets]
8764 assert(ClassDecl->needsImplicitMoveAssignment());
8765
Richard Smithafb49182012-11-29 01:34:07 +00008766 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8767 if (DSM.isAlreadyBeingDeclared())
8768 return 0;
8769
Richard Smith1c931be2012-04-02 18:40:40 +00008770 // [Checked after we build the declaration]
8771 // - the move assignment operator would not be implicitly defined as
8772 // deleted,
8773
8774 // [DR1402]:
8775 // - X has no direct or indirect virtual base class with a non-trivial
8776 // move assignment operator, and
8777 // - each of X's non-static data members and direct or virtual base classes
8778 // has a type that either has a move assignment operator or is trivially
8779 // copyable.
8780 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8781 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8782 ClassDecl->setFailedImplicitMoveAssignment();
8783 return 0;
8784 }
8785
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008786 // Note: The following rules are largely analoguous to the move
8787 // constructor rules.
8788
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008789 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8790 QualType RetType = Context.getLValueReferenceType(ArgType);
8791 ArgType = Context.getRValueReferenceType(ArgType);
8792
8793 // An implicitly-declared move assignment operator is an inline public
8794 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008795 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8796 SourceLocation ClassLoc = ClassDecl->getLocation();
8797 DeclarationNameInfo NameInfo(Name, ClassLoc);
8798 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008799 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008800 /*TInfo=*/0, /*isStatic=*/false,
8801 /*StorageClassAsWritten=*/SC_None,
8802 /*isInline=*/true,
8803 /*isConstexpr=*/false,
8804 SourceLocation());
8805 MoveAssignment->setAccess(AS_public);
8806 MoveAssignment->setDefaulted();
8807 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008808
Richard Smithb9d0b762012-07-27 04:22:15 +00008809 // Build an exception specification pointing back at this member.
8810 FunctionProtoType::ExtProtoInfo EPI;
8811 EPI.ExceptionSpecType = EST_Unevaluated;
8812 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008813 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008814
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008815 // Add the parameter to the operator.
8816 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8817 ClassLoc, ClassLoc, /*Id=*/0,
8818 ArgType, /*TInfo=*/0,
8819 SC_None,
8820 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008821 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008822
Richard Smithbc2a35d2012-12-08 08:32:28 +00008823 AddOverriddenMethods(ClassDecl, MoveAssignment);
8824
8825 MoveAssignment->setTrivial(
8826 ClassDecl->needsOverloadResolutionForMoveAssignment()
8827 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8828 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008829
8830 // C++0x [class.copy]p9:
8831 // If the definition of a class X does not explicitly declare a move
8832 // assignment operator, one will be implicitly declared as defaulted if and
8833 // only if:
8834 // [...]
8835 // - the move assignment operator would not be implicitly defined as
8836 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008837 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008838 // Cache this result so that we don't try to generate this over and over
8839 // on every lookup, leaking memory and wasting time.
8840 ClassDecl->setFailedImplicitMoveAssignment();
8841 return 0;
8842 }
8843
Richard Smithbc2a35d2012-12-08 08:32:28 +00008844 // Note that we have added this copy-assignment operator.
8845 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8846
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008847 if (Scope *S = getScopeForContext(ClassDecl))
8848 PushOnScopeChains(MoveAssignment, S, false);
8849 ClassDecl->addDecl(MoveAssignment);
8850
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008851 return MoveAssignment;
8852}
8853
8854void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8855 CXXMethodDecl *MoveAssignOperator) {
8856 assert((MoveAssignOperator->isDefaulted() &&
8857 MoveAssignOperator->isOverloadedOperator() &&
8858 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008859 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8860 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008861 "DefineImplicitMoveAssignment called for wrong function");
8862
8863 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8864
8865 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8866 MoveAssignOperator->setInvalidDecl();
8867 return;
8868 }
8869
8870 MoveAssignOperator->setUsed();
8871
Eli Friedman9a14db32012-10-18 20:14:08 +00008872 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008873 DiagnosticErrorTrap Trap(Diags);
8874
8875 // C++0x [class.copy]p28:
8876 // The implicitly-defined or move assignment operator for a non-union class
8877 // X performs memberwise move assignment of its subobjects. The direct base
8878 // classes of X are assigned first, in the order of their declaration in the
8879 // base-specifier-list, and then the immediate non-static data members of X
8880 // are assigned, in the order in which they were declared in the class
8881 // definition.
8882
8883 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008884 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008885
8886 // The parameter for the "other" object, which we are move from.
8887 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8888 QualType OtherRefType = Other->getType()->
8889 getAs<RValueReferenceType>()->getPointeeType();
8890 assert(OtherRefType.getQualifiers() == 0 &&
8891 "Bad argument type of defaulted move assignment");
8892
8893 // Our location for everything implicitly-generated.
8894 SourceLocation Loc = MoveAssignOperator->getLocation();
8895
8896 // Construct a reference to the "other" object. We'll be using this
8897 // throughout the generated ASTs.
8898 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8899 assert(OtherRef && "Reference to parameter cannot fail!");
8900 // Cast to rvalue.
8901 OtherRef = CastForMoving(*this, OtherRef);
8902
8903 // Construct the "this" pointer. We'll be using this throughout the generated
8904 // ASTs.
8905 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8906 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008907
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008908 // Assign base classes.
8909 bool Invalid = false;
8910 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8911 E = ClassDecl->bases_end(); Base != E; ++Base) {
8912 // Form the assignment:
8913 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8914 QualType BaseType = Base->getType().getUnqualifiedType();
8915 if (!BaseType->isRecordType()) {
8916 Invalid = true;
8917 continue;
8918 }
8919
8920 CXXCastPath BasePath;
8921 BasePath.push_back(Base);
8922
8923 // Construct the "from" expression, which is an implicit cast to the
8924 // appropriately-qualified base type.
8925 Expr *From = OtherRef;
8926 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008927 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008928
8929 // Dereference "this".
8930 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8931
8932 // Implicitly cast "this" to the appropriately-qualified base type.
8933 To = ImpCastExprToType(To.take(),
8934 Context.getCVRQualifiedType(BaseType,
8935 MoveAssignOperator->getTypeQualifiers()),
8936 CK_UncheckedDerivedToBase,
8937 VK_LValue, &BasePath);
8938
8939 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008940 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008941 To.get(), From,
8942 /*CopyingBaseSubobject=*/true,
8943 /*Copying=*/false);
8944 if (Move.isInvalid()) {
8945 Diag(CurrentLocation, diag::note_member_synthesized_at)
8946 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8947 MoveAssignOperator->setInvalidDecl();
8948 return;
8949 }
8950
8951 // Success! Record the move.
8952 Statements.push_back(Move.takeAs<Expr>());
8953 }
8954
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008955 // Assign non-static members.
8956 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8957 FieldEnd = ClassDecl->field_end();
8958 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008959 if (Field->isUnnamedBitfield())
8960 continue;
8961
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008962 // Check for members of reference type; we can't move those.
8963 if (Field->getType()->isReferenceType()) {
8964 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8965 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8966 Diag(Field->getLocation(), diag::note_declared_at);
8967 Diag(CurrentLocation, diag::note_member_synthesized_at)
8968 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8969 Invalid = true;
8970 continue;
8971 }
8972
8973 // Check for members of const-qualified, non-class type.
8974 QualType BaseType = Context.getBaseElementType(Field->getType());
8975 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8976 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8977 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8978 Diag(Field->getLocation(), diag::note_declared_at);
8979 Diag(CurrentLocation, diag::note_member_synthesized_at)
8980 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8981 Invalid = true;
8982 continue;
8983 }
8984
8985 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008986 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8987 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008988
8989 QualType FieldType = Field->getType().getNonReferenceType();
8990 if (FieldType->isIncompleteArrayType()) {
8991 assert(ClassDecl->hasFlexibleArrayMember() &&
8992 "Incomplete array type is not valid");
8993 continue;
8994 }
8995
8996 // Build references to the field in the object we're copying from and to.
8997 CXXScopeSpec SS; // Intentionally empty
8998 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8999 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009000 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009001 MemberLookup.resolveKind();
9002 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9003 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009004 SS, SourceLocation(), 0,
9005 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009006 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9007 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009008 SS, SourceLocation(), 0,
9009 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009010 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9011 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9012
9013 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9014 "Member reference with rvalue base must be rvalue except for reference "
9015 "members, which aren't allowed for move assignment.");
9016
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009017 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009018 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009019 To.get(), From.get(),
9020 /*CopyingBaseSubobject=*/false,
9021 /*Copying=*/false);
9022 if (Move.isInvalid()) {
9023 Diag(CurrentLocation, diag::note_member_synthesized_at)
9024 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9025 MoveAssignOperator->setInvalidDecl();
9026 return;
9027 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009028
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009029 // Success! Record the copy.
9030 Statements.push_back(Move.takeAs<Stmt>());
9031 }
9032
9033 if (!Invalid) {
9034 // Add a "return *this;"
9035 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9036
9037 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9038 if (Return.isInvalid())
9039 Invalid = true;
9040 else {
9041 Statements.push_back(Return.takeAs<Stmt>());
9042
9043 if (Trap.hasErrorOccurred()) {
9044 Diag(CurrentLocation, diag::note_member_synthesized_at)
9045 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9046 Invalid = true;
9047 }
9048 }
9049 }
9050
9051 if (Invalid) {
9052 MoveAssignOperator->setInvalidDecl();
9053 return;
9054 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009055
9056 StmtResult Body;
9057 {
9058 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009059 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009060 /*isStmtExpr=*/false);
9061 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9062 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009063 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9064
9065 if (ASTMutationListener *L = getASTMutationListener()) {
9066 L->CompletedImplicitDefinition(MoveAssignOperator);
9067 }
9068}
9069
Richard Smithb9d0b762012-07-27 04:22:15 +00009070Sema::ImplicitExceptionSpecification
9071Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9072 CXXRecordDecl *ClassDecl = MD->getParent();
9073
9074 ImplicitExceptionSpecification ExceptSpec(*this);
9075 if (ClassDecl->isInvalidDecl())
9076 return ExceptSpec;
9077
9078 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9079 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9080 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9081
Douglas Gregor0d405db2010-07-01 20:59:04 +00009082 // C++ [except.spec]p14:
9083 // An implicitly declared special member function (Clause 12) shall have an
9084 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009085 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9086 BaseEnd = ClassDecl->bases_end();
9087 Base != BaseEnd;
9088 ++Base) {
9089 // Virtual bases are handled below.
9090 if (Base->isVirtual())
9091 continue;
9092
Douglas Gregor22584312010-07-02 23:41:54 +00009093 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009094 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009095 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009096 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009097 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009098 }
9099 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9100 BaseEnd = ClassDecl->vbases_end();
9101 Base != BaseEnd;
9102 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009103 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009104 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009105 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009106 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009107 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009108 }
9109 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9110 FieldEnd = ClassDecl->field_end();
9111 Field != FieldEnd;
9112 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009113 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009114 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9115 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009116 LookupCopyingConstructor(FieldClassDecl,
9117 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009118 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009119 }
9120 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009121
Richard Smithb9d0b762012-07-27 04:22:15 +00009122 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009123}
9124
9125CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9126 CXXRecordDecl *ClassDecl) {
9127 // C++ [class.copy]p4:
9128 // If the class definition does not explicitly declare a copy
9129 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009130 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009131
Richard Smithafb49182012-11-29 01:34:07 +00009132 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9133 if (DSM.isAlreadyBeingDeclared())
9134 return 0;
9135
Sean Hunt49634cf2011-05-13 06:10:58 +00009136 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9137 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009138 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009139 if (Const)
9140 ArgType = ArgType.withConst();
9141 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009142
Richard Smith7756afa2012-06-10 05:43:50 +00009143 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9144 CXXCopyConstructor,
9145 Const);
9146
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009147 DeclarationName Name
9148 = Context.DeclarationNames.getCXXConstructorName(
9149 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009150 SourceLocation ClassLoc = ClassDecl->getLocation();
9151 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009152
9153 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009154 // member of its class.
9155 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009156 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009157 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009158 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009159 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009160 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009161
Richard Smithb9d0b762012-07-27 04:22:15 +00009162 // Build an exception specification pointing back at this member.
9163 FunctionProtoType::ExtProtoInfo EPI;
9164 EPI.ExceptionSpecType = EST_Unevaluated;
9165 EPI.ExceptionSpecDecl = CopyConstructor;
9166 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009167 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009168
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009169 // Add the parameter to the constructor.
9170 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009171 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009172 /*IdentifierInfo=*/0,
9173 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009174 SC_None,
9175 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009176 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009177
Richard Smithbc2a35d2012-12-08 08:32:28 +00009178 CopyConstructor->setTrivial(
9179 ClassDecl->needsOverloadResolutionForCopyConstructor()
9180 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9181 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009182
Nico Weberafcc96a2012-01-23 03:19:29 +00009183 // C++11 [class.copy]p8:
9184 // ... If the class definition does not explicitly declare a copy
9185 // constructor, there is no user-declared move constructor, and there is no
9186 // user-declared move assignment operator, a copy constructor is implicitly
9187 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009188 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009189 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009190
Richard Smithbc2a35d2012-12-08 08:32:28 +00009191 // Note that we have declared this constructor.
9192 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9193
9194 if (Scope *S = getScopeForContext(ClassDecl))
9195 PushOnScopeChains(CopyConstructor, S, false);
9196 ClassDecl->addDecl(CopyConstructor);
9197
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009198 return CopyConstructor;
9199}
9200
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009201void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009202 CXXConstructorDecl *CopyConstructor) {
9203 assert((CopyConstructor->isDefaulted() &&
9204 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009205 !CopyConstructor->doesThisDeclarationHaveABody() &&
9206 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009207 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009208
Anders Carlsson63010a72010-04-23 16:24:12 +00009209 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009210 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009211
Eli Friedman9a14db32012-10-18 20:14:08 +00009212 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009213 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009214
David Blaikie93c86172013-01-17 05:26:25 +00009215 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009216 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009217 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009218 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009219 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009220 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009221 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009222 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9223 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009224 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009225 /*isStmtExpr=*/false)
9226 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009227 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009228 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009229
9230 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009231 if (ASTMutationListener *L = getASTMutationListener()) {
9232 L->CompletedImplicitDefinition(CopyConstructor);
9233 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009234}
9235
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009236Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009237Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9238 CXXRecordDecl *ClassDecl = MD->getParent();
9239
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009240 // C++ [except.spec]p14:
9241 // An implicitly declared special member function (Clause 12) shall have an
9242 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009243 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009244 if (ClassDecl->isInvalidDecl())
9245 return ExceptSpec;
9246
9247 // Direct base-class constructors.
9248 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9249 BEnd = ClassDecl->bases_end();
9250 B != BEnd; ++B) {
9251 if (B->isVirtual()) // Handled below.
9252 continue;
9253
9254 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9255 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009256 CXXConstructorDecl *Constructor =
9257 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009258 // If this is a deleted function, add it anyway. This might be conformant
9259 // with the standard. This might not. I'm not sure. It might not matter.
9260 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009261 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009262 }
9263 }
9264
9265 // Virtual base-class constructors.
9266 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9267 BEnd = ClassDecl->vbases_end();
9268 B != BEnd; ++B) {
9269 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9270 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009271 CXXConstructorDecl *Constructor =
9272 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009273 // If this is a deleted function, add it anyway. This might be conformant
9274 // with the standard. This might not. I'm not sure. It might not matter.
9275 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009276 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009277 }
9278 }
9279
9280 // Field constructors.
9281 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9282 FEnd = ClassDecl->field_end();
9283 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009284 QualType FieldType = Context.getBaseElementType(F->getType());
9285 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9286 CXXConstructorDecl *Constructor =
9287 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009288 // If this is a deleted function, add it anyway. This might be conformant
9289 // with the standard. This might not. I'm not sure. It might not matter.
9290 // In particular, the problem is that this function never gets called. It
9291 // might just be ill-formed because this function attempts to refer to
9292 // a deleted function here.
9293 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009294 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009295 }
9296 }
9297
9298 return ExceptSpec;
9299}
9300
9301CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9302 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009303 // C++11 [class.copy]p9:
9304 // If the definition of a class X does not explicitly declare a move
9305 // constructor, one will be implicitly declared as defaulted if and only if:
9306 //
9307 // - [first 4 bullets]
9308 assert(ClassDecl->needsImplicitMoveConstructor());
9309
Richard Smithafb49182012-11-29 01:34:07 +00009310 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9311 if (DSM.isAlreadyBeingDeclared())
9312 return 0;
9313
Richard Smith1c931be2012-04-02 18:40:40 +00009314 // [Checked after we build the declaration]
9315 // - the move assignment operator would not be implicitly defined as
9316 // deleted,
9317
9318 // [DR1402]:
9319 // - each of X's non-static data members and direct or virtual base classes
9320 // has a type that either has a move constructor or is trivially copyable.
9321 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9322 ClassDecl->setFailedImplicitMoveConstructor();
9323 return 0;
9324 }
9325
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009326 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9327 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009328
Richard Smith7756afa2012-06-10 05:43:50 +00009329 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9330 CXXMoveConstructor,
9331 false);
9332
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009333 DeclarationName Name
9334 = Context.DeclarationNames.getCXXConstructorName(
9335 Context.getCanonicalType(ClassType));
9336 SourceLocation ClassLoc = ClassDecl->getLocation();
9337 DeclarationNameInfo NameInfo(Name, ClassLoc);
9338
9339 // C++0x [class.copy]p11:
9340 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009341 // member of its class.
9342 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009343 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009344 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009345 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009346 MoveConstructor->setAccess(AS_public);
9347 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009348
Richard Smithb9d0b762012-07-27 04:22:15 +00009349 // Build an exception specification pointing back at this member.
9350 FunctionProtoType::ExtProtoInfo EPI;
9351 EPI.ExceptionSpecType = EST_Unevaluated;
9352 EPI.ExceptionSpecDecl = MoveConstructor;
9353 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009354 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009355
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009356 // Add the parameter to the constructor.
9357 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9358 ClassLoc, ClassLoc,
9359 /*IdentifierInfo=*/0,
9360 ArgType, /*TInfo=*/0,
9361 SC_None,
9362 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009363 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009364
Richard Smithbc2a35d2012-12-08 08:32:28 +00009365 MoveConstructor->setTrivial(
9366 ClassDecl->needsOverloadResolutionForMoveConstructor()
9367 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9368 : ClassDecl->hasTrivialMoveConstructor());
9369
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009370 // C++0x [class.copy]p9:
9371 // If the definition of a class X does not explicitly declare a move
9372 // constructor, one will be implicitly declared as defaulted if and only if:
9373 // [...]
9374 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009375 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009376 // Cache this result so that we don't try to generate this over and over
9377 // on every lookup, leaking memory and wasting time.
9378 ClassDecl->setFailedImplicitMoveConstructor();
9379 return 0;
9380 }
9381
9382 // Note that we have declared this constructor.
9383 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9384
9385 if (Scope *S = getScopeForContext(ClassDecl))
9386 PushOnScopeChains(MoveConstructor, S, false);
9387 ClassDecl->addDecl(MoveConstructor);
9388
9389 return MoveConstructor;
9390}
9391
9392void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9393 CXXConstructorDecl *MoveConstructor) {
9394 assert((MoveConstructor->isDefaulted() &&
9395 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009396 !MoveConstructor->doesThisDeclarationHaveABody() &&
9397 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009398 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9399
9400 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9401 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9402
Eli Friedman9a14db32012-10-18 20:14:08 +00009403 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009404 DiagnosticErrorTrap Trap(Diags);
9405
David Blaikie93c86172013-01-17 05:26:25 +00009406 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009407 Trap.hasErrorOccurred()) {
9408 Diag(CurrentLocation, diag::note_member_synthesized_at)
9409 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9410 MoveConstructor->setInvalidDecl();
9411 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009412 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009413 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9414 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009415 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009416 /*isStmtExpr=*/false)
9417 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009418 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009419 }
9420
9421 MoveConstructor->setUsed();
9422
9423 if (ASTMutationListener *L = getASTMutationListener()) {
9424 L->CompletedImplicitDefinition(MoveConstructor);
9425 }
9426}
9427
Douglas Gregore4e68d42012-02-15 19:33:52 +00009428bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9429 return FD->isDeleted() &&
9430 (FD->isDefaulted() || FD->isImplicit()) &&
9431 isa<CXXMethodDecl>(FD);
9432}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009433
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009434/// \brief Mark the call operator of the given lambda closure type as "used".
9435static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9436 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009437 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00009438 Lambda->lookup(
9439 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009440 CallOperator->setReferenced();
9441 CallOperator->setUsed();
9442}
9443
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009444void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9445 SourceLocation CurrentLocation,
9446 CXXConversionDecl *Conv)
9447{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009448 CXXRecordDecl *Lambda = Conv->getParent();
9449
9450 // Make sure that the lambda call operator is marked used.
9451 markLambdaCallOperatorUsed(*this, Lambda);
9452
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009453 Conv->setUsed();
9454
Eli Friedman9a14db32012-10-18 20:14:08 +00009455 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009456 DiagnosticErrorTrap Trap(Diags);
9457
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009458 // Return the address of the __invoke function.
9459 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9460 CXXMethodDecl *Invoke
David Blaikie3bc93e32012-12-19 00:45:41 +00009461 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009462 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9463 VK_LValue, Conv->getLocation()).take();
9464 assert(FunctionRef && "Can't refer to __invoke function?");
9465 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +00009466 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009467 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009468 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009469
9470 // Fill in the __invoke function with a dummy implementation. IR generation
9471 // will fill in the actual details.
9472 Invoke->setUsed();
9473 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009474 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009475
9476 if (ASTMutationListener *L = getASTMutationListener()) {
9477 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009478 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009479 }
9480}
9481
9482void Sema::DefineImplicitLambdaToBlockPointerConversion(
9483 SourceLocation CurrentLocation,
9484 CXXConversionDecl *Conv)
9485{
9486 Conv->setUsed();
9487
Eli Friedman9a14db32012-10-18 20:14:08 +00009488 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009489 DiagnosticErrorTrap Trap(Diags);
9490
Douglas Gregorac1303e2012-02-22 05:02:47 +00009491 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009492 Expr *This = ActOnCXXThis(CurrentLocation).take();
9493 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009494
Eli Friedman23f02672012-03-01 04:01:32 +00009495 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9496 Conv->getLocation(),
9497 Conv, DerefThis);
9498
9499 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9500 // behavior. Note that only the general conversion function does this
9501 // (since it's unusable otherwise); in the case where we inline the
9502 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009503 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009504 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9505 CK_CopyAndAutoreleaseBlockObject,
9506 BuildBlock.get(), 0, VK_RValue);
9507
9508 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009509 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009510 Conv->setInvalidDecl();
9511 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009512 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009513
Douglas Gregorac1303e2012-02-22 05:02:47 +00009514 // Create the return statement that returns the block from the conversion
9515 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009516 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009517 if (Return.isInvalid()) {
9518 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9519 Conv->setInvalidDecl();
9520 return;
9521 }
9522
9523 // Set the body of the conversion function.
9524 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +00009525 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +00009526 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009527 Conv->getLocation()));
9528
Douglas Gregorac1303e2012-02-22 05:02:47 +00009529 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009530 if (ASTMutationListener *L = getASTMutationListener()) {
9531 L->CompletedImplicitDefinition(Conv);
9532 }
9533}
9534
Douglas Gregorf52757d2012-03-10 06:53:13 +00009535/// \brief Determine whether the given list arguments contains exactly one
9536/// "real" (non-default) argument.
9537static bool hasOneRealArgument(MultiExprArg Args) {
9538 switch (Args.size()) {
9539 case 0:
9540 return false;
9541
9542 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009543 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009544 return false;
9545
9546 // fall through
9547 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009548 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009549 }
9550
9551 return false;
9552}
9553
John McCall60d7b3a2010-08-24 06:29:42 +00009554ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009555Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009556 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009557 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009558 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009559 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009560 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009561 unsigned ConstructKind,
9562 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009563 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009564
Douglas Gregor2f599792010-04-02 18:24:57 +00009565 // C++0x [class.copy]p34:
9566 // When certain criteria are met, an implementation is allowed to
9567 // omit the copy/move construction of a class object, even if the
9568 // copy/move constructor and/or destructor for the object have
9569 // side effects. [...]
9570 // - when a temporary class object that has not been bound to a
9571 // reference (12.2) would be copied/moved to a class object
9572 // with the same cv-unqualified type, the copy/move operation
9573 // can be omitted by constructing the temporary object
9574 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009575 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009576 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009577 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009578 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009579 }
Mike Stump1eb44332009-09-09 15:08:12 +00009580
9581 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009582 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009583 IsListInitialization, RequiresZeroInit,
9584 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009585}
9586
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009587/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9588/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009589ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009590Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9591 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009592 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009593 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +00009594 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009595 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009596 unsigned ConstructKind,
9597 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009598 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009599 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009600 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +00009601 HadMultipleCandidates,
9602 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009603 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9604 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009605}
9606
John McCall68c6c9a2010-02-02 09:10:11 +00009607void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009608 if (VD->isInvalidDecl()) return;
9609
John McCall68c6c9a2010-02-02 09:10:11 +00009610 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009611 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009612 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009613 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009614
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009615 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009616 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009617 CheckDestructorAccess(VD->getLocation(), Destructor,
9618 PDiag(diag::err_access_dtor_var)
9619 << VD->getDeclName()
9620 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009621 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009622
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009623 if (!VD->hasGlobalStorage()) return;
9624
9625 // Emit warning for non-trivial dtor in global scope (a real global,
9626 // class-static, function-static).
9627 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9628
9629 // TODO: this should be re-enabled for static locals by !CXAAtExit
9630 if (!VD->isStaticLocal())
9631 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009632}
9633
Douglas Gregor39da0b82009-09-09 23:08:42 +00009634/// \brief Given a constructor and the set of arguments provided for the
9635/// constructor, convert the arguments and add any required default arguments
9636/// to form a proper call to this constructor.
9637///
9638/// \returns true if an error occurred, false otherwise.
9639bool
9640Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9641 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009642 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009643 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009644 bool AllowExplicit,
9645 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009646 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9647 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009648 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009649
9650 const FunctionProtoType *Proto
9651 = Constructor->getType()->getAs<FunctionProtoType>();
9652 assert(Proto && "Constructor without a prototype?");
9653 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009654
9655 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009656 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009657 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009658 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009659 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009660
9661 VariadicCallType CallType =
9662 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009663 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009664 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9665 Proto, 0, Args, NumArgs, AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +00009666 CallType, AllowExplicit,
9667 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009668 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009669
9670 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9671
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00009672 CheckConstructorCall(Constructor,
9673 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9674 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +00009675 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009676
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009677 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009678}
9679
Anders Carlsson20d45d22009-12-12 00:32:00 +00009680static inline bool
9681CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9682 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009683 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009684 if (isa<NamespaceDecl>(DC)) {
9685 return SemaRef.Diag(FnDecl->getLocation(),
9686 diag::err_operator_new_delete_declared_in_namespace)
9687 << FnDecl->getDeclName();
9688 }
9689
9690 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009691 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009692 return SemaRef.Diag(FnDecl->getLocation(),
9693 diag::err_operator_new_delete_declared_static)
9694 << FnDecl->getDeclName();
9695 }
9696
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009697 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009698}
9699
Anders Carlsson156c78e2009-12-13 17:53:43 +00009700static inline bool
9701CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9702 CanQualType ExpectedResultType,
9703 CanQualType ExpectedFirstParamType,
9704 unsigned DependentParamTypeDiag,
9705 unsigned InvalidParamTypeDiag) {
9706 QualType ResultType =
9707 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9708
9709 // Check that the result type is not dependent.
9710 if (ResultType->isDependentType())
9711 return SemaRef.Diag(FnDecl->getLocation(),
9712 diag::err_operator_new_delete_dependent_result_type)
9713 << FnDecl->getDeclName() << ExpectedResultType;
9714
9715 // Check that the result type is what we expect.
9716 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9717 return SemaRef.Diag(FnDecl->getLocation(),
9718 diag::err_operator_new_delete_invalid_result_type)
9719 << FnDecl->getDeclName() << ExpectedResultType;
9720
9721 // A function template must have at least 2 parameters.
9722 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9723 return SemaRef.Diag(FnDecl->getLocation(),
9724 diag::err_operator_new_delete_template_too_few_parameters)
9725 << FnDecl->getDeclName();
9726
9727 // The function decl must have at least 1 parameter.
9728 if (FnDecl->getNumParams() == 0)
9729 return SemaRef.Diag(FnDecl->getLocation(),
9730 diag::err_operator_new_delete_too_few_parameters)
9731 << FnDecl->getDeclName();
9732
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009733 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009734 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9735 if (FirstParamType->isDependentType())
9736 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9737 << FnDecl->getDeclName() << ExpectedFirstParamType;
9738
9739 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009740 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009741 ExpectedFirstParamType)
9742 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9743 << FnDecl->getDeclName() << ExpectedFirstParamType;
9744
9745 return false;
9746}
9747
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009748static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009749CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009750 // C++ [basic.stc.dynamic.allocation]p1:
9751 // A program is ill-formed if an allocation function is declared in a
9752 // namespace scope other than global scope or declared static in global
9753 // scope.
9754 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9755 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009756
9757 CanQualType SizeTy =
9758 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9759
9760 // C++ [basic.stc.dynamic.allocation]p1:
9761 // The return type shall be void*. The first parameter shall have type
9762 // std::size_t.
9763 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9764 SizeTy,
9765 diag::err_operator_new_dependent_param_type,
9766 diag::err_operator_new_param_type))
9767 return true;
9768
9769 // C++ [basic.stc.dynamic.allocation]p1:
9770 // The first parameter shall not have an associated default argument.
9771 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009772 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009773 diag::err_operator_new_default_arg)
9774 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9775
9776 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009777}
9778
9779static bool
Richard Smith444d3842012-10-20 08:26:51 +00009780CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009781 // C++ [basic.stc.dynamic.deallocation]p1:
9782 // A program is ill-formed if deallocation functions are declared in a
9783 // namespace scope other than global scope or declared static in global
9784 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009785 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9786 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009787
9788 // C++ [basic.stc.dynamic.deallocation]p2:
9789 // Each deallocation function shall return void and its first parameter
9790 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009791 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9792 SemaRef.Context.VoidPtrTy,
9793 diag::err_operator_delete_dependent_param_type,
9794 diag::err_operator_delete_param_type))
9795 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009796
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009797 return false;
9798}
9799
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009800/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9801/// of this overloaded operator is well-formed. If so, returns false;
9802/// otherwise, emits appropriate diagnostics and returns true.
9803bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009804 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009805 "Expected an overloaded operator declaration");
9806
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009807 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9808
Mike Stump1eb44332009-09-09 15:08:12 +00009809 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009810 // The allocation and deallocation functions, operator new,
9811 // operator new[], operator delete and operator delete[], are
9812 // described completely in 3.7.3. The attributes and restrictions
9813 // found in the rest of this subclause do not apply to them unless
9814 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009815 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009816 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009817
Anders Carlssona3ccda52009-12-12 00:26:23 +00009818 if (Op == OO_New || Op == OO_Array_New)
9819 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009820
9821 // C++ [over.oper]p6:
9822 // An operator function shall either be a non-static member
9823 // function or be a non-member function and have at least one
9824 // parameter whose type is a class, a reference to a class, an
9825 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009826 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9827 if (MethodDecl->isStatic())
9828 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009829 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009830 } else {
9831 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009832 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9833 ParamEnd = FnDecl->param_end();
9834 Param != ParamEnd; ++Param) {
9835 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009836 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9837 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009838 ClassOrEnumParam = true;
9839 break;
9840 }
9841 }
9842
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009843 if (!ClassOrEnumParam)
9844 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009845 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009846 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009847 }
9848
9849 // C++ [over.oper]p8:
9850 // An operator function cannot have default arguments (8.3.6),
9851 // except where explicitly stated below.
9852 //
Mike Stump1eb44332009-09-09 15:08:12 +00009853 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009854 // (C++ [over.call]p1).
9855 if (Op != OO_Call) {
9856 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9857 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009858 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009859 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009860 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009861 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009862 }
9863 }
9864
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009865 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9866 { false, false, false }
9867#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9868 , { Unary, Binary, MemberOnly }
9869#include "clang/Basic/OperatorKinds.def"
9870 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009871
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009872 bool CanBeUnaryOperator = OperatorUses[Op][0];
9873 bool CanBeBinaryOperator = OperatorUses[Op][1];
9874 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009875
9876 // C++ [over.oper]p8:
9877 // [...] Operator functions cannot have more or fewer parameters
9878 // than the number required for the corresponding operator, as
9879 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009880 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009881 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009882 if (Op != OO_Call &&
9883 ((NumParams == 1 && !CanBeUnaryOperator) ||
9884 (NumParams == 2 && !CanBeBinaryOperator) ||
9885 (NumParams < 1) || (NumParams > 2))) {
9886 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009887 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009888 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009889 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009890 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009891 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009892 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009893 assert(CanBeBinaryOperator &&
9894 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009895 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009896 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009897
Chris Lattner416e46f2008-11-21 07:57:12 +00009898 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009899 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009900 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009901
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009902 // Overloaded operators other than operator() cannot be variadic.
9903 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009904 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009905 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009906 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009907 }
9908
9909 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009910 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9911 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009912 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009913 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009914 }
9915
9916 // C++ [over.inc]p1:
9917 // The user-defined function called operator++ implements the
9918 // prefix and postfix ++ operator. If this function is a member
9919 // function with no parameters, or a non-member function with one
9920 // parameter of class or enumeration type, it defines the prefix
9921 // increment operator ++ for objects of that type. If the function
9922 // is a member function with one parameter (which shall be of type
9923 // int) or a non-member function with two parameters (the second
9924 // of which shall be of type int), it defines the postfix
9925 // increment operator ++ for objects of that type.
9926 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9927 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9928 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009929 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009930 ParamIsInt = BT->getKind() == BuiltinType::Int;
9931
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009932 if (!ParamIsInt)
9933 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009934 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009935 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009936 }
9937
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009938 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009939}
Chris Lattner5a003a42008-12-17 07:09:26 +00009940
Sean Hunta6c058d2010-01-13 09:01:02 +00009941/// CheckLiteralOperatorDeclaration - Check whether the declaration
9942/// of this literal operator function is well-formed. If so, returns
9943/// false; otherwise, emits appropriate diagnostics and returns true.
9944bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009945 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009946 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9947 << FnDecl->getDeclName();
9948 return true;
9949 }
9950
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009951 if (FnDecl->isExternC()) {
9952 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9953 return true;
9954 }
9955
Sean Hunta6c058d2010-01-13 09:01:02 +00009956 bool Valid = false;
9957
Richard Smith36f5cfe2012-03-09 08:00:36 +00009958 // This might be the definition of a literal operator template.
9959 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9960 // This might be a specialization of a literal operator template.
9961 if (!TpDecl)
9962 TpDecl = FnDecl->getPrimaryTemplate();
9963
Sean Hunt216c2782010-04-07 23:11:06 +00009964 // template <char...> type operator "" name() is the only valid template
9965 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009966 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009967 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009968 // Must have only one template parameter
9969 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9970 if (Params->size() == 1) {
9971 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009972 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009973
Sean Hunt216c2782010-04-07 23:11:06 +00009974 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009975 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9976 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9977 Valid = true;
9978 }
9979 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009980 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009981 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009982 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9983
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009984 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009985
Sean Hunt30019c02010-04-07 22:57:35 +00009986 // unsigned long long int, long double, and any character type are allowed
9987 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009988 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9989 Context.hasSameType(T, Context.LongDoubleTy) ||
9990 Context.hasSameType(T, Context.CharTy) ||
9991 Context.hasSameType(T, Context.WCharTy) ||
9992 Context.hasSameType(T, Context.Char16Ty) ||
9993 Context.hasSameType(T, Context.Char32Ty)) {
9994 if (++Param == FnDecl->param_end())
9995 Valid = true;
9996 goto FinishedParams;
9997 }
9998
Sean Hunt30019c02010-04-07 22:57:35 +00009999 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010000 const PointerType *PT = T->getAs<PointerType>();
10001 if (!PT)
10002 goto FinishedParams;
10003 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010004 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010005 goto FinishedParams;
10006 T = T.getUnqualifiedType();
10007
10008 // Move on to the second parameter;
10009 ++Param;
10010
10011 // If there is no second parameter, the first must be a const char *
10012 if (Param == FnDecl->param_end()) {
10013 if (Context.hasSameType(T, Context.CharTy))
10014 Valid = true;
10015 goto FinishedParams;
10016 }
10017
10018 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10019 // are allowed as the first parameter to a two-parameter function
10020 if (!(Context.hasSameType(T, Context.CharTy) ||
10021 Context.hasSameType(T, Context.WCharTy) ||
10022 Context.hasSameType(T, Context.Char16Ty) ||
10023 Context.hasSameType(T, Context.Char32Ty)))
10024 goto FinishedParams;
10025
10026 // The second and final parameter must be an std::size_t
10027 T = (*Param)->getType().getUnqualifiedType();
10028 if (Context.hasSameType(T, Context.getSizeType()) &&
10029 ++Param == FnDecl->param_end())
10030 Valid = true;
10031 }
10032
10033 // FIXME: This diagnostic is absolutely terrible.
10034FinishedParams:
10035 if (!Valid) {
10036 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10037 << FnDecl->getDeclName();
10038 return true;
10039 }
10040
Richard Smitha9e88b22012-03-09 08:16:22 +000010041 // A parameter-declaration-clause containing a default argument is not
10042 // equivalent to any of the permitted forms.
10043 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10044 ParamEnd = FnDecl->param_end();
10045 Param != ParamEnd; ++Param) {
10046 if ((*Param)->hasDefaultArg()) {
10047 Diag((*Param)->getDefaultArgRange().getBegin(),
10048 diag::err_literal_operator_default_argument)
10049 << (*Param)->getDefaultArgRange();
10050 break;
10051 }
10052 }
10053
Richard Smith2fb4ae32012-03-08 02:39:21 +000010054 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010055 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10056 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010057 // C++11 [usrlit.suffix]p1:
10058 // Literal suffix identifiers that do not start with an underscore
10059 // are reserved for future standardization.
10060 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010061 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010062
Sean Hunta6c058d2010-01-13 09:01:02 +000010063 return false;
10064}
10065
Douglas Gregor074149e2009-01-05 19:45:36 +000010066/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10067/// linkage specification, including the language and (if present)
10068/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10069/// the location of the language string literal, which is provided
10070/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10071/// the '{' brace. Otherwise, this linkage specification does not
10072/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010073Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10074 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010075 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010076 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010077 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010078 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010079 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010080 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010081 Language = LinkageSpecDecl::lang_cxx;
10082 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010083 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010084 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010085 }
Mike Stump1eb44332009-09-09 15:08:12 +000010086
Chris Lattnercc98eac2008-12-17 07:13:27 +000010087 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010088
Douglas Gregor074149e2009-01-05 19:45:36 +000010089 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010090 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010091 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010092 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010093 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010094}
10095
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010096/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010097/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10098/// valid, it's the position of the closing '}' brace in a linkage
10099/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010100Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010101 Decl *LinkageSpec,
10102 SourceLocation RBraceLoc) {
10103 if (LinkageSpec) {
10104 if (RBraceLoc.isValid()) {
10105 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10106 LSDecl->setRBraceLoc(RBraceLoc);
10107 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010108 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010109 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010110 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010111}
10112
Michael Han684aa732013-02-22 17:15:32 +000010113Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10114 AttributeList *AttrList,
10115 SourceLocation SemiLoc) {
10116 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10117 // Attribute declarations appertain to empty declaration so we handle
10118 // them here.
10119 if (AttrList)
10120 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010121
Michael Han684aa732013-02-22 17:15:32 +000010122 CurContext->addDecl(ED);
10123 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010124}
10125
Douglas Gregord308e622009-05-18 20:51:54 +000010126/// \brief Perform semantic analysis for the variable declaration that
10127/// occurs within a C++ catch clause, returning the newly-created
10128/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010129VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010130 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010131 SourceLocation StartLoc,
10132 SourceLocation Loc,
10133 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010134 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010135 QualType ExDeclType = TInfo->getType();
10136
Sebastian Redl4b07b292008-12-22 19:15:10 +000010137 // Arrays and functions decay.
10138 if (ExDeclType->isArrayType())
10139 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10140 else if (ExDeclType->isFunctionType())
10141 ExDeclType = Context.getPointerType(ExDeclType);
10142
10143 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10144 // The exception-declaration shall not denote a pointer or reference to an
10145 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010146 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010147 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010148 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010149 Invalid = true;
10150 }
Douglas Gregord308e622009-05-18 20:51:54 +000010151
Sebastian Redl4b07b292008-12-22 19:15:10 +000010152 QualType BaseType = ExDeclType;
10153 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010154 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010155 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010156 BaseType = Ptr->getPointeeType();
10157 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010158 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010159 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010160 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010161 BaseType = Ref->getPointeeType();
10162 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010163 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010164 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010165 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010166 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010167 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010168
Mike Stump1eb44332009-09-09 15:08:12 +000010169 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010170 RequireNonAbstractType(Loc, ExDeclType,
10171 diag::err_abstract_type_in_decl,
10172 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010173 Invalid = true;
10174
John McCall5a180392010-07-24 00:37:23 +000010175 // Only the non-fragile NeXT runtime currently supports C++ catches
10176 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010177 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010178 QualType T = ExDeclType;
10179 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10180 T = RT->getPointeeType();
10181
10182 if (T->isObjCObjectType()) {
10183 Diag(Loc, diag::err_objc_object_catch);
10184 Invalid = true;
10185 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010186 // FIXME: should this be a test for macosx-fragile specifically?
10187 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010188 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010189 }
10190 }
10191
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010192 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10193 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010194 ExDecl->setExceptionVariable(true);
10195
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010196 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010197 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010198 Invalid = true;
10199
Douglas Gregorc41b8782011-07-06 18:14:43 +000010200 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010201 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010202 // C++ [except.handle]p16:
10203 // The object declared in an exception-declaration or, if the
10204 // exception-declaration does not specify a name, a temporary (12.2) is
10205 // copy-initialized (8.5) from the exception object. [...]
10206 // The object is destroyed when the handler exits, after the destruction
10207 // of any automatic objects initialized within the handler.
10208 //
10209 // We just pretend to initialize the object with itself, then make sure
10210 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010211 QualType initType = ExDeclType;
10212
10213 InitializedEntity entity =
10214 InitializedEntity::InitializeVariable(ExDecl);
10215 InitializationKind initKind =
10216 InitializationKind::CreateCopy(Loc, SourceLocation());
10217
10218 Expr *opaqueValue =
10219 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10220 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10221 ExprResult result = sequence.Perform(*this, entity, initKind,
10222 MultiExprArg(&opaqueValue, 1));
10223 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010224 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010225 else {
10226 // If the constructor used was non-trivial, set this as the
10227 // "initializer".
10228 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10229 if (!construct->getConstructor()->isTrivial()) {
10230 Expr *init = MaybeCreateExprWithCleanups(construct);
10231 ExDecl->setInit(init);
10232 }
10233
10234 // And make sure it's destructable.
10235 FinalizeVarWithDestructor(ExDecl, recordType);
10236 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010237 }
10238 }
10239
Douglas Gregord308e622009-05-18 20:51:54 +000010240 if (Invalid)
10241 ExDecl->setInvalidDecl();
10242
10243 return ExDecl;
10244}
10245
10246/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10247/// handler.
John McCalld226f652010-08-21 09:40:31 +000010248Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010249 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010250 bool Invalid = D.isInvalidType();
10251
10252 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010253 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10254 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010255 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10256 D.getIdentifierLoc());
10257 Invalid = true;
10258 }
10259
Sebastian Redl4b07b292008-12-22 19:15:10 +000010260 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010261 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010262 LookupOrdinaryName,
10263 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010264 // The scope should be freshly made just for us. There is just no way
10265 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010266 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010267 if (PrevDecl->isTemplateParameter()) {
10268 // Maybe we will complain about the shadowed template parameter.
10269 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010270 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010271 }
10272 }
10273
Chris Lattnereaaebc72009-04-25 08:06:05 +000010274 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010275 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10276 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010277 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010278 }
10279
Douglas Gregor83cb9422010-09-09 17:09:21 +000010280 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010281 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010282 D.getIdentifierLoc(),
10283 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010284 if (Invalid)
10285 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010286
Sebastian Redl4b07b292008-12-22 19:15:10 +000010287 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010288 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010289 PushOnScopeChains(ExDecl, S);
10290 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010291 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010292
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010293 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010294 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010295}
Anders Carlssonfb311762009-03-14 00:25:26 +000010296
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010297Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010298 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010299 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010300 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010301 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010302
Richard Smithe3f470a2012-07-11 22:37:56 +000010303 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10304 return 0;
10305
10306 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10307 AssertMessage, RParenLoc, false);
10308}
10309
10310Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10311 Expr *AssertExpr,
10312 StringLiteral *AssertMessage,
10313 SourceLocation RParenLoc,
10314 bool Failed) {
10315 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10316 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010317 // In a static_assert-declaration, the constant-expression shall be a
10318 // constant expression that can be contextually converted to bool.
10319 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10320 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010321 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010322
Richard Smithdaaefc52011-12-14 23:32:26 +000010323 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010324 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010325 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010326 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010327 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010328
Richard Smithe3f470a2012-07-11 22:37:56 +000010329 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010330 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010331 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010332 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010333 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010334 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010335 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010336 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010337 }
Mike Stump1eb44332009-09-09 15:08:12 +000010338
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010339 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010340 AssertExpr, AssertMessage, RParenLoc,
10341 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010342
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010343 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010344 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010345}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010346
Douglas Gregor1d869352010-04-07 16:53:43 +000010347/// \brief Perform semantic analysis of the given friend type declaration.
10348///
10349/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010350FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010351 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010352 TypeSourceInfo *TSInfo) {
10353 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10354
10355 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010356 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010357
Richard Smith6b130222011-10-18 21:39:00 +000010358 // C++03 [class.friend]p2:
10359 // An elaborated-type-specifier shall be used in a friend declaration
10360 // for a class.*
10361 //
10362 // * The class-key of the elaborated-type-specifier is required.
10363 if (!ActiveTemplateInstantiations.empty()) {
10364 // Do not complain about the form of friend template types during
10365 // template instantiation; we will already have complained when the
10366 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010367 } else {
10368 if (!T->isElaboratedTypeSpecifier()) {
10369 // If we evaluated the type to a record type, suggest putting
10370 // a tag in front.
10371 if (const RecordType *RT = T->getAs<RecordType>()) {
10372 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010373
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010374 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010375
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010376 Diag(TypeRange.getBegin(),
10377 getLangOpts().CPlusPlus11 ?
10378 diag::warn_cxx98_compat_unelaborated_friend_type :
10379 diag::ext_unelaborated_friend_type)
10380 << (unsigned) RD->getTagKind()
10381 << T
10382 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10383 InsertionText);
10384 } else {
10385 Diag(FriendLoc,
10386 getLangOpts().CPlusPlus11 ?
10387 diag::warn_cxx98_compat_nonclass_type_friend :
10388 diag::ext_nonclass_type_friend)
10389 << T
10390 << TypeRange;
10391 }
10392 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010393 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010394 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010395 diag::warn_cxx98_compat_enum_friend :
10396 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010397 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010398 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010399 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010400
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010401 // C++11 [class.friend]p3:
10402 // A friend declaration that does not declare a function shall have one
10403 // of the following forms:
10404 // friend elaborated-type-specifier ;
10405 // friend simple-type-specifier ;
10406 // friend typename-specifier ;
10407 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10408 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10409 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010410
Douglas Gregor06245bf2010-04-07 17:57:12 +000010411 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010412 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010413 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010414 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010415}
10416
John McCall9a34edb2010-10-19 01:40:49 +000010417/// Handle a friend tag declaration where the scope specifier was
10418/// templated.
10419Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10420 unsigned TagSpec, SourceLocation TagLoc,
10421 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010422 IdentifierInfo *Name,
10423 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000010424 AttributeList *Attr,
10425 MultiTemplateParamsArg TempParamLists) {
10426 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10427
10428 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010429 bool Invalid = false;
10430
10431 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010432 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010433 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010434 TempParamLists.size(),
10435 /*friend*/ true,
10436 isExplicitSpecialization,
10437 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010438 if (TemplateParams->size() > 0) {
10439 // This is a declaration of a class template.
10440 if (Invalid)
10441 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010442
Eric Christopher4110e132011-07-21 05:34:24 +000010443 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10444 SS, Name, NameLoc, Attr,
10445 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010446 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010447 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010448 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010449 } else {
10450 // The "template<>" header is extraneous.
10451 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10452 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10453 isExplicitSpecialization = true;
10454 }
10455 }
10456
10457 if (Invalid) return 0;
10458
John McCall9a34edb2010-10-19 01:40:49 +000010459 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010460 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010461 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010462 isAllExplicitSpecializations = false;
10463 break;
10464 }
10465 }
10466
10467 // FIXME: don't ignore attributes.
10468
10469 // If it's explicit specializations all the way down, just forget
10470 // about the template header and build an appropriate non-templated
10471 // friend. TODO: for source fidelity, remember the headers.
10472 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010473 if (SS.isEmpty()) {
10474 bool Owned = false;
10475 bool IsDependent = false;
10476 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10477 Attr, AS_public,
10478 /*ModulePrivateLoc=*/SourceLocation(),
10479 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010480 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010481 /*ScopedEnumUsesClassTag=*/false,
10482 /*UnderlyingType=*/TypeResult());
10483 }
10484
Douglas Gregor2494dd02011-03-01 01:34:45 +000010485 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010486 ElaboratedTypeKeyword Keyword
10487 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010488 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010489 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010490 if (T.isNull())
10491 return 0;
10492
10493 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10494 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000010495 DependentNameTypeLoc TL =
10496 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010497 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010498 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010499 TL.setNameLoc(NameLoc);
10500 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000010501 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010502 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010503 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000010504 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010505 }
10506
10507 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010508 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010509 Friend->setAccess(AS_public);
10510 CurContext->addDecl(Friend);
10511 return Friend;
10512 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010513
10514 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10515
10516
John McCall9a34edb2010-10-19 01:40:49 +000010517
10518 // Handle the case of a templated-scope friend class. e.g.
10519 // template <class T> class A<T>::B;
10520 // FIXME: we don't support these right now.
10521 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10522 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10523 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000010524 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000010525 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010526 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010527 TL.setNameLoc(NameLoc);
10528
10529 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010530 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000010531 Friend->setAccess(AS_public);
10532 Friend->setUnsupportedFriend(true);
10533 CurContext->addDecl(Friend);
10534 return Friend;
10535}
10536
10537
John McCalldd4a3b02009-09-16 22:47:08 +000010538/// Handle a friend type declaration. This works in tandem with
10539/// ActOnTag.
10540///
10541/// Notes on friend class templates:
10542///
10543/// We generally treat friend class declarations as if they were
10544/// declaring a class. So, for example, the elaborated type specifier
10545/// in a friend declaration is required to obey the restrictions of a
10546/// class-head (i.e. no typedefs in the scope chain), template
10547/// parameters are required to match up with simple template-ids, &c.
10548/// However, unlike when declaring a template specialization, it's
10549/// okay to refer to a template specialization without an empty
10550/// template parameter declaration, e.g.
10551/// friend class A<T>::B<unsigned>;
10552/// We permit this as a special case; if there are any template
10553/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010554/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010555Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010556 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010557 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010558
10559 assert(DS.isFriendSpecified());
10560 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10561
John McCalldd4a3b02009-09-16 22:47:08 +000010562 // Try to convert the decl specifier to a type. This works for
10563 // friend templates because ActOnTag never produces a ClassTemplateDecl
10564 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010565 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010566 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10567 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010568 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010569 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010570
Douglas Gregor6ccab972010-12-16 01:14:37 +000010571 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10572 return 0;
10573
John McCalldd4a3b02009-09-16 22:47:08 +000010574 // This is definitely an error in C++98. It's probably meant to
10575 // be forbidden in C++0x, too, but the specification is just
10576 // poorly written.
10577 //
10578 // The problem is with declarations like the following:
10579 // template <T> friend A<T>::foo;
10580 // where deciding whether a class C is a friend or not now hinges
10581 // on whether there exists an instantiation of A that causes
10582 // 'foo' to equal C. There are restrictions on class-heads
10583 // (which we declare (by fiat) elaborated friend declarations to
10584 // be) that makes this tractable.
10585 //
10586 // FIXME: handle "template <> friend class A<T>;", which
10587 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010588 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010589 Diag(Loc, diag::err_tagless_friend_type_template)
10590 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010591 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010592 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010593
John McCall02cace72009-08-28 07:59:38 +000010594 // C++98 [class.friend]p1: A friend of a class is a function
10595 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010596 // This is fixed in DR77, which just barely didn't make the C++03
10597 // deadline. It's also a very silly restriction that seriously
10598 // affects inner classes and which nobody else seems to implement;
10599 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010600 //
10601 // But note that we could warn about it: it's always useless to
10602 // friend one of your own members (it's not, however, worthless to
10603 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010604
John McCalldd4a3b02009-09-16 22:47:08 +000010605 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010606 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010607 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010608 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010609 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010610 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010611 DS.getFriendSpecLoc());
10612 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010613 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010614
10615 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010616 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010617
John McCalldd4a3b02009-09-16 22:47:08 +000010618 D->setAccess(AS_public);
10619 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010620
John McCalld226f652010-08-21 09:40:31 +000010621 return D;
John McCall02cace72009-08-28 07:59:38 +000010622}
10623
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000010624NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10625 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010626 const DeclSpec &DS = D.getDeclSpec();
10627
10628 assert(DS.isFriendSpecified());
10629 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10630
10631 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010632 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010633
10634 // C++ [class.friend]p1
10635 // A friend of a class is a function or class....
10636 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010637 // It *doesn't* see through dependent types, which is correct
10638 // according to [temp.arg.type]p3:
10639 // If a declaration acquires a function type through a
10640 // type dependent on a template-parameter and this causes
10641 // a declaration that does not use the syntactic form of a
10642 // function declarator to have a function type, the program
10643 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010644 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010645 Diag(Loc, diag::err_unexpected_friend);
10646
10647 // It might be worthwhile to try to recover by creating an
10648 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010649 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010650 }
10651
10652 // C++ [namespace.memdef]p3
10653 // - If a friend declaration in a non-local class first declares a
10654 // class or function, the friend class or function is a member
10655 // of the innermost enclosing namespace.
10656 // - The name of the friend is not found by simple name lookup
10657 // until a matching declaration is provided in that namespace
10658 // scope (either before or after the class declaration granting
10659 // friendship).
10660 // - If a friend function is called, its name may be found by the
10661 // name lookup that considers functions from namespaces and
10662 // classes associated with the types of the function arguments.
10663 // - When looking for a prior declaration of a class or a function
10664 // declared as a friend, scopes outside the innermost enclosing
10665 // namespace scope are not considered.
10666
John McCall337ec3d2010-10-12 23:13:28 +000010667 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010668 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10669 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010670 assert(Name);
10671
Douglas Gregor6ccab972010-12-16 01:14:37 +000010672 // Check for unexpanded parameter packs.
10673 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10674 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10675 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10676 return 0;
10677
John McCall67d1a672009-08-06 02:15:43 +000010678 // The context we found the declaration in, or in which we should
10679 // create the declaration.
10680 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010681 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010682 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010683 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010684
John McCall337ec3d2010-10-12 23:13:28 +000010685 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010686
John McCall337ec3d2010-10-12 23:13:28 +000010687 // There are four cases here.
10688 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010689 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010690 // there as appropriate.
10691 // Recover from invalid scope qualifiers as if they just weren't there.
10692 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010693 // C++0x [namespace.memdef]p3:
10694 // If the name in a friend declaration is neither qualified nor
10695 // a template-id and the declaration is a function or an
10696 // elaborated-type-specifier, the lookup to determine whether
10697 // the entity has been previously declared shall not consider
10698 // any scopes outside the innermost enclosing namespace.
10699 // C++0x [class.friend]p11:
10700 // If a friend declaration appears in a local class and the name
10701 // specified is an unqualified name, a prior declaration is
10702 // looked up without considering scopes that are outside the
10703 // innermost enclosing non-class scope. For a friend function
10704 // declaration, if there is no prior declaration, the program is
10705 // ill-formed.
10706 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010707 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010708
John McCall29ae6e52010-10-13 05:45:15 +000010709 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010710 DC = CurContext;
10711 while (true) {
10712 // Skip class contexts. If someone can cite chapter and verse
10713 // for this behavior, that would be nice --- it's what GCC and
10714 // EDG do, and it seems like a reasonable intent, but the spec
10715 // really only says that checks for unqualified existing
10716 // declarations should stop at the nearest enclosing namespace,
10717 // not that they should only consider the nearest enclosing
10718 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010719 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010720 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010721
John McCall68263142009-11-18 22:49:29 +000010722 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010723
10724 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010725 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010726 break;
John McCall29ae6e52010-10-13 05:45:15 +000010727
John McCall8a407372010-10-14 22:22:28 +000010728 if (isTemplateId) {
10729 if (isa<TranslationUnitDecl>(DC)) break;
10730 } else {
10731 if (DC->isFileContext()) break;
10732 }
John McCall67d1a672009-08-06 02:15:43 +000010733 DC = DC->getParent();
10734 }
10735
10736 // C++ [class.friend]p1: A friend of a class is a function or
10737 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010738 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010739 // Most C++ 98 compilers do seem to give an error here, so
10740 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010741 if (!Previous.empty() && DC->Equals(CurContext))
10742 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010743 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010744 diag::warn_cxx98_compat_friend_is_member :
10745 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010746
John McCall380aaa42010-10-13 06:22:15 +000010747 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010748
Douglas Gregor883af832011-10-10 01:11:59 +000010749 // C++ [class.friend]p6:
10750 // A function can be defined in a friend declaration of a class if and
10751 // only if the class is a non-local class (9.8), the function name is
10752 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010753 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010754 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10755 }
10756
John McCall337ec3d2010-10-12 23:13:28 +000010757 // - There's a non-dependent scope specifier, in which case we
10758 // compute it and do a previous lookup there for a function
10759 // or function template.
10760 } else if (!SS.getScopeRep()->isDependent()) {
10761 DC = computeDeclContext(SS);
10762 if (!DC) return 0;
10763
10764 if (RequireCompleteDeclContext(SS, DC)) return 0;
10765
10766 LookupQualifiedName(Previous, DC);
10767
10768 // Ignore things found implicitly in the wrong scope.
10769 // TODO: better diagnostics for this case. Suggesting the right
10770 // qualified scope would be nice...
10771 LookupResult::Filter F = Previous.makeFilter();
10772 while (F.hasNext()) {
10773 NamedDecl *D = F.next();
10774 if (!DC->InEnclosingNamespaceSetOf(
10775 D->getDeclContext()->getRedeclContext()))
10776 F.erase();
10777 }
10778 F.done();
10779
10780 if (Previous.empty()) {
10781 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010782 Diag(Loc, diag::err_qualified_friend_not_found)
10783 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010784 return 0;
10785 }
10786
10787 // C++ [class.friend]p1: A friend of a class is a function or
10788 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010789 if (DC->Equals(CurContext))
10790 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000010791 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010792 diag::warn_cxx98_compat_friend_is_member :
10793 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010794
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010795 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010796 // C++ [class.friend]p6:
10797 // A function can be defined in a friend declaration of a class if and
10798 // only if the class is a non-local class (9.8), the function name is
10799 // unqualified, and the function has namespace scope.
10800 SemaDiagnosticBuilder DB
10801 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10802
10803 DB << SS.getScopeRep();
10804 if (DC->isFileContext())
10805 DB << FixItHint::CreateRemoval(SS.getRange());
10806 SS.clear();
10807 }
John McCall337ec3d2010-10-12 23:13:28 +000010808
10809 // - There's a scope specifier that does not match any template
10810 // parameter lists, in which case we use some arbitrary context,
10811 // create a method or method template, and wait for instantiation.
10812 // - There's a scope specifier that does match some template
10813 // parameter lists, which we don't handle right now.
10814 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010815 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010816 // C++ [class.friend]p6:
10817 // A function can be defined in a friend declaration of a class if and
10818 // only if the class is a non-local class (9.8), the function name is
10819 // unqualified, and the function has namespace scope.
10820 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10821 << SS.getScopeRep();
10822 }
10823
John McCall337ec3d2010-10-12 23:13:28 +000010824 DC = CurContext;
10825 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010826 }
Douglas Gregor883af832011-10-10 01:11:59 +000010827
John McCall29ae6e52010-10-13 05:45:15 +000010828 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010829 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010830 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10831 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10832 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010833 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010834 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10835 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010836 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010837 }
John McCall67d1a672009-08-06 02:15:43 +000010838 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010839
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010840 // FIXME: This is an egregious hack to cope with cases where the scope stack
10841 // does not contain the declaration context, i.e., in an out-of-line
10842 // definition of a class.
10843 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10844 if (!DCScope) {
10845 FakeDCScope.setEntity(DC);
10846 DCScope = &FakeDCScope;
10847 }
10848
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010849 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010850 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010851 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010852 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010853
Douglas Gregor182ddf02009-09-28 00:08:27 +000010854 assert(ND->getDeclContext() == DC);
10855 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010856
John McCallab88d972009-08-31 22:39:49 +000010857 // Add the function declaration to the appropriate lookup tables,
10858 // adjusting the redeclarations list as necessary. We don't
10859 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010860 //
John McCallab88d972009-08-31 22:39:49 +000010861 // Also update the scope-based lookup if the target context's
10862 // lookup context is in lexical scope.
10863 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010864 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010865 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010866 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010867 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010868 }
John McCall02cace72009-08-28 07:59:38 +000010869
10870 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010871 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010872 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010873 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010874 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010875
John McCall1f2e1a92012-08-10 03:15:35 +000010876 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010877 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010878 } else {
10879 if (DC->isRecord()) CheckFriendAccess(ND);
10880
John McCall6102ca12010-10-16 06:59:13 +000010881 FunctionDecl *FD;
10882 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10883 FD = FTD->getTemplatedDecl();
10884 else
10885 FD = cast<FunctionDecl>(ND);
10886
10887 // Mark templated-scope function declarations as unsupported.
10888 if (FD->getNumTemplateParameterLists())
10889 FrD->setUnsupportedFriend(true);
10890 }
John McCall337ec3d2010-10-12 23:13:28 +000010891
John McCalld226f652010-08-21 09:40:31 +000010892 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010893}
10894
John McCalld226f652010-08-21 09:40:31 +000010895void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10896 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010897
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010898 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000010899 if (!Fn) {
10900 Diag(DelLoc, diag::err_deleted_non_function);
10901 return;
10902 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010903 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010904 // Don't consider the implicit declaration we generate for explicit
10905 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010906 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10907 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010908 Diag(DelLoc, diag::err_deleted_decl_not_first);
10909 Diag(Prev->getLocation(), diag::note_previous_declaration);
10910 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010911 // If the declaration wasn't the first, we delete the function anyway for
10912 // recovery.
10913 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010914 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010915}
Sebastian Redl13e88542009-04-27 21:33:24 +000010916
Sean Hunte4246a62011-05-12 06:15:49 +000010917void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000010918 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000010919
10920 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010921 if (MD->getParent()->isDependentType()) {
10922 MD->setDefaulted();
10923 MD->setExplicitlyDefaulted();
10924 return;
10925 }
10926
Sean Hunte4246a62011-05-12 06:15:49 +000010927 CXXSpecialMember Member = getSpecialMember(MD);
10928 if (Member == CXXInvalid) {
10929 Diag(DefaultLoc, diag::err_default_special_members);
10930 return;
10931 }
10932
10933 MD->setDefaulted();
10934 MD->setExplicitlyDefaulted();
10935
Sean Huntcd10dec2011-05-23 23:14:04 +000010936 // If this definition appears within the record, do the checking when
10937 // the record is complete.
10938 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010939 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010940 // Find the uninstantiated declaration that actually had the '= default'
10941 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010942 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010943
10944 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010945 return;
10946
Richard Smithb9d0b762012-07-27 04:22:15 +000010947 CheckExplicitlyDefaultedSpecialMember(MD);
10948
Richard Smith1d28caf2012-12-11 01:14:52 +000010949 // The exception specification is needed because we are defining the
10950 // function.
10951 ResolveExceptionSpec(DefaultLoc,
10952 MD->getType()->castAs<FunctionProtoType>());
10953
Sean Hunte4246a62011-05-12 06:15:49 +000010954 switch (Member) {
10955 case CXXDefaultConstructor: {
10956 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010957 if (!CD->isInvalidDecl())
10958 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10959 break;
10960 }
10961
10962 case CXXCopyConstructor: {
10963 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010964 if (!CD->isInvalidDecl())
10965 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010966 break;
10967 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010968
Sean Hunt2b188082011-05-14 05:23:28 +000010969 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010970 if (!MD->isInvalidDecl())
10971 DefineImplicitCopyAssignment(DefaultLoc, MD);
10972 break;
10973 }
10974
Sean Huntcb45a0f2011-05-12 22:46:25 +000010975 case CXXDestructor: {
10976 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010977 if (!DD->isInvalidDecl())
10978 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010979 break;
10980 }
10981
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010982 case CXXMoveConstructor: {
10983 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010984 if (!CD->isInvalidDecl())
10985 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010986 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010987 }
Sean Hunt82713172011-05-25 23:16:36 +000010988
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010989 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010990 if (!MD->isInvalidDecl())
10991 DefineImplicitMoveAssignment(DefaultLoc, MD);
10992 break;
10993 }
10994
10995 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010996 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010997 }
10998 } else {
10999 Diag(DefaultLoc, diag::err_default_special_members);
11000 }
11001}
11002
Sebastian Redl13e88542009-04-27 21:33:24 +000011003static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011004 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011005 Stmt *SubStmt = *CI;
11006 if (!SubStmt)
11007 continue;
11008 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011009 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011010 diag::err_return_in_constructor_handler);
11011 if (!isa<Expr>(SubStmt))
11012 SearchForReturnInStmt(Self, SubStmt);
11013 }
11014}
11015
11016void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11017 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11018 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11019 SearchForReturnInStmt(*this, Handler);
11020 }
11021}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011022
David Blaikie299adab2013-01-18 23:03:15 +000011023bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011024 const CXXMethodDecl *Old) {
11025 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11026 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11027
11028 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11029
11030 // If the calling conventions match, everything is fine
11031 if (NewCC == OldCC)
11032 return false;
11033
11034 // If either of the calling conventions are set to "default", we need to pick
11035 // something more sensible based on the target. This supports code where the
11036 // one method explicitly sets thiscall, and another has no explicit calling
11037 // convention.
11038 CallingConv Default =
11039 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11040 if (NewCC == CC_Default)
11041 NewCC = Default;
11042 if (OldCC == CC_Default)
11043 OldCC = Default;
11044
11045 // If the calling conventions still don't match, then report the error
11046 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011047 Diag(New->getLocation(),
11048 diag::err_conflicting_overriding_cc_attributes)
11049 << New->getDeclName() << New->getType() << Old->getType();
11050 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11051 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011052 }
11053
11054 return false;
11055}
11056
Mike Stump1eb44332009-09-09 15:08:12 +000011057bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011058 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011059 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11060 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011061
Chandler Carruth73857792010-02-15 11:53:20 +000011062 if (Context.hasSameType(NewTy, OldTy) ||
11063 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011064 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011065
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011066 // Check if the return types are covariant
11067 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011068
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011069 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011070 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11071 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011072 NewClassTy = NewPT->getPointeeType();
11073 OldClassTy = OldPT->getPointeeType();
11074 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011075 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11076 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11077 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11078 NewClassTy = NewRT->getPointeeType();
11079 OldClassTy = OldRT->getPointeeType();
11080 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011081 }
11082 }
Mike Stump1eb44332009-09-09 15:08:12 +000011083
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011084 // The return types aren't either both pointers or references to a class type.
11085 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011086 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011087 diag::err_different_return_type_for_overriding_virtual_function)
11088 << New->getDeclName() << NewTy << OldTy;
11089 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011090
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011091 return true;
11092 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011093
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011094 // C++ [class.virtual]p6:
11095 // If the return type of D::f differs from the return type of B::f, the
11096 // class type in the return type of D::f shall be complete at the point of
11097 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011098 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11099 if (!RT->isBeingDefined() &&
11100 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011101 diag::err_covariant_return_incomplete,
11102 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011103 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011104 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011105
Douglas Gregora4923eb2009-11-16 21:35:15 +000011106 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011107 // Check if the new class derives from the old class.
11108 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11109 Diag(New->getLocation(),
11110 diag::err_covariant_return_not_derived)
11111 << New->getDeclName() << NewTy << OldTy;
11112 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11113 return true;
11114 }
Mike Stump1eb44332009-09-09 15:08:12 +000011115
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011116 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011117 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011118 diag::err_covariant_return_inaccessible_base,
11119 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11120 // FIXME: Should this point to the return type?
11121 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011122 // FIXME: this note won't trigger for delayed access control
11123 // diagnostics, and it's impossible to get an undelayed error
11124 // here from access control during the original parse because
11125 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011126 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11127 return true;
11128 }
11129 }
Mike Stump1eb44332009-09-09 15:08:12 +000011130
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011131 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011132 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011133 Diag(New->getLocation(),
11134 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011135 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011136 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11137 return true;
11138 };
Mike Stump1eb44332009-09-09 15:08:12 +000011139
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011140
11141 // The new class type must have the same or less qualifiers as the old type.
11142 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11143 Diag(New->getLocation(),
11144 diag::err_covariant_return_type_class_type_more_qualified)
11145 << New->getDeclName() << NewTy << OldTy;
11146 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11147 return true;
11148 };
Mike Stump1eb44332009-09-09 15:08:12 +000011149
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011150 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011151}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011152
Douglas Gregor4ba31362009-12-01 17:24:26 +000011153/// \brief Mark the given method pure.
11154///
11155/// \param Method the method to be marked pure.
11156///
11157/// \param InitRange the source range that covers the "0" initializer.
11158bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011159 SourceLocation EndLoc = InitRange.getEnd();
11160 if (EndLoc.isValid())
11161 Method->setRangeEnd(EndLoc);
11162
Douglas Gregor4ba31362009-12-01 17:24:26 +000011163 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11164 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011165 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011166 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011167
11168 if (!Method->isInvalidDecl())
11169 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11170 << Method->getDeclName() << InitRange;
11171 return true;
11172}
11173
Douglas Gregor552e2992012-02-21 02:22:07 +000011174/// \brief Determine whether the given declaration is a static data member.
11175static bool isStaticDataMember(Decl *D) {
11176 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11177 if (!Var)
11178 return false;
11179
11180 return Var->isStaticDataMember();
11181}
John McCall731ad842009-12-19 09:28:58 +000011182/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11183/// an initializer for the out-of-line declaration 'Dcl'. The scope
11184/// is a fresh scope pushed for just this purpose.
11185///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011186/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11187/// static data member of class X, names should be looked up in the scope of
11188/// class X.
John McCalld226f652010-08-21 09:40:31 +000011189void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011190 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011191 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011192
John McCall731ad842009-12-19 09:28:58 +000011193 // We should only get called for declarations with scope specifiers, like:
11194 // int foo::bar;
11195 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011196 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011197
11198 // If we are parsing the initializer for a static data member, push a
11199 // new expression evaluation context that is associated with this static
11200 // data member.
11201 if (isStaticDataMember(D))
11202 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011203}
11204
11205/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011206/// initializer for the out-of-line declaration 'D'.
11207void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011208 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011209 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011210
Douglas Gregor552e2992012-02-21 02:22:07 +000011211 if (isStaticDataMember(D))
11212 PopExpressionEvaluationContext();
11213
John McCall731ad842009-12-19 09:28:58 +000011214 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011215 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011216}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011217
11218/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11219/// C++ if/switch/while/for statement.
11220/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011221DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011222 // C++ 6.4p2:
11223 // The declarator shall not specify a function or an array.
11224 // The type-specifier-seq shall not contain typedef and shall not declare a
11225 // new class or enumeration.
11226 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11227 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011228
11229 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011230 if (!Dcl)
11231 return true;
11232
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011233 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11234 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011235 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011236 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011237 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011238
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011239 return Dcl;
11240}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011241
Douglas Gregordfe65432011-07-28 19:11:31 +000011242void Sema::LoadExternalVTableUses() {
11243 if (!ExternalSource)
11244 return;
11245
11246 SmallVector<ExternalVTableUse, 4> VTables;
11247 ExternalSource->ReadUsedVTables(VTables);
11248 SmallVector<VTableUse, 4> NewUses;
11249 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11250 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11251 = VTablesUsed.find(VTables[I].Record);
11252 // Even if a definition wasn't required before, it may be required now.
11253 if (Pos != VTablesUsed.end()) {
11254 if (!Pos->second && VTables[I].DefinitionRequired)
11255 Pos->second = true;
11256 continue;
11257 }
11258
11259 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11260 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11261 }
11262
11263 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11264}
11265
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011266void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11267 bool DefinitionRequired) {
11268 // Ignore any vtable uses in unevaluated operands or for classes that do
11269 // not have a vtable.
11270 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11271 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011272 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011273 return;
11274
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011275 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011276 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011277 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11278 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11279 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11280 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011281 // If we already had an entry, check to see if we are promoting this vtable
11282 // to required a definition. If so, we need to reappend to the VTableUses
11283 // list, since we may have already processed the first entry.
11284 if (DefinitionRequired && !Pos.first->second) {
11285 Pos.first->second = true;
11286 } else {
11287 // Otherwise, we can early exit.
11288 return;
11289 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011290 }
11291
11292 // Local classes need to have their virtual members marked
11293 // immediately. For all other classes, we mark their virtual members
11294 // at the end of the translation unit.
11295 if (Class->isLocalClass())
11296 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011297 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011298 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011299}
11300
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011301bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011302 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011303 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011304 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011305
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011306 // Note: The VTableUses vector could grow as a result of marking
11307 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011308 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011309 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011310 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011311 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011312 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011313 if (!Class)
11314 continue;
11315
11316 SourceLocation Loc = VTableUses[I].second;
11317
Richard Smithb9d0b762012-07-27 04:22:15 +000011318 bool DefineVTable = true;
11319
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011320 // If this class has a key function, but that key function is
11321 // defined in another translation unit, we don't need to emit the
11322 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011323 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011324 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011325 switch (KeyFunction->getTemplateSpecializationKind()) {
11326 case TSK_Undeclared:
11327 case TSK_ExplicitSpecialization:
11328 case TSK_ExplicitInstantiationDeclaration:
11329 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011330 DefineVTable = false;
11331 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011332
11333 case TSK_ExplicitInstantiationDefinition:
11334 case TSK_ImplicitInstantiation:
11335 // We will be instantiating the key function.
11336 break;
11337 }
11338 } else if (!KeyFunction) {
11339 // If we have a class with no key function that is the subject
11340 // of an explicit instantiation declaration, suppress the
11341 // vtable; it will live with the explicit instantiation
11342 // definition.
11343 bool IsExplicitInstantiationDeclaration
11344 = Class->getTemplateSpecializationKind()
11345 == TSK_ExplicitInstantiationDeclaration;
11346 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11347 REnd = Class->redecls_end();
11348 R != REnd; ++R) {
11349 TemplateSpecializationKind TSK
11350 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11351 if (TSK == TSK_ExplicitInstantiationDeclaration)
11352 IsExplicitInstantiationDeclaration = true;
11353 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11354 IsExplicitInstantiationDeclaration = false;
11355 break;
11356 }
11357 }
11358
11359 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011360 DefineVTable = false;
11361 }
11362
11363 // The exception specifications for all virtual members may be needed even
11364 // if we are not providing an authoritative form of the vtable in this TU.
11365 // We may choose to emit it available_externally anyway.
11366 if (!DefineVTable) {
11367 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11368 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011369 }
11370
11371 // Mark all of the virtual members of this class as referenced, so
11372 // that we can build a vtable. Then, tell the AST consumer that a
11373 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011374 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011375 MarkVirtualMembersReferenced(Loc, Class);
11376 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11377 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11378
11379 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola531db822013-03-07 02:00:27 +000011380 if (Class->hasExternalLinkage() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011381 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011382 const FunctionDecl *KeyFunctionDef = 0;
11383 if (!KeyFunction ||
11384 (KeyFunction->hasBody(KeyFunctionDef) &&
11385 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011386 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11387 TSK_ExplicitInstantiationDefinition
11388 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11389 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011390 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011391 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011392 VTableUses.clear();
11393
Douglas Gregor78844032011-04-22 22:25:37 +000011394 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011395}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011396
Richard Smithb9d0b762012-07-27 04:22:15 +000011397void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11398 const CXXRecordDecl *RD) {
11399 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11400 E = RD->method_end(); I != E; ++I)
11401 if ((*I)->isVirtual() && !(*I)->isPure())
11402 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11403}
11404
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011405void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11406 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011407 // Mark all functions which will appear in RD's vtable as used.
11408 CXXFinalOverriderMap FinalOverriders;
11409 RD->getFinalOverriders(FinalOverriders);
11410 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11411 E = FinalOverriders.end();
11412 I != E; ++I) {
11413 for (OverridingMethods::const_iterator OI = I->second.begin(),
11414 OE = I->second.end();
11415 OI != OE; ++OI) {
11416 assert(OI->second.size() > 0 && "no final overrider");
11417 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011418
Richard Smithff817f72012-07-07 06:59:51 +000011419 // C++ [basic.def.odr]p2:
11420 // [...] A virtual member function is used if it is not pure. [...]
11421 if (!Overrider->isPure())
11422 MarkFunctionReferenced(Loc, Overrider);
11423 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011424 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011425
11426 // Only classes that have virtual bases need a VTT.
11427 if (RD->getNumVBases() == 0)
11428 return;
11429
11430 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11431 e = RD->bases_end(); i != e; ++i) {
11432 const CXXRecordDecl *Base =
11433 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011434 if (Base->getNumVBases() == 0)
11435 continue;
11436 MarkVirtualMembersReferenced(Loc, Base);
11437 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011438}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011439
11440/// SetIvarInitializers - This routine builds initialization ASTs for the
11441/// Objective-C implementation whose ivars need be initialized.
11442void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011443 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011444 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011445 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011446 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011447 CollectIvarsToConstructOrDestruct(OID, ivars);
11448 if (ivars.empty())
11449 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011450 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011451 for (unsigned i = 0; i < ivars.size(); i++) {
11452 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011453 if (Field->isInvalidDecl())
11454 continue;
11455
Sean Huntcbb67482011-01-08 20:30:50 +000011456 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011457 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11458 InitializationKind InitKind =
11459 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11460
11461 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011462 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011463 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011464 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011465 // Note, MemberInit could actually come back empty if no initialization
11466 // is required (e.g., because it would call a trivial default constructor)
11467 if (!MemberInit.get() || MemberInit.isInvalid())
11468 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011469
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011470 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011471 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11472 SourceLocation(),
11473 MemberInit.takeAs<Expr>(),
11474 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011475 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011476
11477 // Be sure that the destructor is accessible and is marked as referenced.
11478 if (const RecordType *RecordTy
11479 = Context.getBaseElementType(Field->getType())
11480 ->getAs<RecordType>()) {
11481 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011482 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011483 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011484 CheckDestructorAccess(Field->getLocation(), Destructor,
11485 PDiag(diag::err_access_dtor_ivar)
11486 << Context.getBaseElementType(Field->getType()));
11487 }
11488 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011489 }
11490 ObjCImplementation->setIvarInitializers(Context,
11491 AllToInit.data(), AllToInit.size());
11492 }
11493}
Sean Huntfe57eef2011-05-04 05:57:24 +000011494
Sean Huntebcbe1d2011-05-04 23:29:54 +000011495static
11496void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11497 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11498 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11499 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11500 Sema &S) {
11501 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11502 CE = Current.end();
11503 if (Ctor->isInvalidDecl())
11504 return;
11505
Richard Smitha8eaf002012-08-23 06:16:52 +000011506 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11507
11508 // Target may not be determinable yet, for instance if this is a dependent
11509 // call in an uninstantiated template.
11510 if (Target) {
11511 const FunctionDecl *FNTarget = 0;
11512 (void)Target->hasBody(FNTarget);
11513 Target = const_cast<CXXConstructorDecl*>(
11514 cast_or_null<CXXConstructorDecl>(FNTarget));
11515 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011516
11517 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11518 // Avoid dereferencing a null pointer here.
11519 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11520
11521 if (!Current.insert(Canonical))
11522 return;
11523
11524 // We know that beyond here, we aren't chaining into a cycle.
11525 if (!Target || !Target->isDelegatingConstructor() ||
11526 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11527 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11528 Valid.insert(*CI);
11529 Current.clear();
11530 // We've hit a cycle.
11531 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11532 Current.count(TCanonical)) {
11533 // If we haven't diagnosed this cycle yet, do so now.
11534 if (!Invalid.count(TCanonical)) {
11535 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011536 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011537 << Ctor;
11538
Richard Smitha8eaf002012-08-23 06:16:52 +000011539 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011540 if (TCanonical != Canonical)
11541 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11542
11543 CXXConstructorDecl *C = Target;
11544 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011545 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011546 (void)C->getTargetConstructor()->hasBody(FNTarget);
11547 assert(FNTarget && "Ctor cycle through bodiless function");
11548
Richard Smitha8eaf002012-08-23 06:16:52 +000011549 C = const_cast<CXXConstructorDecl*>(
11550 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011551 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11552 }
11553 }
11554
11555 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11556 Invalid.insert(*CI);
11557 Current.clear();
11558 } else {
11559 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11560 }
11561}
11562
11563
Sean Huntfe57eef2011-05-04 05:57:24 +000011564void Sema::CheckDelegatingCtorCycles() {
11565 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11566
Sean Huntebcbe1d2011-05-04 23:29:54 +000011567 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11568 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011569
Douglas Gregor0129b562011-07-27 21:57:17 +000011570 for (DelegatingCtorDeclsType::iterator
11571 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011572 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011573 I != E; ++I)
11574 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011575
11576 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11577 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011578}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011579
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011580namespace {
11581 /// \brief AST visitor that finds references to the 'this' expression.
11582 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11583 Sema &S;
11584
11585 public:
11586 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11587
11588 bool VisitCXXThisExpr(CXXThisExpr *E) {
11589 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11590 << E->isImplicit();
11591 return false;
11592 }
11593 };
11594}
11595
11596bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11597 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11598 if (!TSInfo)
11599 return false;
11600
11601 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011602 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011603 if (!ProtoTL)
11604 return false;
11605
11606 // C++11 [expr.prim.general]p3:
11607 // [The expression this] shall not appear before the optional
11608 // cv-qualifier-seq and it shall not appear within the declaration of a
11609 // static member function (although its type and value category are defined
11610 // within a static member function as they are within a non-static member
11611 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011612 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000011613 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011614 FindCXXThisExpr Finder(*this);
11615
11616 // If the return type came after the cv-qualifier-seq, check it now.
11617 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000011618 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011619 return true;
11620
11621 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011622 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11623 return true;
11624
11625 return checkThisInStaticMemberFunctionAttributes(Method);
11626}
11627
11628bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11629 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11630 if (!TSInfo)
11631 return false;
11632
11633 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000011634 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011635 if (!ProtoTL)
11636 return false;
11637
David Blaikie39e6ab42013-02-18 22:06:02 +000011638 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011639 FindCXXThisExpr Finder(*this);
11640
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011641 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011642 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011643 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011644 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011645 case EST_DynamicNone:
11646 case EST_MSAny:
11647 case EST_None:
11648 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011649
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011650 case EST_ComputedNoexcept:
11651 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11652 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011653
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011654 case EST_Dynamic:
11655 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011656 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011657 E != EEnd; ++E) {
11658 if (!Finder.TraverseType(*E))
11659 return true;
11660 }
11661 break;
11662 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011663
11664 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011665}
11666
11667bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11668 FindCXXThisExpr Finder(*this);
11669
11670 // Check attributes.
11671 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11672 A != AEnd; ++A) {
11673 // FIXME: This should be emitted by tblgen.
11674 Expr *Arg = 0;
11675 ArrayRef<Expr *> Args;
11676 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11677 Arg = G->getArg();
11678 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11679 Arg = G->getArg();
11680 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11681 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11682 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11683 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11684 else if (ExclusiveLockFunctionAttr *ELF
11685 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11686 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11687 else if (SharedLockFunctionAttr *SLF
11688 = dyn_cast<SharedLockFunctionAttr>(*A))
11689 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11690 else if (ExclusiveTrylockFunctionAttr *ETLF
11691 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11692 Arg = ETLF->getSuccessValue();
11693 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11694 } else if (SharedTrylockFunctionAttr *STLF
11695 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11696 Arg = STLF->getSuccessValue();
11697 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11698 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11699 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11700 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11701 Arg = LR->getArg();
11702 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11703 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11704 else if (ExclusiveLocksRequiredAttr *ELR
11705 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11706 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11707 else if (SharedLocksRequiredAttr *SLR
11708 = dyn_cast<SharedLocksRequiredAttr>(*A))
11709 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11710
11711 if (Arg && !Finder.TraverseStmt(Arg))
11712 return true;
11713
11714 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11715 if (!Finder.TraverseStmt(Args[I]))
11716 return true;
11717 }
11718 }
11719
11720 return false;
11721}
11722
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011723void
11724Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11725 ArrayRef<ParsedType> DynamicExceptions,
11726 ArrayRef<SourceRange> DynamicExceptionRanges,
11727 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011728 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011729 FunctionProtoType::ExtProtoInfo &EPI) {
11730 Exceptions.clear();
11731 EPI.ExceptionSpecType = EST;
11732 if (EST == EST_Dynamic) {
11733 Exceptions.reserve(DynamicExceptions.size());
11734 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11735 // FIXME: Preserve type source info.
11736 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11737
11738 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11739 collectUnexpandedParameterPacks(ET, Unexpanded);
11740 if (!Unexpanded.empty()) {
11741 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11742 UPPC_ExceptionType,
11743 Unexpanded);
11744 continue;
11745 }
11746
11747 // Check that the type is valid for an exception spec, and
11748 // drop it if not.
11749 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11750 Exceptions.push_back(ET);
11751 }
11752 EPI.NumExceptions = Exceptions.size();
11753 EPI.Exceptions = Exceptions.data();
11754 return;
11755 }
11756
11757 if (EST == EST_ComputedNoexcept) {
11758 // If an error occurred, there's no expression here.
11759 if (NoexceptExpr) {
11760 assert((NoexceptExpr->isTypeDependent() ||
11761 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11762 Context.BoolTy) &&
11763 "Parser should have made sure that the expression is boolean");
11764 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11765 EPI.ExceptionSpecType = EST_BasicNoexcept;
11766 return;
11767 }
11768
11769 if (!NoexceptExpr->isValueDependent())
11770 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011771 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011772 /*AllowFold*/ false).take();
11773 EPI.NoexceptExpr = NoexceptExpr;
11774 }
11775 return;
11776 }
11777}
11778
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011779/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11780Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11781 // Implicitly declared functions (e.g. copy constructors) are
11782 // __host__ __device__
11783 if (D->isImplicit())
11784 return CFT_HostDevice;
11785
11786 if (D->hasAttr<CUDAGlobalAttr>())
11787 return CFT_Global;
11788
11789 if (D->hasAttr<CUDADeviceAttr>()) {
11790 if (D->hasAttr<CUDAHostAttr>())
11791 return CFT_HostDevice;
11792 else
11793 return CFT_Device;
11794 }
11795
11796 return CFT_Host;
11797}
11798
11799bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11800 CUDAFunctionTarget CalleeTarget) {
11801 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11802 // Callable from the device only."
11803 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11804 return true;
11805
11806 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11807 // Callable from the host only."
11808 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11809 // Callable from the host only."
11810 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11811 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11812 return true;
11813
11814 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11815 return true;
11816
11817 return false;
11818}