blob: 2fae8c9f91bb1811726f747446a5e4988adaa563 [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
John McCallb4eb64d2010-10-08 02:01:28 +0000255 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000256 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // Okay: add the default argument to the parameter
259 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000261 // We have already instantiated this parameter; provide each of the
262 // instantiations with the uninstantiated default argument.
263 UnparsedDefaultArgInstantiationsMap::iterator InstPos
264 = UnparsedDefaultArgInstantiations.find(Param);
265 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269 // We're done tracking this parameter's instantiations.
270 UnparsedDefaultArgInstantiations.erase(InstPos);
271 }
272
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000274}
275
Chris Lattner8123a952008-04-10 02:22:51 +0000276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000279void
John McCalld226f652010-08-21 09:40:31 +0000280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000281 Expr *DefaultArg) {
282 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000283 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
John McCalld226f652010-08-21 09:40:31 +0000285 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000286 UnparsedDefaultArgLocs.erase(Param);
287
Chris Lattner3d1cee32008-04-08 05:04:30 +0000288 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000289 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 Diag(EqualLoc, diag::err_param_default_argument)
291 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000292 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293 return;
294 }
295
Douglas Gregor6f526752010-12-16 08:48:57 +0000296 // Check for unexpanded parameter packs.
297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298 Param->setInvalidDecl();
299 return;
300 }
301
Anders Carlsson66e30672009-08-25 01:02:06 +0000302 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000305 Param->setInvalidDecl();
306 return;
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
John McCall9ae2f072010-08-23 23:25:46 +0000309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000310}
311
Douglas Gregor61366e92008-12-24 00:01:03 +0000312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000317 SourceLocation EqualLoc,
318 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000319 if (!param)
320 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000321
John McCalld226f652010-08-21 09:40:31 +0000322 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000323 if (Param)
324 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Anders Carlsson5e300d12009-06-12 16:51:40 +0000326 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000327}
328
Douglas Gregor72b505b2008-12-16 21:30:33 +0000329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000332 if (!param)
333 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000334
John McCalld226f652010-08-21 09:40:31 +0000335 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Anders Carlsson5e300d12009-06-12 16:51:40 +0000339 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000340}
341
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348 // C++ [dcl.fct.default]p3
349 // A default argument expression shall be specified only in the
350 // parameter-declaration-clause of a function declaration or in a
351 // template-parameter (14.1). It shall not be specified for a
352 // parameter pack. If it is specified in a
353 // parameter-declaration-clause, it shall not occur within a
354 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000356 DeclaratorChunk &chunk = D.getTypeObject(i);
357 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000361 if (Param->hasUnparsedDefaultArg()) {
362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365 delete Toks;
366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000367 } else if (Param->getDefaultArg()) {
368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369 << Param->getDefaultArg()->getSourceRange();
370 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000371 }
372 }
373 }
374 }
375}
376
Craig Topper1a6eac82012-09-21 04:33:26 +0000377/// MergeCXXFunctionDecl - Merge two declarations of the same C++
378/// function, once we already know that they have the same
379/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000383 bool Invalid = false;
384
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 // For non-template functions, default arguments can be added in
387 // later declarations of a function in the same
388 // scope. Declarations in different scopes have completely
389 // distinct sets of default arguments. That is, declarations in
390 // inner scopes do not acquire default arguments from
391 // declarations in outer scopes, and vice versa. In a given
392 // function declaration, all parameters subsequent to a
393 // parameter with a default argument shall have default
394 // arguments supplied in this or previous declarations. A
395 // default argument shall not be redefined by a later
396 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000397 //
398 // C++ [dcl.fct.default]p6:
399 // Except for member functions of class templates, the default arguments
400 // in a member function definition that appears outside of the class
401 // definition are added to the set of default arguments provided by the
402 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404 ParmVarDecl *OldParam = Old->getParamDecl(p);
405 ParmVarDecl *NewParam = New->getParamDecl(p);
406
James Molloy9cda03f2012-03-13 08:55:35 +0000407 bool OldParamHasDfl = OldParam->hasDefaultArg();
408 bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410 NamedDecl *ND = Old;
411 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412 // Ignore default parameters of old decl if they are not in
413 // the same scope.
414 OldParamHasDfl = false;
415
416 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000417
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 unsigned DiagDefaultParamID =
419 diag::err_param_default_argument_redefinition;
420
421 // MSVC accepts that default parameters be redefined for member functions
422 // of template class. The new default parameter's value is ignored.
423 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000424 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000427 // Merge the old default argument into the new parameter.
428 NewParam->setHasInheritedDefaultArg();
429 if (OldParam->hasUninstantiatedDefaultArg())
430 NewParam->setUninstantiatedDefaultArg(
431 OldParam->getUninstantiatedDefaultArg());
432 else
433 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000435 Invalid = false;
436 }
437 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000438
Francois Pichet8cf90492011-04-10 04:58:30 +0000439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440 // hint here. Alternatively, we could walk the type-source information
441 // for NewParam to find the last source location in the type... but it
442 // isn't worth the effort right now. This is the kind of test case that
443 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000444 // int f(int);
445 // void g(int (*fp)(int) = f);
446 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000447 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000448 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449
450 // Look for the function declaration where the default argument was
451 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000452 for (FunctionDecl *Older = Old->getPreviousDecl();
453 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000454 if (!Older->getParamDecl(p)->hasDefaultArg())
455 break;
456
457 OldParam = Older->getParamDecl(p);
458 }
459
460 Diag(OldParam->getLocation(), diag::note_previous_definition)
461 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000462 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000463 // Merge the old default argument into the new parameter.
464 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000465 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000466 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000467 if (OldParam->hasUninstantiatedDefaultArg())
468 NewParam->setUninstantiatedDefaultArg(
469 OldParam->getUninstantiatedDefaultArg());
470 else
John McCall3d6c1782010-05-04 01:53:42 +0000471 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000472 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000473 if (New->getDescribedFunctionTemplate()) {
474 // Paragraph 4, quoted above, only applies to non-template functions.
475 Diag(NewParam->getLocation(),
476 diag::err_param_default_argument_template_redecl)
477 << NewParam->getDefaultArgRange();
478 Diag(Old->getLocation(), diag::note_template_prev_declaration)
479 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000480 } else if (New->getTemplateSpecializationKind()
481 != TSK_ImplicitInstantiation &&
482 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483 // C++ [temp.expr.spec]p21:
484 // Default function arguments shall not be specified in a declaration
485 // or a definition for one of the following explicit specializations:
486 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000487 // - the explicit specialization of a member function template;
488 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000489 // template where the class template specialization to which the
490 // member function specialization belongs is implicitly
491 // instantiated.
492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494 << New->getDeclName()
495 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 } else if (New->getDeclContext()->isDependentContext()) {
497 // C++ [dcl.fct.default]p6 (DR217):
498 // Default arguments for a member function of a class template shall
499 // be specified on the initial declaration of the member function
500 // within the class template.
501 //
502 // Reading the tea leaves a bit in DR217 and its reference to DR205
503 // leads me to the conclusion that one cannot add default function
504 // arguments for an out-of-line definition of a member function of a
505 // dependent type.
506 int WhichKind = 2;
507 if (CXXRecordDecl *Record
508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509 if (Record->getDescribedClassTemplate())
510 WhichKind = 0;
511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512 WhichKind = 1;
513 else
514 WhichKind = 2;
515 }
516
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_member_template_redecl)
519 << WhichKind
520 << NewParam->getDefaultArgRange();
521 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000522 }
523 }
524
Richard Smithb8abff62012-11-28 03:45:24 +0000525 // DR1344: If a default argument is added outside a class definition and that
526 // default argument makes the function a special member function, the program
527 // is ill-formed. This can only happen for constructors.
528 if (isa<CXXConstructorDecl>(New) &&
529 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
530 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
531 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
532 if (NewSM != OldSM) {
533 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
534 assert(NewParam->hasDefaultArg());
535 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
536 << NewParam->getDefaultArgRange() << NewSM;
537 Diag(Old->getLocation(), diag::note_previous_declaration);
538 }
539 }
540
Richard Smithff234882012-02-20 23:28:05 +0000541 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000542 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000543 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000544 if (New->isConstexpr() != Old->isConstexpr()) {
545 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
546 << New << New->isConstexpr();
547 Diag(Old->getLocation(), diag::note_previous_declaration);
548 Invalid = true;
549 }
550
Douglas Gregore13ad832010-02-12 07:32:17 +0000551 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000552 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000553
Douglas Gregorcda9c672009-02-16 17:45:42 +0000554 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000555}
556
Sebastian Redl60618fa2011-03-12 11:50:43 +0000557/// \brief Merge the exception specifications of two variable declarations.
558///
559/// This is called when there's a redeclaration of a VarDecl. The function
560/// checks if the redeclaration might have an exception specification and
561/// validates compatibility and merges the specs if necessary.
562void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
563 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000564 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000565 return;
566
567 assert(Context.hasSameType(New->getType(), Old->getType()) &&
568 "Should only be called if types are otherwise the same.");
569
570 QualType NewType = New->getType();
571 QualType OldType = Old->getType();
572
573 // We're only interested in pointers and references to functions, as well
574 // as pointers to member functions.
575 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
576 NewType = R->getPointeeType();
577 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
578 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
579 NewType = P->getPointeeType();
580 OldType = OldType->getAs<PointerType>()->getPointeeType();
581 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
582 NewType = M->getPointeeType();
583 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
584 }
585
586 if (!NewType->isFunctionProtoType())
587 return;
588
589 // There's lots of special cases for functions. For function pointers, system
590 // libraries are hopefully not as broken so that we don't need these
591 // workarounds.
592 if (CheckEquivalentExceptionSpec(
593 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
594 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
595 New->setInvalidDecl();
596 }
597}
598
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599/// CheckCXXDefaultArguments - Verify that the default arguments for a
600/// function declaration are well-formed according to C++
601/// [dcl.fct.default].
602void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
603 unsigned NumParams = FD->getNumParams();
604 unsigned p;
605
Douglas Gregorc6889e72012-02-14 22:28:59 +0000606 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
607 isa<CXXMethodDecl>(FD) &&
608 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
609
Chris Lattner3d1cee32008-04-08 05:04:30 +0000610 // Find first parameter with a default argument
611 for (p = 0; p < NumParams; ++p) {
612 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000613 if (Param->hasDefaultArg()) {
614 // C++11 [expr.prim.lambda]p5:
615 // [...] Default arguments (8.3.6) shall not be specified in the
616 // parameter-declaration-clause of a lambda-declarator.
617 //
618 // FIXME: Core issue 974 strikes this sentence, we only provide an
619 // extension warning.
620 if (IsLambda)
621 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
622 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000623 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000624 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000625 }
626
627 // C++ [dcl.fct.default]p4:
628 // In a given function declaration, all parameters
629 // subsequent to a parameter with a default argument shall
630 // have default arguments supplied in this or previous
631 // declarations. A default argument shall not be redefined
632 // by a later declaration (not even to the same value).
633 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000634 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000636 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000637 if (Param->isInvalidDecl())
638 /* We already complained about this parameter. */;
639 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000640 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000641 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000642 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000643 else
Mike Stump1eb44332009-09-09 15:08:12 +0000644 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000645 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattner3d1cee32008-04-08 05:04:30 +0000647 LastMissingDefaultArg = p;
648 }
649 }
650
651 if (LastMissingDefaultArg > 0) {
652 // Some default arguments were missing. Clear out all of the
653 // default arguments up to (and including) the last missing
654 // default argument, so that we leave the function parameters
655 // in a semantically valid state.
656 for (p = 0; p <= LastMissingDefaultArg; ++p) {
657 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000658 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000659 Param->setDefaultArg(0);
660 }
661 }
662 }
663}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000664
Richard Smith9f569cc2011-10-01 02:31:28 +0000665// CheckConstexprParameterTypes - Check whether a function's parameter types
666// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000667// diagnostic and return false.
668static bool CheckConstexprParameterTypes(Sema &SemaRef,
669 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000670 unsigned ArgIndex = 0;
671 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
672 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
673 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
674 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
675 SourceLocation ParamLoc = PD->getLocation();
676 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000677 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000678 diag::err_constexpr_non_literal_param,
679 ArgIndex+1, PD->getSourceRange(),
680 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000681 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000682 }
Joao Matos17d35c32012-08-31 22:18:20 +0000683 return true;
684}
685
686/// \brief Get diagnostic %select index for tag kind for
687/// record diagnostic message.
688/// WARNING: Indexes apply to particular diagnostics only!
689///
690/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000691static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000692 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000693 case TTK_Struct: return 0;
694 case TTK_Interface: return 1;
695 case TTK_Class: return 2;
696 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000697 }
Joao Matos17d35c32012-08-31 22:18:20 +0000698}
699
700// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
701// the requirements of a constexpr function definition or a constexpr
702// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000703// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000704//
Richard Smith86c3ae42012-02-13 03:54:03 +0000705// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
706bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000707 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
708 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000709 // C++11 [dcl.constexpr]p4:
710 // The definition of a constexpr constructor shall satisfy the following
711 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000712 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000713 const CXXRecordDecl *RD = MD->getParent();
714 if (RD->getNumVBases()) {
715 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
716 << isa<CXXConstructorDecl>(NewFD)
717 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
718 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
719 E = RD->vbases_end(); I != E; ++I)
720 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000721 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000722 return false;
723 }
Richard Smith35340502012-01-13 04:54:00 +0000724 }
725
726 if (!isa<CXXConstructorDecl>(NewFD)) {
727 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000728 // The definition of a constexpr function shall satisfy the following
729 // constraints:
730 // - it shall not be virtual;
731 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
732 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000733 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000734
Richard Smith86c3ae42012-02-13 03:54:03 +0000735 // If it's not obvious why this function is virtual, find an overridden
736 // function which uses the 'virtual' keyword.
737 const CXXMethodDecl *WrittenVirtual = Method;
738 while (!WrittenVirtual->isVirtualAsWritten())
739 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
740 if (WrittenVirtual != Method)
741 Diag(WrittenVirtual->getLocation(),
742 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000743 return false;
744 }
745
746 // - its return type shall be a literal type;
747 QualType RT = NewFD->getResultType();
748 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000749 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000750 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000752 }
753
Richard Smith35340502012-01-13 04:54:00 +0000754 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000755 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000756 return false;
757
Richard Smith9f569cc2011-10-01 02:31:28 +0000758 return true;
759}
760
761/// Check the given declaration statement is legal within a constexpr function
762/// body. C++0x [dcl.constexpr]p3,p4.
763///
764/// \return true if the body is OK, false if we have diagnosed a problem.
765static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
766 DeclStmt *DS) {
767 // C++0x [dcl.constexpr]p3 and p4:
768 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
769 // contain only
770 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
771 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
772 switch ((*DclIt)->getKind()) {
773 case Decl::StaticAssert:
774 case Decl::Using:
775 case Decl::UsingShadow:
776 case Decl::UsingDirective:
777 case Decl::UnresolvedUsingTypename:
778 // - static_assert-declarations
779 // - using-declarations,
780 // - using-directives,
781 continue;
782
783 case Decl::Typedef:
784 case Decl::TypeAlias: {
785 // - typedef declarations and alias-declarations that do not define
786 // classes or enumerations,
787 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
788 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
789 // Don't allow variably-modified types in constexpr functions.
790 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
791 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
792 << TL.getSourceRange() << TL.getType()
793 << isa<CXXConstructorDecl>(Dcl);
794 return false;
795 }
796 continue;
797 }
798
799 case Decl::Enum:
800 case Decl::CXXRecord:
801 // As an extension, we allow the declaration (but not the definition) of
802 // classes and enumerations in all declarations, not just in typedef and
803 // alias declarations.
804 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
805 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
806 << isa<CXXConstructorDecl>(Dcl);
807 return false;
808 }
809 continue;
810
811 case Decl::Var:
812 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
813 << isa<CXXConstructorDecl>(Dcl);
814 return false;
815
816 default:
817 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
818 << isa<CXXConstructorDecl>(Dcl);
819 return false;
820 }
821 }
822
823 return true;
824}
825
826/// Check that the given field is initialized within a constexpr constructor.
827///
828/// \param Dcl The constexpr constructor being checked.
829/// \param Field The field being checked. This may be a member of an anonymous
830/// struct or union nested within the class being checked.
831/// \param Inits All declarations, including anonymous struct/union members and
832/// indirect members, for which any initialization was provided.
833/// \param Diagnosed Set to true if an error is produced.
834static void CheckConstexprCtorInitializer(Sema &SemaRef,
835 const FunctionDecl *Dcl,
836 FieldDecl *Field,
837 llvm::SmallSet<Decl*, 16> &Inits,
838 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000839 if (Field->isUnnamedBitfield())
840 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000841
842 if (Field->isAnonymousStructOrUnion() &&
843 Field->getType()->getAsCXXRecordDecl()->isEmpty())
844 return;
845
Richard Smith9f569cc2011-10-01 02:31:28 +0000846 if (!Inits.count(Field)) {
847 if (!Diagnosed) {
848 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
849 Diagnosed = true;
850 }
851 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
852 } else if (Field->isAnonymousStructOrUnion()) {
853 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
854 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
855 I != E; ++I)
856 // If an anonymous union contains an anonymous struct of which any member
857 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000858 if (!RD->isUnion() || Inits.count(*I))
859 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000860 }
861}
862
863/// Check the body for the given constexpr function declaration only contains
864/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
865///
866/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000867bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000868 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000869 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000870 // The definition of a constexpr function shall satisfy the following
871 // constraints: [...]
872 // - its function-body shall be = delete, = default, or a
873 // compound-statement
874 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000875 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000876 // In the definition of a constexpr constructor, [...]
877 // - its function-body shall not be a function-try-block;
878 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
879 << isa<CXXConstructorDecl>(Dcl);
880 return false;
881 }
882
883 // - its function-body shall be [...] a compound-statement that contains only
884 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
885
886 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
887 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
888 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
889 switch ((*BodyIt)->getStmtClass()) {
890 case Stmt::NullStmtClass:
891 // - null statements,
892 continue;
893
894 case Stmt::DeclStmtClass:
895 // - static_assert-declarations
896 // - using-declarations,
897 // - using-directives,
898 // - typedef declarations and alias-declarations that do not define
899 // classes or enumerations,
900 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
901 return false;
902 continue;
903
904 case Stmt::ReturnStmtClass:
905 // - and exactly one return statement;
906 if (isa<CXXConstructorDecl>(Dcl))
907 break;
908
909 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 continue;
911
912 default:
913 break;
914 }
915
916 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
917 << isa<CXXConstructorDecl>(Dcl);
918 return false;
919 }
920
921 if (const CXXConstructorDecl *Constructor
922 = dyn_cast<CXXConstructorDecl>(Dcl)) {
923 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000924 // DR1359:
925 // - every non-variant non-static data member and base class sub-object
926 // shall be initialized;
927 // - if the class is a non-empty union, or for each non-empty anonymous
928 // union member of a non-union class, exactly one non-static data member
929 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000930 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000931 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000932 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
933 return false;
934 }
Richard Smith6e433752011-10-10 16:38:04 +0000935 } else if (!Constructor->isDependentContext() &&
936 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000937 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
938
939 // Skip detailed checking if we have enough initializers, and we would
940 // allow at most one initializer per member.
941 bool AnyAnonStructUnionMembers = false;
942 unsigned Fields = 0;
943 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
944 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000945 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000946 AnyAnonStructUnionMembers = true;
947 break;
948 }
949 }
950 if (AnyAnonStructUnionMembers ||
951 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
952 // Check initialization of non-static data members. Base classes are
953 // always initialized so do not need to be checked. Dependent bases
954 // might not have initializers in the member initializer list.
955 llvm::SmallSet<Decl*, 16> Inits;
956 for (CXXConstructorDecl::init_const_iterator
957 I = Constructor->init_begin(), E = Constructor->init_end();
958 I != E; ++I) {
959 if (FieldDecl *FD = (*I)->getMember())
960 Inits.insert(FD);
961 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
962 Inits.insert(ID->chain_begin(), ID->chain_end());
963 }
964
965 bool Diagnosed = false;
966 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
967 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000968 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000969 if (Diagnosed)
970 return false;
971 }
972 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000973 } else {
974 if (ReturnStmts.empty()) {
975 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
976 return false;
977 }
978 if (ReturnStmts.size() > 1) {
979 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
980 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
981 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
982 return false;
983 }
984 }
985
Richard Smith5ba73e12012-02-04 00:33:54 +0000986 // C++11 [dcl.constexpr]p5:
987 // if no function argument values exist such that the function invocation
988 // substitution would produce a constant expression, the program is
989 // ill-formed; no diagnostic required.
990 // C++11 [dcl.constexpr]p3:
991 // - every constructor call and implicit conversion used in initializing the
992 // return value shall be one of those allowed in a constant expression.
993 // C++11 [dcl.constexpr]p4:
994 // - every constructor involved in initializing non-static data members and
995 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000996 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000997 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +0000998 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +0000999 << isa<CXXConstructorDecl>(Dcl);
1000 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1001 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001002 // Don't return false here: we allow this for compatibility in
1003 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001004 }
1005
Richard Smith9f569cc2011-10-01 02:31:28 +00001006 return true;
1007}
1008
Douglas Gregorb48fe382008-10-31 09:07:45 +00001009/// isCurrentClassName - Determine whether the identifier II is the
1010/// name of the class type currently being defined. In the case of
1011/// nested classes, this will only return true if II is the name of
1012/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001013bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1014 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001015 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001016
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001017 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001018 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001019 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001020 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1021 } else
1022 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1023
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001024 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001025 return &II == CurDecl->getIdentifier();
1026 else
1027 return false;
1028}
1029
Douglas Gregor229d47a2012-11-10 07:24:09 +00001030/// \brief Determine whether the given class is a base class of the given
1031/// class, including looking at dependent bases.
1032static bool findCircularInheritance(const CXXRecordDecl *Class,
1033 const CXXRecordDecl *Current) {
1034 SmallVector<const CXXRecordDecl*, 8> Queue;
1035
1036 Class = Class->getCanonicalDecl();
1037 while (true) {
1038 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1039 E = Current->bases_end();
1040 I != E; ++I) {
1041 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1042 if (!Base)
1043 continue;
1044
1045 Base = Base->getDefinition();
1046 if (!Base)
1047 continue;
1048
1049 if (Base->getCanonicalDecl() == Class)
1050 return true;
1051
1052 Queue.push_back(Base);
1053 }
1054
1055 if (Queue.empty())
1056 return false;
1057
1058 Current = Queue.back();
1059 Queue.pop_back();
1060 }
1061
1062 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001063}
1064
Mike Stump1eb44332009-09-09 15:08:12 +00001065/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001066///
1067/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1068/// and returns NULL otherwise.
1069CXXBaseSpecifier *
1070Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1071 SourceRange SpecifierRange,
1072 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001073 TypeSourceInfo *TInfo,
1074 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001075 QualType BaseType = TInfo->getType();
1076
Douglas Gregor2943aed2009-03-03 04:44:36 +00001077 // C++ [class.union]p1:
1078 // A union shall not have base classes.
1079 if (Class->isUnion()) {
1080 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1081 << SpecifierRange;
1082 return 0;
1083 }
1084
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001085 if (EllipsisLoc.isValid() &&
1086 !TInfo->getType()->containsUnexpandedParameterPack()) {
1087 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1088 << TInfo->getTypeLoc().getSourceRange();
1089 EllipsisLoc = SourceLocation();
1090 }
Douglas Gregord777e282012-11-10 01:18:17 +00001091
1092 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1093
1094 if (BaseType->isDependentType()) {
1095 // Make sure that we don't have circular inheritance among our dependent
1096 // bases. For non-dependent bases, the check for completeness below handles
1097 // this.
1098 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1099 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1100 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001101 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001102 Diag(BaseLoc, diag::err_circular_inheritance)
1103 << BaseType << Context.getTypeDeclType(Class);
1104
1105 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1106 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1107 << BaseType;
1108
1109 return 0;
1110 }
1111 }
1112
Mike Stump1eb44332009-09-09 15:08:12 +00001113 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001114 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001115 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001116 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001117
1118 // Base specifiers must be record types.
1119 if (!BaseType->isRecordType()) {
1120 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1121 return 0;
1122 }
1123
1124 // C++ [class.union]p1:
1125 // A union shall not be used as a base class.
1126 if (BaseType->isUnionType()) {
1127 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1128 return 0;
1129 }
1130
1131 // C++ [class.derived]p2:
1132 // The class-name in a base-specifier shall not be an incompletely
1133 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001134 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001135 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001136 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001137 return 0;
John McCall572fc622010-08-17 07:23:57 +00001138 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139
Eli Friedman1d954f62009-08-15 21:55:26 +00001140 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001141 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001143 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001144 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001145 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1146 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001147
Anders Carlsson1d209272011-03-25 14:55:14 +00001148 // C++ [class]p3:
1149 // If a class is marked final and it appears as a base-type-specifier in
1150 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001151 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001152 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1153 << CXXBaseDecl->getDeclName();
1154 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1155 << CXXBaseDecl->getDeclName();
1156 return 0;
1157 }
1158
John McCall572fc622010-08-17 07:23:57 +00001159 if (BaseDecl->isInvalidDecl())
1160 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001161
1162 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001163 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001164 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001165 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001166}
1167
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001168/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1169/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001170/// example:
1171/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001172/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001173BaseResult
John McCalld226f652010-08-21 09:40:31 +00001174Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001175 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001176 ParsedType basetype, SourceLocation BaseLoc,
1177 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001178 if (!classdecl)
1179 return true;
1180
Douglas Gregor40808ce2009-03-09 23:48:35 +00001181 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001182 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001183 if (!Class)
1184 return true;
1185
Nick Lewycky56062202010-07-26 16:56:01 +00001186 TypeSourceInfo *TInfo = 0;
1187 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001188
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001189 if (EllipsisLoc.isInvalid() &&
1190 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001191 UPPC_BaseType))
1192 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001193
Douglas Gregor2943aed2009-03-03 04:44:36 +00001194 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001195 Virtual, Access, TInfo,
1196 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001197 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001198 else
1199 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Douglas Gregor2943aed2009-03-03 04:44:36 +00001201 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001202}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001203
Douglas Gregor2943aed2009-03-03 04:44:36 +00001204/// \brief Performs the actual work of attaching the given base class
1205/// specifiers to a C++ class.
1206bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1207 unsigned NumBases) {
1208 if (NumBases == 0)
1209 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001210
1211 // Used to keep track of which base types we have already seen, so
1212 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001213 // that the key is always the unqualified canonical type of the base
1214 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001215 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1216
1217 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001218 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001219 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001220 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001221 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001222 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001223 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001224
1225 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1226 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001227 // C++ [class.mi]p3:
1228 // A class shall not be specified as a direct base class of a
1229 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001230 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001231 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001232 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001233 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001234
1235 // Delete the duplicate base class specifier; we're going to
1236 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001237 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001238
1239 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001240 } else {
1241 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001242 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001243 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001244 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1245 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1246 if (Class->isInterface() &&
1247 (!RD->isInterface() ||
1248 KnownBase->getAccessSpecifier() != AS_public)) {
1249 // The Microsoft extension __interface does not permit bases that
1250 // are not themselves public interfaces.
1251 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1252 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1253 << RD->getSourceRange();
1254 Invalid = true;
1255 }
1256 if (RD->hasAttr<WeakAttr>())
1257 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1258 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001259 }
1260 }
1261
1262 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001263 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001264
1265 // Delete the remaining (good) base class specifiers, since their
1266 // data has been copied into the CXXRecordDecl.
1267 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001268 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001269
1270 return Invalid;
1271}
1272
1273/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1274/// class, after checking whether there are any duplicate base
1275/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001276void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001277 unsigned NumBases) {
1278 if (!ClassDecl || !Bases || !NumBases)
1279 return;
1280
1281 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001282 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001283 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001284}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001285
John McCall3cb0ebd2010-03-10 03:28:59 +00001286static CXXRecordDecl *GetClassForType(QualType T) {
1287 if (const RecordType *RT = T->getAs<RecordType>())
1288 return cast<CXXRecordDecl>(RT->getDecl());
1289 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1290 return ICT->getDecl();
1291 else
1292 return 0;
1293}
1294
Douglas Gregora8f32e02009-10-06 17:59:45 +00001295/// \brief Determine whether the type \p Derived is a C++ class that is
1296/// derived from the type \p Base.
1297bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001298 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001299 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001300
1301 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1302 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001303 return false;
1304
John McCall3cb0ebd2010-03-10 03:28:59 +00001305 CXXRecordDecl *BaseRD = GetClassForType(Base);
1306 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001307 return false;
1308
John McCall86ff3082010-02-04 22:26:26 +00001309 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1310 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001311}
1312
1313/// \brief Determine whether the type \p Derived is a C++ class that is
1314/// derived from the type \p Base.
1315bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001316 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001317 return false;
1318
John McCall3cb0ebd2010-03-10 03:28:59 +00001319 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1320 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001321 return false;
1322
John McCall3cb0ebd2010-03-10 03:28:59 +00001323 CXXRecordDecl *BaseRD = GetClassForType(Base);
1324 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001325 return false;
1326
Douglas Gregora8f32e02009-10-06 17:59:45 +00001327 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1328}
1329
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001330void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001331 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001332 assert(BasePathArray.empty() && "Base path array must be empty!");
1333 assert(Paths.isRecordingPaths() && "Must record paths!");
1334
1335 const CXXBasePath &Path = Paths.front();
1336
1337 // We first go backward and check if we have a virtual base.
1338 // FIXME: It would be better if CXXBasePath had the base specifier for
1339 // the nearest virtual base.
1340 unsigned Start = 0;
1341 for (unsigned I = Path.size(); I != 0; --I) {
1342 if (Path[I - 1].Base->isVirtual()) {
1343 Start = I - 1;
1344 break;
1345 }
1346 }
1347
1348 // Now add all bases.
1349 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001350 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001351}
1352
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001353/// \brief Determine whether the given base path includes a virtual
1354/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001355bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1356 for (CXXCastPath::const_iterator B = BasePath.begin(),
1357 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001358 B != BEnd; ++B)
1359 if ((*B)->isVirtual())
1360 return true;
1361
1362 return false;
1363}
1364
Douglas Gregora8f32e02009-10-06 17:59:45 +00001365/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1366/// conversion (where Derived and Base are class types) is
1367/// well-formed, meaning that the conversion is unambiguous (and
1368/// that all of the base classes are accessible). Returns true
1369/// and emits a diagnostic if the code is ill-formed, returns false
1370/// otherwise. Loc is the location where this routine should point to
1371/// if there is an error, and Range is the source range to highlight
1372/// if there is an error.
1373bool
1374Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001375 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001376 unsigned AmbigiousBaseConvID,
1377 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001378 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001379 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001380 // First, determine whether the path from Derived to Base is
1381 // ambiguous. This is slightly more expensive than checking whether
1382 // the Derived to Base conversion exists, because here we need to
1383 // explore multiple paths to determine if there is an ambiguity.
1384 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1385 /*DetectVirtual=*/false);
1386 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1387 assert(DerivationOkay &&
1388 "Can only be used with a derived-to-base conversion");
1389 (void)DerivationOkay;
1390
1391 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001392 if (InaccessibleBaseID) {
1393 // Check that the base class can be accessed.
1394 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1395 InaccessibleBaseID)) {
1396 case AR_inaccessible:
1397 return true;
1398 case AR_accessible:
1399 case AR_dependent:
1400 case AR_delayed:
1401 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001402 }
John McCall6b2accb2010-02-10 09:31:12 +00001403 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001404
1405 // Build a base path if necessary.
1406 if (BasePath)
1407 BuildBasePathArray(Paths, *BasePath);
1408 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001409 }
1410
1411 // We know that the derived-to-base conversion is ambiguous, and
1412 // we're going to produce a diagnostic. Perform the derived-to-base
1413 // search just one more time to compute all of the possible paths so
1414 // that we can print them out. This is more expensive than any of
1415 // the previous derived-to-base checks we've done, but at this point
1416 // performance isn't as much of an issue.
1417 Paths.clear();
1418 Paths.setRecordingPaths(true);
1419 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1420 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1421 (void)StillOkay;
1422
1423 // Build up a textual representation of the ambiguous paths, e.g.,
1424 // D -> B -> A, that will be used to illustrate the ambiguous
1425 // conversions in the diagnostic. We only print one of the paths
1426 // to each base class subobject.
1427 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1428
1429 Diag(Loc, AmbigiousBaseConvID)
1430 << Derived << Base << PathDisplayStr << Range << Name;
1431 return true;
1432}
1433
1434bool
1435Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001436 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001437 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001438 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001439 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001440 IgnoreAccess ? 0
1441 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001442 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001443 Loc, Range, DeclarationName(),
1444 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001445}
1446
1447
1448/// @brief Builds a string representing ambiguous paths from a
1449/// specific derived class to different subobjects of the same base
1450/// class.
1451///
1452/// This function builds a string that can be used in error messages
1453/// to show the different paths that one can take through the
1454/// inheritance hierarchy to go from the derived class to different
1455/// subobjects of a base class. The result looks something like this:
1456/// @code
1457/// struct D -> struct B -> struct A
1458/// struct D -> struct C -> struct A
1459/// @endcode
1460std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1461 std::string PathDisplayStr;
1462 std::set<unsigned> DisplayedPaths;
1463 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1464 Path != Paths.end(); ++Path) {
1465 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1466 // We haven't displayed a path to this particular base
1467 // class subobject yet.
1468 PathDisplayStr += "\n ";
1469 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1470 for (CXXBasePath::const_iterator Element = Path->begin();
1471 Element != Path->end(); ++Element)
1472 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1473 }
1474 }
1475
1476 return PathDisplayStr;
1477}
1478
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001479//===----------------------------------------------------------------------===//
1480// C++ class member Handling
1481//===----------------------------------------------------------------------===//
1482
Abramo Bagnara6206d532010-06-05 05:09:32 +00001483/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001484bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1485 SourceLocation ASLoc,
1486 SourceLocation ColonLoc,
1487 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001488 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001489 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001490 ASLoc, ColonLoc);
1491 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001492 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001493}
1494
Richard Smitha4b39652012-08-06 03:25:17 +00001495/// CheckOverrideControl - Check C++11 override control semantics.
1496void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001497 if (D->isInvalidDecl())
1498 return;
1499
Chris Lattner5f9e2722011-07-23 10:55:15 +00001500 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001501
Richard Smitha4b39652012-08-06 03:25:17 +00001502 // Do we know which functions this declaration might be overriding?
1503 bool OverridesAreKnown = !MD ||
1504 (!MD->getParent()->hasAnyDependentBases() &&
1505 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001506
Richard Smitha4b39652012-08-06 03:25:17 +00001507 if (!MD || !MD->isVirtual()) {
1508 if (OverridesAreKnown) {
1509 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1510 Diag(OA->getLocation(),
1511 diag::override_keyword_only_allowed_on_virtual_member_functions)
1512 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1513 D->dropAttr<OverrideAttr>();
1514 }
1515 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1516 Diag(FA->getLocation(),
1517 diag::override_keyword_only_allowed_on_virtual_member_functions)
1518 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1519 D->dropAttr<FinalAttr>();
1520 }
1521 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001522 return;
1523 }
Richard Smitha4b39652012-08-06 03:25:17 +00001524
1525 if (!OverridesAreKnown)
1526 return;
1527
1528 // C++11 [class.virtual]p5:
1529 // If a virtual function is marked with the virt-specifier override and
1530 // does not override a member function of a base class, the program is
1531 // ill-formed.
1532 bool HasOverriddenMethods =
1533 MD->begin_overridden_methods() != MD->end_overridden_methods();
1534 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1535 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1536 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001537}
1538
Richard Smitha4b39652012-08-06 03:25:17 +00001539/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001540/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001541/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001542bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1543 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001544 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001545 return false;
1546
1547 Diag(New->getLocation(), diag::err_final_function_overridden)
1548 << New->getDeclName();
1549 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1550 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001551}
1552
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001553static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001554 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1555 // FIXME: Destruction of ObjC lifetime types has side-effects.
1556 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1557 return !RD->isCompleteDefinition() ||
1558 !RD->hasTrivialDefaultConstructor() ||
1559 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001560 return false;
1561}
1562
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001563/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1564/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001565/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001566/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1567/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001568Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001569Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001570 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001571 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001572 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001573 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001574 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1575 DeclarationName Name = NameInfo.getName();
1576 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001577
1578 // For anonymous bitfields, the location should point to the type.
1579 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001580 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001581
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001582 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001583
John McCall4bde1e12010-06-04 08:34:12 +00001584 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001585 assert(!DS.isFriendSpecified());
1586
Richard Smith1ab0d902011-06-25 02:28:38 +00001587 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001588
John McCalle402e722012-09-25 07:32:39 +00001589 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1590 // The Microsoft extension __interface only permits public member functions
1591 // and prohibits constructors, destructors, operators, non-public member
1592 // functions, static methods and data members.
1593 unsigned InvalidDecl;
1594 bool ShowDeclName = true;
1595 if (!isFunc)
1596 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1597 else if (AS != AS_public)
1598 InvalidDecl = 2;
1599 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1600 InvalidDecl = 3;
1601 else switch (Name.getNameKind()) {
1602 case DeclarationName::CXXConstructorName:
1603 InvalidDecl = 4;
1604 ShowDeclName = false;
1605 break;
1606
1607 case DeclarationName::CXXDestructorName:
1608 InvalidDecl = 5;
1609 ShowDeclName = false;
1610 break;
1611
1612 case DeclarationName::CXXOperatorName:
1613 case DeclarationName::CXXConversionFunctionName:
1614 InvalidDecl = 6;
1615 break;
1616
1617 default:
1618 InvalidDecl = 0;
1619 break;
1620 }
1621
1622 if (InvalidDecl) {
1623 if (ShowDeclName)
1624 Diag(Loc, diag::err_invalid_member_in_interface)
1625 << (InvalidDecl-1) << Name;
1626 else
1627 Diag(Loc, diag::err_invalid_member_in_interface)
1628 << (InvalidDecl-1) << "";
1629 return 0;
1630 }
1631 }
1632
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001633 // C++ 9.2p6: A member shall not be declared to have automatic storage
1634 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001635 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1636 // data members and cannot be applied to names declared const or static,
1637 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001638 switch (DS.getStorageClassSpec()) {
1639 case DeclSpec::SCS_unspecified:
1640 case DeclSpec::SCS_typedef:
1641 case DeclSpec::SCS_static:
1642 // FALL THROUGH.
1643 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001644 case DeclSpec::SCS_mutable:
1645 if (isFunc) {
1646 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001647 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001648 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001649 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Sebastian Redla11f42f2008-11-17 23:24:37 +00001651 // FIXME: It would be nicer if the keyword was ignored only for this
1652 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001653 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001654 }
1655 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001656 default:
1657 if (DS.getStorageClassSpecLoc().isValid())
1658 Diag(DS.getStorageClassSpecLoc(),
1659 diag::err_storageclass_invalid_for_member);
1660 else
1661 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1662 D.getMutableDeclSpec().ClearStorageClassSpecs();
1663 }
1664
Sebastian Redl669d5d72008-11-14 23:42:31 +00001665 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1666 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001667 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001668
1669 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001670 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001671 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001672
1673 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001674 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001675 Diag(Loc, diag::err_bad_variable_name)
1676 << Name;
1677 return 0;
1678 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001679
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001680 IdentifierInfo *II = Name.getAsIdentifierInfo();
1681
Douglas Gregorf2503652011-09-21 14:40:46 +00001682 // Member field could not be with "template" keyword.
1683 // So TemplateParameterLists should be empty in this case.
1684 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001685 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001686 if (TemplateParams->size()) {
1687 // There is no such thing as a member field template.
1688 Diag(D.getIdentifierLoc(), diag::err_template_member)
1689 << II
1690 << SourceRange(TemplateParams->getTemplateLoc(),
1691 TemplateParams->getRAngleLoc());
1692 } else {
1693 // There is an extraneous 'template<>' for this member.
1694 Diag(TemplateParams->getTemplateLoc(),
1695 diag::err_template_member_noparams)
1696 << II
1697 << SourceRange(TemplateParams->getTemplateLoc(),
1698 TemplateParams->getRAngleLoc());
1699 }
1700 return 0;
1701 }
1702
Douglas Gregor922fff22010-10-13 22:19:53 +00001703 if (SS.isSet() && !SS.isInvalid()) {
1704 // The user provided a superfluous scope specifier inside a class
1705 // definition:
1706 //
1707 // class X {
1708 // int X::member;
1709 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001710 if (DeclContext *DC = computeDeclContext(SS, false))
1711 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001712 else
1713 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1714 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001715
Douglas Gregor922fff22010-10-13 22:19:53 +00001716 SS.clear();
1717 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001718
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001719 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001720 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001721 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001722 } else {
Richard Smithca523302012-06-10 03:12:00 +00001723 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001724
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001725 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001726 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001727 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001728 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001729
1730 // Non-instance-fields can't have a bitfield.
1731 if (BitWidth) {
1732 if (Member->isInvalidDecl()) {
1733 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001734 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001735 // C++ 9.6p3: A bit-field shall not be a static member.
1736 // "static member 'A' cannot be a bit-field"
1737 Diag(Loc, diag::err_static_not_bitfield)
1738 << Name << BitWidth->getSourceRange();
1739 } else if (isa<TypedefDecl>(Member)) {
1740 // "typedef member 'x' cannot be a bit-field"
1741 Diag(Loc, diag::err_typedef_not_bitfield)
1742 << Name << BitWidth->getSourceRange();
1743 } else {
1744 // A function typedef ("typedef int f(); f a;").
1745 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1746 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001747 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001748 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001749 }
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Chris Lattner8b963ef2009-03-05 23:01:03 +00001751 BitWidth = 0;
1752 Member->setInvalidDecl();
1753 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001754
1755 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Douglas Gregor37b372b2009-08-20 22:52:58 +00001757 // If we have declared a member function template, set the access of the
1758 // templated declaration as well.
1759 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1760 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001761 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001762
Richard Smitha4b39652012-08-06 03:25:17 +00001763 if (VS.isOverrideSpecified())
1764 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1765 if (VS.isFinalSpecified())
1766 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001767
Douglas Gregorf5251602011-03-08 17:10:18 +00001768 if (VS.getLastLocation().isValid()) {
1769 // Update the end location of a method that has a virt-specifiers.
1770 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1771 MD->setRangeEnd(VS.getLastLocation());
1772 }
Richard Smitha4b39652012-08-06 03:25:17 +00001773
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001774 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001775
Douglas Gregor10bd3682008-11-17 22:58:34 +00001776 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001777
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001778 if (isInstField) {
1779 FieldDecl *FD = cast<FieldDecl>(Member);
1780 FieldCollector->Add(FD);
1781
1782 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1783 FD->getLocation())
1784 != DiagnosticsEngine::Ignored) {
1785 // Remember all explicit private FieldDecls that have a name, no side
1786 // effects and are not part of a dependent type declaration.
1787 if (!FD->isImplicit() && FD->getDeclName() &&
1788 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001789 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001790 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001791 !InitializationHasSideEffects(*FD))
1792 UnusedPrivateFields.insert(FD);
1793 }
1794 }
1795
John McCalld226f652010-08-21 09:40:31 +00001796 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001797}
1798
Hans Wennborg471f9852012-09-18 15:58:06 +00001799namespace {
1800 class UninitializedFieldVisitor
1801 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1802 Sema &S;
1803 ValueDecl *VD;
1804 public:
1805 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1806 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001807 S(S) {
1808 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1809 this->VD = IFD->getAnonField();
1810 else
1811 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001812 }
1813
1814 void HandleExpr(Expr *E) {
1815 if (!E) return;
1816
1817 // Expressions like x(x) sometimes lack the surrounding expressions
1818 // but need to be checked anyways.
1819 HandleValue(E);
1820 Visit(E);
1821 }
1822
1823 void HandleValue(Expr *E) {
1824 E = E->IgnoreParens();
1825
1826 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1827 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001828 return;
1829
1830 // FieldME is the inner-most MemberExpr that is not an anonymous struct
1831 // or union.
1832 MemberExpr *FieldME = ME;
1833
Hans Wennborg471f9852012-09-18 15:58:06 +00001834 Expr *Base = E;
1835 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001836 ME = cast<MemberExpr>(Base);
1837
1838 if (isa<VarDecl>(ME->getMemberDecl()))
1839 return;
1840
1841 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1842 if (!FD->isAnonymousStructOrUnion())
1843 FieldME = ME;
1844
Hans Wennborg471f9852012-09-18 15:58:06 +00001845 Base = ME->getBase();
1846 }
1847
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001848 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00001849 unsigned diag = VD->getType()->isReferenceType()
1850 ? diag::warn_reference_field_is_uninit
1851 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001852 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00001853 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00001854 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00001855 }
1856
1857 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1858 HandleValue(CO->getTrueExpr());
1859 HandleValue(CO->getFalseExpr());
1860 return;
1861 }
1862
1863 if (BinaryConditionalOperator *BCO =
1864 dyn_cast<BinaryConditionalOperator>(E)) {
1865 HandleValue(BCO->getCommon());
1866 HandleValue(BCO->getFalseExpr());
1867 return;
1868 }
1869
1870 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1871 switch (BO->getOpcode()) {
1872 default:
1873 return;
1874 case(BO_PtrMemD):
1875 case(BO_PtrMemI):
1876 HandleValue(BO->getLHS());
1877 return;
1878 case(BO_Comma):
1879 HandleValue(BO->getRHS());
1880 return;
1881 }
1882 }
1883 }
1884
1885 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1886 if (E->getCastKind() == CK_LValueToRValue)
1887 HandleValue(E->getSubExpr());
1888
1889 Inherited::VisitImplicitCastExpr(E);
1890 }
1891
1892 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1893 Expr *Callee = E->getCallee();
1894 if (isa<MemberExpr>(Callee))
1895 HandleValue(Callee);
1896
1897 Inherited::VisitCXXMemberCallExpr(E);
1898 }
1899 };
1900 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1901 ValueDecl *VD) {
1902 UninitializedFieldVisitor(S, VD).HandleExpr(E);
1903 }
1904} // namespace
1905
Richard Smith7a614d82011-06-11 17:19:42 +00001906/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001907/// in-class initializer for a non-static C++ class member, and after
1908/// instantiating an in-class initializer in a class template. Such actions
1909/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001910void
Richard Smithca523302012-06-10 03:12:00 +00001911Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001912 Expr *InitExpr) {
1913 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001914 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1915 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001916
1917 if (!InitExpr) {
1918 FD->setInvalidDecl();
1919 FD->removeInClassInitializer();
1920 return;
1921 }
1922
Peter Collingbournefef21892011-10-23 18:59:44 +00001923 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1924 FD->setInvalidDecl();
1925 FD->removeInClassInitializer();
1926 return;
1927 }
1928
Hans Wennborg471f9852012-09-18 15:58:06 +00001929 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1930 != DiagnosticsEngine::Ignored) {
1931 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1932 }
1933
Richard Smith7a614d82011-06-11 17:19:42 +00001934 ExprResult Init = InitExpr;
Douglas Gregordd084272012-09-14 04:20:37 +00001935 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() &&
1936 !FD->getDeclContext()->isDependentContext()) {
1937 // Note: We don't type-check when we're in a dependent context, because
1938 // the initialization-substitution code does not properly handle direct
1939 // list initialization. We have the same hackaround for ctor-initializers.
Sebastian Redl772291a2012-02-19 16:31:05 +00001940 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001941 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001942 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1943 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001944 Expr **Inits = &InitExpr;
1945 unsigned NumInits = 1;
1946 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001947 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001948 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001949 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001950 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1951 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001952 if (Init.isInvalid()) {
1953 FD->setInvalidDecl();
1954 return;
1955 }
1956
Richard Smithca523302012-06-10 03:12:00 +00001957 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001958 }
1959
1960 // C++0x [class.base.init]p7:
1961 // The initialization of each base and member constitutes a
1962 // full-expression.
1963 Init = MaybeCreateExprWithCleanups(Init);
1964 if (Init.isInvalid()) {
1965 FD->setInvalidDecl();
1966 return;
1967 }
1968
1969 InitExpr = Init.release();
1970
1971 FD->setInClassInitializer(InitExpr);
1972}
1973
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001974/// \brief Find the direct and/or virtual base specifiers that
1975/// correspond to the given base type, for use in base initialization
1976/// within a constructor.
1977static bool FindBaseInitializer(Sema &SemaRef,
1978 CXXRecordDecl *ClassDecl,
1979 QualType BaseType,
1980 const CXXBaseSpecifier *&DirectBaseSpec,
1981 const CXXBaseSpecifier *&VirtualBaseSpec) {
1982 // First, check for a direct base class.
1983 DirectBaseSpec = 0;
1984 for (CXXRecordDecl::base_class_const_iterator Base
1985 = ClassDecl->bases_begin();
1986 Base != ClassDecl->bases_end(); ++Base) {
1987 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1988 // We found a direct base of this type. That's what we're
1989 // initializing.
1990 DirectBaseSpec = &*Base;
1991 break;
1992 }
1993 }
1994
1995 // Check for a virtual base class.
1996 // FIXME: We might be able to short-circuit this if we know in advance that
1997 // there are no virtual bases.
1998 VirtualBaseSpec = 0;
1999 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2000 // We haven't found a base yet; search the class hierarchy for a
2001 // virtual base class.
2002 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2003 /*DetectVirtual=*/false);
2004 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2005 BaseType, Paths)) {
2006 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2007 Path != Paths.end(); ++Path) {
2008 if (Path->back().Base->isVirtual()) {
2009 VirtualBaseSpec = Path->back().Base;
2010 break;
2011 }
2012 }
2013 }
2014 }
2015
2016 return DirectBaseSpec || VirtualBaseSpec;
2017}
2018
Sebastian Redl6df65482011-09-24 17:48:25 +00002019/// \brief Handle a C++ member initializer using braced-init-list syntax.
2020MemInitResult
2021Sema::ActOnMemInitializer(Decl *ConstructorD,
2022 Scope *S,
2023 CXXScopeSpec &SS,
2024 IdentifierInfo *MemberOrBase,
2025 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002026 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002027 SourceLocation IdLoc,
2028 Expr *InitList,
2029 SourceLocation EllipsisLoc) {
2030 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002031 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002032 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002033}
2034
2035/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002036MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002037Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002038 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002039 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002040 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002041 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002042 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002043 SourceLocation IdLoc,
2044 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002045 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002046 SourceLocation RParenLoc,
2047 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002048 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2049 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002050 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002051 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002052 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002053}
2054
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002055namespace {
2056
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002057// Callback to only accept typo corrections that can be a valid C++ member
2058// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002059class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2060 public:
2061 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2062 : ClassDecl(ClassDecl) {}
2063
2064 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2065 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2066 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2067 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2068 else
2069 return isa<TypeDecl>(ND);
2070 }
2071 return false;
2072 }
2073
2074 private:
2075 CXXRecordDecl *ClassDecl;
2076};
2077
2078}
2079
Sebastian Redl6df65482011-09-24 17:48:25 +00002080/// \brief Handle a C++ member initializer.
2081MemInitResult
2082Sema::BuildMemInitializer(Decl *ConstructorD,
2083 Scope *S,
2084 CXXScopeSpec &SS,
2085 IdentifierInfo *MemberOrBase,
2086 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002087 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002088 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002089 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002090 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002091 if (!ConstructorD)
2092 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002094 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002095
2096 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002097 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002098 if (!Constructor) {
2099 // The user wrote a constructor initializer on a function that is
2100 // not a C++ constructor. Ignore the error for now, because we may
2101 // have more member initializers coming; we'll diagnose it just
2102 // once in ActOnMemInitializers.
2103 return true;
2104 }
2105
2106 CXXRecordDecl *ClassDecl = Constructor->getParent();
2107
2108 // C++ [class.base.init]p2:
2109 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002110 // constructor's class and, if not found in that scope, are looked
2111 // up in the scope containing the constructor's definition.
2112 // [Note: if the constructor's class contains a member with the
2113 // same name as a direct or virtual base class of the class, a
2114 // mem-initializer-id naming the member or base class and composed
2115 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002116 // mem-initializer-id for the hidden base class may be specified
2117 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002118 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002119 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002120 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002121 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00002122 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002123 ValueDecl *Member;
2124 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
2125 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002126 if (EllipsisLoc.isValid())
2127 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002128 << MemberOrBase
2129 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002130
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002131 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002132 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002133 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002134 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002135 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002136 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002137 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002138
2139 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002140 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002141 } else if (DS.getTypeSpecType() == TST_decltype) {
2142 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002143 } else {
2144 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2145 LookupParsedName(R, S, &SS);
2146
2147 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2148 if (!TyD) {
2149 if (R.isAmbiguous()) return true;
2150
John McCallfd225442010-04-09 19:01:14 +00002151 // We don't want access-control diagnostics here.
2152 R.suppressDiagnostics();
2153
Douglas Gregor7a886e12010-01-19 06:46:48 +00002154 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2155 bool NotUnknownSpecialization = false;
2156 DeclContext *DC = computeDeclContext(SS, false);
2157 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2158 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2159
2160 if (!NotUnknownSpecialization) {
2161 // When the scope specifier can refer to a member of an unknown
2162 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002163 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2164 SS.getWithLocInContext(Context),
2165 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002166 if (BaseType.isNull())
2167 return true;
2168
Douglas Gregor7a886e12010-01-19 06:46:48 +00002169 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002170 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002171 }
2172 }
2173
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002174 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002175 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002176 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002177 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002178 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002179 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002180 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2181 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002182 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002183 // We have found a non-static data member with a similar
2184 // name to what was typed; complain and initialize that
2185 // member.
2186 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2187 << MemberOrBase << true << CorrectedQuotedStr
2188 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2189 Diag(Member->getLocation(), diag::note_previous_decl)
2190 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002191
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002192 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002193 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002194 const CXXBaseSpecifier *DirectBaseSpec;
2195 const CXXBaseSpecifier *VirtualBaseSpec;
2196 if (FindBaseInitializer(*this, ClassDecl,
2197 Context.getTypeDeclType(Type),
2198 DirectBaseSpec, VirtualBaseSpec)) {
2199 // We have found a direct or virtual base class with a
2200 // similar name to what was typed; complain and initialize
2201 // that base class.
2202 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002203 << MemberOrBase << false << CorrectedQuotedStr
2204 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002205
2206 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2207 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002208 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002209 diag::note_base_class_specified_here)
2210 << BaseSpec->getType()
2211 << BaseSpec->getSourceRange();
2212
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002213 TyD = Type;
2214 }
2215 }
2216 }
2217
Douglas Gregor7a886e12010-01-19 06:46:48 +00002218 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002219 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002220 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002221 return true;
2222 }
John McCall2b194412009-12-21 10:41:20 +00002223 }
2224
Douglas Gregor7a886e12010-01-19 06:46:48 +00002225 if (BaseType.isNull()) {
2226 BaseType = Context.getTypeDeclType(TyD);
2227 if (SS.isSet()) {
2228 NestedNameSpecifier *Qualifier =
2229 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002230
Douglas Gregor7a886e12010-01-19 06:46:48 +00002231 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002232 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002233 }
John McCall2b194412009-12-21 10:41:20 +00002234 }
2235 }
Mike Stump1eb44332009-09-09 15:08:12 +00002236
John McCalla93c9342009-12-07 02:54:59 +00002237 if (!TInfo)
2238 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002239
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002240 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002241}
2242
Chandler Carruth81c64772011-09-03 01:14:15 +00002243/// Checks a member initializer expression for cases where reference (or
2244/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002245static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2246 Expr *Init,
2247 SourceLocation IdLoc) {
2248 QualType MemberTy = Member->getType();
2249
2250 // We only handle pointers and references currently.
2251 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2252 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2253 return;
2254
2255 const bool IsPointer = MemberTy->isPointerType();
2256 if (IsPointer) {
2257 if (const UnaryOperator *Op
2258 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2259 // The only case we're worried about with pointers requires taking the
2260 // address.
2261 if (Op->getOpcode() != UO_AddrOf)
2262 return;
2263
2264 Init = Op->getSubExpr();
2265 } else {
2266 // We only handle address-of expression initializers for pointers.
2267 return;
2268 }
2269 }
2270
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002271 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2272 // Taking the address of a temporary will be diagnosed as a hard error.
2273 if (IsPointer)
2274 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002275
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002276 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2277 << Member << Init->getSourceRange();
2278 } else if (const DeclRefExpr *DRE
2279 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2280 // We only warn when referring to a non-reference parameter declaration.
2281 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2282 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002283 return;
2284
2285 S.Diag(Init->getExprLoc(),
2286 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2287 : diag::warn_bind_ref_member_to_parameter)
2288 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002289 } else {
2290 // Other initializers are fine.
2291 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002292 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002293
2294 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2295 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002296}
2297
John McCallf312b1e2010-08-26 23:41:50 +00002298MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002299Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002300 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002301 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2302 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2303 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002304 "Member must be a FieldDecl or IndirectFieldDecl");
2305
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002306 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002307 return true;
2308
Douglas Gregor464b2f02010-11-05 22:21:31 +00002309 if (Member->isInvalidDecl())
2310 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002311
John McCallb4190042009-11-04 23:02:40 +00002312 // Diagnose value-uses of fields to initialize themselves, e.g.
2313 // foo(foo)
2314 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002315 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002316 Expr **Args;
2317 unsigned NumArgs;
2318 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2319 Args = ParenList->getExprs();
2320 NumArgs = ParenList->getNumExprs();
2321 } else {
2322 InitListExpr *InitList = cast<InitListExpr>(Init);
2323 Args = InitList->getInits();
2324 NumArgs = InitList->getNumInits();
2325 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002326
Richard Trieude5e75c2012-06-14 23:11:34 +00002327 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2328 != DiagnosticsEngine::Ignored)
2329 for (unsigned i = 0; i < NumArgs; ++i)
2330 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002331 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002332 // initializing the i'th field, throw a warning if any of the >= i'th
2333 // fields are used, as they are not yet initialized.
2334 // Right now we are only handling the case where the i'th field uses
2335 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002336 // Also need to take into account that some fields may be initialized by
2337 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002338 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002339
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002340 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002341
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002342 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002343 // Can't check initialization for a member of dependent type or when
2344 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002345 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002346 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002347 bool InitList = false;
2348 if (isa<InitListExpr>(Init)) {
2349 InitList = true;
2350 Args = &Init;
2351 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002352
2353 if (isStdInitializerList(Member->getType(), 0)) {
2354 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2355 << /*at end of ctor*/1 << InitRange;
2356 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002357 }
2358
Chandler Carruth894aed92010-12-06 09:23:57 +00002359 // Initialize the member.
2360 InitializedEntity MemberEntity =
2361 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2362 : InitializedEntity::InitializeMember(IndirectMember, 0);
2363 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002364 InitList ? InitializationKind::CreateDirectList(IdLoc)
2365 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2366 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002367
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002368 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2369 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002370 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002371 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002372 if (MemberInit.isInvalid())
2373 return true;
2374
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002375 CheckImplicitConversions(MemberInit.get(),
2376 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002377
2378 // C++0x [class.base.init]p7:
2379 // The initialization of each base and member constitutes a
2380 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002381 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002382 if (MemberInit.isInvalid())
2383 return true;
2384
2385 // If we are in a dependent context, template instantiation will
2386 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002387 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002388 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2389 // of the information that we have about the member
2390 // initializer. However, deconstructing the ASTs is a dicey process,
2391 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002392 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002393 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002394 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002395 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002396 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2397 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002398 }
2399
Chandler Carruth894aed92010-12-06 09:23:57 +00002400 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002401 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2402 InitRange.getBegin(), Init,
2403 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002404 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002405 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2406 InitRange.getBegin(), Init,
2407 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002408 }
Eli Friedman59c04372009-07-29 19:44:27 +00002409}
2410
John McCallf312b1e2010-08-26 23:41:50 +00002411MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002412Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002413 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002414 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002415 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002416 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002417 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002418 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002419
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002420 bool InitList = true;
2421 Expr **Args = &Init;
2422 unsigned NumArgs = 1;
2423 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2424 InitList = false;
2425 Args = ParenList->getExprs();
2426 NumArgs = ParenList->getNumExprs();
2427 }
2428
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002429 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002430 // Initialize the object.
2431 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2432 QualType(ClassDecl->getTypeForDecl(), 0));
2433 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002434 InitList ? InitializationKind::CreateDirectList(NameLoc)
2435 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2436 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002437 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2438 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002439 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002440 0);
Sean Hunt41717662011-02-26 19:13:13 +00002441 if (DelegationInit.isInvalid())
2442 return true;
2443
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002444 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2445 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002446
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002447 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002448
2449 // C++0x [class.base.init]p7:
2450 // The initialization of each base and member constitutes a
2451 // full-expression.
2452 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2453 if (DelegationInit.isInvalid())
2454 return true;
2455
Eli Friedmand21016f2012-05-19 23:35:23 +00002456 // If we are in a dependent context, template instantiation will
2457 // perform this type-checking again. Just save the arguments that we
2458 // received in a ParenListExpr.
2459 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2460 // of the information that we have about the base
2461 // initializer. However, deconstructing the ASTs is a dicey process,
2462 // and this approach is far more likely to get the corner cases right.
2463 if (CurContext->isDependentContext())
2464 DelegationInit = Owned(Init);
2465
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002466 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002467 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002468 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002469}
2470
2471MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002472Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002473 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002474 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002475 SourceLocation BaseLoc
2476 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002477
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002478 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2479 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2480 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2481
2482 // C++ [class.base.init]p2:
2483 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002484 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002485 // of that class, the mem-initializer is ill-formed. A
2486 // mem-initializer-list can initialize a base class using any
2487 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002488 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002489
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002490 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002491 if (EllipsisLoc.isValid()) {
2492 // This is a pack expansion.
2493 if (!BaseType->containsUnexpandedParameterPack()) {
2494 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002495 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002496
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002497 EllipsisLoc = SourceLocation();
2498 }
2499 } else {
2500 // Check for any unexpanded parameter packs.
2501 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2502 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002503
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002504 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002505 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002506 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002507
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002508 // Check for direct and virtual base classes.
2509 const CXXBaseSpecifier *DirectBaseSpec = 0;
2510 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2511 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002512 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2513 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002514 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002515
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002516 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2517 VirtualBaseSpec);
2518
2519 // C++ [base.class.init]p2:
2520 // Unless the mem-initializer-id names a nonstatic data member of the
2521 // constructor's class or a direct or virtual base of that class, the
2522 // mem-initializer is ill-formed.
2523 if (!DirectBaseSpec && !VirtualBaseSpec) {
2524 // If the class has any dependent bases, then it's possible that
2525 // one of those types will resolve to the same type as
2526 // BaseType. Therefore, just treat this as a dependent base
2527 // class initialization. FIXME: Should we try to check the
2528 // initialization anyway? It seems odd.
2529 if (ClassDecl->hasAnyDependentBases())
2530 Dependent = true;
2531 else
2532 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2533 << BaseType << Context.getTypeDeclType(ClassDecl)
2534 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2535 }
2536 }
2537
2538 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002539 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Sebastian Redl6df65482011-09-24 17:48:25 +00002541 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2542 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002543 InitRange.getBegin(), Init,
2544 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002545 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002546
2547 // C++ [base.class.init]p2:
2548 // If a mem-initializer-id is ambiguous because it designates both
2549 // a direct non-virtual base class and an inherited virtual base
2550 // class, the mem-initializer is ill-formed.
2551 if (DirectBaseSpec && VirtualBaseSpec)
2552 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002553 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002554
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002555 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002556 if (!BaseSpec)
2557 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2558
2559 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002560 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002561 Expr **Args = &Init;
2562 unsigned NumArgs = 1;
2563 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002564 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002565 Args = ParenList->getExprs();
2566 NumArgs = ParenList->getNumExprs();
2567 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002568
2569 InitializedEntity BaseEntity =
2570 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2571 InitializationKind Kind =
2572 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2573 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2574 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002575 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2576 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002577 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002578 if (BaseInit.isInvalid())
2579 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002580
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002581 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002582
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002583 // C++0x [class.base.init]p7:
2584 // The initialization of each base and member constitutes a
2585 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002586 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002587 if (BaseInit.isInvalid())
2588 return true;
2589
2590 // If we are in a dependent context, template instantiation will
2591 // perform this type-checking again. Just save the arguments that we
2592 // received in a ParenListExpr.
2593 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2594 // of the information that we have about the base
2595 // initializer. However, deconstructing the ASTs is a dicey process,
2596 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002597 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002598 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002599
Sean Huntcbb67482011-01-08 20:30:50 +00002600 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002601 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002602 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002603 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002604 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002605}
2606
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002607// Create a static_cast\<T&&>(expr).
2608static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2609 QualType ExprType = E->getType();
2610 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2611 SourceLocation ExprLoc = E->getLocStart();
2612 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2613 TargetType, ExprLoc);
2614
2615 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2616 SourceRange(ExprLoc, ExprLoc),
2617 E->getSourceRange()).take();
2618}
2619
Anders Carlssone5ef7402010-04-23 03:10:23 +00002620/// ImplicitInitializerKind - How an implicit base or member initializer should
2621/// initialize its base or member.
2622enum ImplicitInitializerKind {
2623 IIK_Default,
2624 IIK_Copy,
2625 IIK_Move
2626};
2627
Anders Carlssondefefd22010-04-23 02:00:02 +00002628static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002629BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002630 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002631 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002632 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002633 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002634 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002635 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2636 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002637
John McCall60d7b3a2010-08-24 06:29:42 +00002638 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002639
2640 switch (ImplicitInitKind) {
2641 case IIK_Default: {
2642 InitializationKind InitKind
2643 = InitializationKind::CreateDefault(Constructor->getLocation());
2644 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002645 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002646 break;
2647 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002648
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002649 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002650 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002651 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002652 ParmVarDecl *Param = Constructor->getParamDecl(0);
2653 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002654
Anders Carlssone5ef7402010-04-23 03:10:23 +00002655 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002656 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002657 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002658 Constructor->getLocation(), ParamType,
2659 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002660
Eli Friedman5f2987c2012-02-02 03:46:19 +00002661 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2662
Anders Carlssonc7957502010-04-24 22:02:54 +00002663 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002664 QualType ArgTy =
2665 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2666 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002667
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002668 if (Moving) {
2669 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2670 }
2671
John McCallf871d0c2010-08-07 06:22:56 +00002672 CXXCastPath BasePath;
2673 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002674 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2675 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002676 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002677 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002678
Anders Carlssone5ef7402010-04-23 03:10:23 +00002679 InitializationKind InitKind
2680 = InitializationKind::CreateDirect(Constructor->getLocation(),
2681 SourceLocation(), SourceLocation());
2682 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2683 &CopyCtorArg, 1);
2684 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002685 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002686 break;
2687 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002688 }
John McCall9ae2f072010-08-23 23:25:46 +00002689
Douglas Gregor53c374f2010-12-07 00:41:46 +00002690 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002691 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002692 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002693
Anders Carlssondefefd22010-04-23 02:00:02 +00002694 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002695 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002696 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2697 SourceLocation()),
2698 BaseSpec->isVirtual(),
2699 SourceLocation(),
2700 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002701 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002702 SourceLocation());
2703
Anders Carlssondefefd22010-04-23 02:00:02 +00002704 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002705}
2706
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002707static bool RefersToRValueRef(Expr *MemRef) {
2708 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2709 return Referenced->getType()->isRValueReferenceType();
2710}
2711
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002712static bool
2713BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002714 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002715 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002716 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002717 if (Field->isInvalidDecl())
2718 return true;
2719
Chandler Carruthf186b542010-06-29 23:50:44 +00002720 SourceLocation Loc = Constructor->getLocation();
2721
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002722 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2723 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002724 ParmVarDecl *Param = Constructor->getParamDecl(0);
2725 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002726
2727 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002728 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2729 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002730
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002731 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002732 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002733 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002734 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002735
Eli Friedman5f2987c2012-02-02 03:46:19 +00002736 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2737
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002738 if (Moving) {
2739 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2740 }
2741
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002742 // Build a reference to this field within the parameter.
2743 CXXScopeSpec SS;
2744 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2745 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002746 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2747 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002748 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002749 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002750 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002751 ParamType, Loc,
2752 /*IsArrow=*/false,
2753 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002754 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002755 /*FirstQualifierInScope=*/0,
2756 MemberLookup,
2757 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002758 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002759 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002760
2761 // C++11 [class.copy]p15:
2762 // - if a member m has rvalue reference type T&&, it is direct-initialized
2763 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002764 if (RefersToRValueRef(CtorArg.get())) {
2765 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002766 }
2767
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002768 // When the field we are copying is an array, create index variables for
2769 // each dimension of the array. We use these index variables to subscript
2770 // the source array, and other clients (e.g., CodeGen) will perform the
2771 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002772 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002773 QualType BaseType = Field->getType();
2774 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002775 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002776 while (const ConstantArrayType *Array
2777 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002778 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002779 // Create the iteration variable for this array index.
2780 IdentifierInfo *IterationVarName = 0;
2781 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002782 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002783 llvm::raw_svector_ostream OS(Str);
2784 OS << "__i" << IndexVariables.size();
2785 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2786 }
2787 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002788 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002789 IterationVarName, SizeType,
2790 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002791 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002792 IndexVariables.push_back(IterationVar);
2793
2794 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002795 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002796 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002797 assert(!IterationVarRef.isInvalid() &&
2798 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002799 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2800 assert(!IterationVarRef.isInvalid() &&
2801 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002802
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002803 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002804 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002805 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002806 Loc);
2807 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002808 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002809
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002810 BaseType = Array->getElementType();
2811 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002812
2813 // The array subscript expression is an lvalue, which is wrong for moving.
2814 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002815 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002816
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002817 // Construct the entity that we will be initializing. For an array, this
2818 // will be first element in the array, which may require several levels
2819 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002820 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002821 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002822 if (Indirect)
2823 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2824 else
2825 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002826 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2827 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2828 0,
2829 Entities.back()));
2830
2831 // Direct-initialize to use the copy constructor.
2832 InitializationKind InitKind =
2833 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2834
Sebastian Redl74e611a2011-09-04 18:14:28 +00002835 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002836 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002837 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002838
John McCall60d7b3a2010-08-24 06:29:42 +00002839 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002840 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002841 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002842 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002843 if (MemberInit.isInvalid())
2844 return true;
2845
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002846 if (Indirect) {
2847 assert(IndexVariables.size() == 0 &&
2848 "Indirect field improperly initialized");
2849 CXXMemberInit
2850 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2851 Loc, Loc,
2852 MemberInit.takeAs<Expr>(),
2853 Loc);
2854 } else
2855 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2856 Loc, MemberInit.takeAs<Expr>(),
2857 Loc,
2858 IndexVariables.data(),
2859 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002860 return false;
2861 }
2862
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002863 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2864
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002865 QualType FieldBaseElementType =
2866 SemaRef.Context.getBaseElementType(Field->getType());
2867
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002868 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002869 InitializedEntity InitEntity
2870 = Indirect? InitializedEntity::InitializeMember(Indirect)
2871 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002872 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002873 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002874
2875 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002876 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002877 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002878
Douglas Gregor53c374f2010-12-07 00:41:46 +00002879 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002880 if (MemberInit.isInvalid())
2881 return true;
2882
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002883 if (Indirect)
2884 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2885 Indirect, Loc,
2886 Loc,
2887 MemberInit.get(),
2888 Loc);
2889 else
2890 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2891 Field, Loc, Loc,
2892 MemberInit.get(),
2893 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002894 return false;
2895 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002896
Sean Hunt1f2f3842011-05-17 00:19:05 +00002897 if (!Field->getParent()->isUnion()) {
2898 if (FieldBaseElementType->isReferenceType()) {
2899 SemaRef.Diag(Constructor->getLocation(),
2900 diag::err_uninitialized_member_in_ctor)
2901 << (int)Constructor->isImplicit()
2902 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2903 << 0 << Field->getDeclName();
2904 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2905 return true;
2906 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002907
Sean Hunt1f2f3842011-05-17 00:19:05 +00002908 if (FieldBaseElementType.isConstQualified()) {
2909 SemaRef.Diag(Constructor->getLocation(),
2910 diag::err_uninitialized_member_in_ctor)
2911 << (int)Constructor->isImplicit()
2912 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2913 << 1 << Field->getDeclName();
2914 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2915 return true;
2916 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002917 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002918
David Blaikie4e4d0842012-03-11 07:00:24 +00002919 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002920 FieldBaseElementType->isObjCRetainableType() &&
2921 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2922 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002923 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002924 // Default-initialize Objective-C pointers to NULL.
2925 CXXMemberInit
2926 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2927 Loc, Loc,
2928 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2929 Loc);
2930 return false;
2931 }
2932
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002933 // Nothing to initialize.
2934 CXXMemberInit = 0;
2935 return false;
2936}
John McCallf1860e52010-05-20 23:23:51 +00002937
2938namespace {
2939struct BaseAndFieldInfo {
2940 Sema &S;
2941 CXXConstructorDecl *Ctor;
2942 bool AnyErrorsInInits;
2943 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002944 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002945 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002946
2947 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2948 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002949 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2950 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002951 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002952 else if (Generated && Ctor->isMoveConstructor())
2953 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002954 else
2955 IIK = IIK_Default;
2956 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002957
2958 bool isImplicitCopyOrMove() const {
2959 switch (IIK) {
2960 case IIK_Copy:
2961 case IIK_Move:
2962 return true;
2963
2964 case IIK_Default:
2965 return false;
2966 }
David Blaikie30263482012-01-20 21:50:17 +00002967
2968 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002969 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002970
2971 bool addFieldInitializer(CXXCtorInitializer *Init) {
2972 AllToInit.push_back(Init);
2973
2974 // Check whether this initializer makes the field "used".
2975 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2976 S.UnusedPrivateFields.remove(Init->getAnyMember());
2977
2978 return false;
2979 }
John McCallf1860e52010-05-20 23:23:51 +00002980};
2981}
2982
Richard Smitha4950662011-09-19 13:34:43 +00002983/// \brief Determine whether the given indirect field declaration is somewhere
2984/// within an anonymous union.
2985static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2986 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2987 CEnd = F->chain_end();
2988 C != CEnd; ++C)
2989 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2990 if (Record->isUnion())
2991 return true;
2992
2993 return false;
2994}
2995
Douglas Gregorddb21472011-11-02 23:04:16 +00002996/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2997/// array type.
2998static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2999 if (T->isIncompleteArrayType())
3000 return true;
3001
3002 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3003 if (!ArrayT->getSize())
3004 return true;
3005
3006 T = ArrayT->getElementType();
3007 }
3008
3009 return false;
3010}
3011
Richard Smith7a614d82011-06-11 17:19:42 +00003012static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003013 FieldDecl *Field,
3014 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00003015
Chandler Carruthe861c602010-06-30 02:59:29 +00003016 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003017 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3018 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003019
Richard Smith0b8220a2012-08-07 21:30:42 +00003020 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003021 // has a brace-or-equal-initializer, the entity is initialized as specified
3022 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003023 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003024 CXXCtorInitializer *Init;
3025 if (Indirect)
3026 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3027 SourceLocation(),
3028 SourceLocation(), 0,
3029 SourceLocation());
3030 else
3031 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3032 SourceLocation(),
3033 SourceLocation(), 0,
3034 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003035 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003036 }
3037
Richard Smithc115f632011-09-18 11:14:50 +00003038 // Don't build an implicit initializer for union members if none was
3039 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003040 if (Field->getParent()->isUnion() ||
3041 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003042 return false;
3043
Douglas Gregorddb21472011-11-02 23:04:16 +00003044 // Don't initialize incomplete or zero-length arrays.
3045 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3046 return false;
3047
John McCallf1860e52010-05-20 23:23:51 +00003048 // Don't try to build an implicit initializer if there were semantic
3049 // errors in any of the initializers (and therefore we might be
3050 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00003051 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00003052 return false;
3053
Sean Huntcbb67482011-01-08 20:30:50 +00003054 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003055 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3056 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003057 return true;
John McCallf1860e52010-05-20 23:23:51 +00003058
Richard Smith0b8220a2012-08-07 21:30:42 +00003059 if (!Init)
3060 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003061
Richard Smith0b8220a2012-08-07 21:30:42 +00003062 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003063}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003064
3065bool
3066Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3067 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003068 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003069 Constructor->setNumCtorInitializers(1);
3070 CXXCtorInitializer **initializer =
3071 new (Context) CXXCtorInitializer*[1];
3072 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3073 Constructor->setCtorInitializers(initializer);
3074
Sean Huntb76af9c2011-05-03 23:05:34 +00003075 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003076 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003077 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3078 }
3079
Sean Huntc1598702011-05-05 00:05:47 +00003080 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003081
Sean Hunt059ce0d2011-05-01 07:04:31 +00003082 return false;
3083}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003084
John McCallb77115d2011-06-17 00:18:42 +00003085bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
3086 CXXCtorInitializer **Initializers,
3087 unsigned NumInitializers,
3088 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003089 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003090 // Just store the initializers as written, they will be checked during
3091 // instantiation.
3092 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003093 Constructor->setNumCtorInitializers(NumInitializers);
3094 CXXCtorInitializer **baseOrMemberInitializers =
3095 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003096 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00003097 NumInitializers * sizeof(CXXCtorInitializer*));
3098 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003099 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003100
3101 // Let template instantiation know whether we had errors.
3102 if (AnyErrors)
3103 Constructor->setInvalidDecl();
3104
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003105 return false;
3106 }
3107
John McCallf1860e52010-05-20 23:23:51 +00003108 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003109
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003110 // We need to build the initializer AST according to order of construction
3111 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003112 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003113 if (!ClassDecl)
3114 return true;
3115
Eli Friedman80c30da2009-11-09 19:20:36 +00003116 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003117
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003118 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003119 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003120
3121 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003122 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003123 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003124 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003125 }
3126
Anders Carlsson711f34a2010-04-21 19:52:01 +00003127 // Keep track of the direct virtual bases.
3128 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3129 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3130 E = ClassDecl->bases_end(); I != E; ++I) {
3131 if (I->isVirtual())
3132 DirectVBases.insert(I);
3133 }
3134
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003135 // Push virtual bases before others.
3136 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3137 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3138
Sean Huntcbb67482011-01-08 20:30:50 +00003139 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003140 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3141 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003142 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003143 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003144 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003145 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003146 VBase, IsInheritedVirtualBase,
3147 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003148 HadError = true;
3149 continue;
3150 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003151
John McCallf1860e52010-05-20 23:23:51 +00003152 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003153 }
3154 }
Mike Stump1eb44332009-09-09 15:08:12 +00003155
John McCallf1860e52010-05-20 23:23:51 +00003156 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003157 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3158 E = ClassDecl->bases_end(); Base != E; ++Base) {
3159 // Virtuals are in the virtual base list and already constructed.
3160 if (Base->isVirtual())
3161 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003162
Sean Huntcbb67482011-01-08 20:30:50 +00003163 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003164 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3165 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003166 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003167 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003168 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003169 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003170 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003171 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003172 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003173 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003174
John McCallf1860e52010-05-20 23:23:51 +00003175 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003176 }
3177 }
Mike Stump1eb44332009-09-09 15:08:12 +00003178
John McCallf1860e52010-05-20 23:23:51 +00003179 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003180 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3181 MemEnd = ClassDecl->decls_end();
3182 Mem != MemEnd; ++Mem) {
3183 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003184 // C++ [class.bit]p2:
3185 // A declaration for a bit-field that omits the identifier declares an
3186 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3187 // initialized.
3188 if (F->isUnnamedBitfield())
3189 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003190
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003191 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003192 // handle anonymous struct/union fields based on their individual
3193 // indirect fields.
3194 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3195 continue;
3196
3197 if (CollectFieldInitializer(*this, Info, F))
3198 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003199 continue;
3200 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003201
3202 // Beyond this point, we only consider default initialization.
3203 if (Info.IIK != IIK_Default)
3204 continue;
3205
3206 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3207 if (F->getType()->isIncompleteArrayType()) {
3208 assert(ClassDecl->hasFlexibleArrayMember() &&
3209 "Incomplete array type is not valid");
3210 continue;
3211 }
3212
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003213 // Initialize each field of an anonymous struct individually.
3214 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3215 HadError = true;
3216
3217 continue;
3218 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003219 }
Mike Stump1eb44332009-09-09 15:08:12 +00003220
John McCallf1860e52010-05-20 23:23:51 +00003221 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003222 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003223 Constructor->setNumCtorInitializers(NumInitializers);
3224 CXXCtorInitializer **baseOrMemberInitializers =
3225 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003226 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003227 NumInitializers * sizeof(CXXCtorInitializer*));
3228 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003229
John McCallef027fe2010-03-16 21:39:52 +00003230 // Constructors implicitly reference the base and member
3231 // destructors.
3232 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3233 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003234 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003235
3236 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003237}
3238
Eli Friedman6347f422009-07-21 19:28:10 +00003239static void *GetKeyForTopLevelField(FieldDecl *Field) {
3240 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003241 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003242 if (RT->getDecl()->isAnonymousStructOrUnion())
3243 return static_cast<void *>(RT->getDecl());
3244 }
3245 return static_cast<void *>(Field);
3246}
3247
Anders Carlssonea356fb2010-04-02 05:42:15 +00003248static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003249 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003250}
3251
Anders Carlssonea356fb2010-04-02 05:42:15 +00003252static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003253 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003254 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003255 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003256
Eli Friedman6347f422009-07-21 19:28:10 +00003257 // For fields injected into the class via declaration of an anonymous union,
3258 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003259 FieldDecl *Field = Member->getAnyMember();
3260
John McCall3c3ccdb2010-04-10 09:28:51 +00003261 // If the field is a member of an anonymous struct or union, our key
3262 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003263 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003264 if (RD->isAnonymousStructOrUnion()) {
3265 while (true) {
3266 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3267 if (Parent->isAnonymousStructOrUnion())
3268 RD = Parent;
3269 else
3270 break;
3271 }
3272
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003273 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003274 }
Mike Stump1eb44332009-09-09 15:08:12 +00003275
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003276 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003277}
3278
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003279static void
3280DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003281 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003282 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003283 unsigned NumInits) {
3284 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003285 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003286
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003287 // Don't check initializers order unless the warning is enabled at the
3288 // location of at least one initializer.
3289 bool ShouldCheckOrder = false;
3290 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003291 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003292 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3293 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003294 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003295 ShouldCheckOrder = true;
3296 break;
3297 }
3298 }
3299 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003300 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003301
John McCalld6ca8da2010-04-10 07:37:23 +00003302 // Build the list of bases and members in the order that they'll
3303 // actually be initialized. The explicit initializers should be in
3304 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003305 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003306
Anders Carlsson071d6102010-04-02 03:38:04 +00003307 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3308
John McCalld6ca8da2010-04-10 07:37:23 +00003309 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003310 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003311 ClassDecl->vbases_begin(),
3312 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003313 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003314
John McCalld6ca8da2010-04-10 07:37:23 +00003315 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003316 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003317 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003318 if (Base->isVirtual())
3319 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003320 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003321 }
Mike Stump1eb44332009-09-09 15:08:12 +00003322
John McCalld6ca8da2010-04-10 07:37:23 +00003323 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003324 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003325 E = ClassDecl->field_end(); Field != E; ++Field) {
3326 if (Field->isUnnamedBitfield())
3327 continue;
3328
David Blaikie581deb32012-06-06 20:45:41 +00003329 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003330 }
3331
John McCalld6ca8da2010-04-10 07:37:23 +00003332 unsigned NumIdealInits = IdealInitKeys.size();
3333 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003334
Sean Huntcbb67482011-01-08 20:30:50 +00003335 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003336 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003337 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003338 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003339
3340 // Scan forward to try to find this initializer in the idealized
3341 // initializers list.
3342 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3343 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003344 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003345
3346 // If we didn't find this initializer, it must be because we
3347 // scanned past it on a previous iteration. That can only
3348 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003349 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003350 Sema::SemaDiagnosticBuilder D =
3351 SemaRef.Diag(PrevInit->getSourceLocation(),
3352 diag::warn_initializer_out_of_order);
3353
Francois Pichet00eb3f92010-12-04 09:14:42 +00003354 if (PrevInit->isAnyMemberInitializer())
3355 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003356 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003357 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003358
Francois Pichet00eb3f92010-12-04 09:14:42 +00003359 if (Init->isAnyMemberInitializer())
3360 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003361 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003362 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003363
3364 // Move back to the initializer's location in the ideal list.
3365 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3366 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003367 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003368
3369 assert(IdealIndex != NumIdealInits &&
3370 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003371 }
John McCalld6ca8da2010-04-10 07:37:23 +00003372
3373 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003374 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003375}
3376
John McCall3c3ccdb2010-04-10 09:28:51 +00003377namespace {
3378bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003379 CXXCtorInitializer *Init,
3380 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003381 if (!PrevInit) {
3382 PrevInit = Init;
3383 return false;
3384 }
3385
3386 if (FieldDecl *Field = Init->getMember())
3387 S.Diag(Init->getSourceLocation(),
3388 diag::err_multiple_mem_initialization)
3389 << Field->getDeclName()
3390 << Init->getSourceRange();
3391 else {
John McCallf4c73712011-01-19 06:33:43 +00003392 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003393 assert(BaseClass && "neither field nor base");
3394 S.Diag(Init->getSourceLocation(),
3395 diag::err_multiple_base_initialization)
3396 << QualType(BaseClass, 0)
3397 << Init->getSourceRange();
3398 }
3399 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3400 << 0 << PrevInit->getSourceRange();
3401
3402 return true;
3403}
3404
Sean Huntcbb67482011-01-08 20:30:50 +00003405typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003406typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3407
3408bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003409 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003410 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003411 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003412 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003413 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003414
3415 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003416 if (Parent->isUnion()) {
3417 UnionEntry &En = Unions[Parent];
3418 if (En.first && En.first != Child) {
3419 S.Diag(Init->getSourceLocation(),
3420 diag::err_multiple_mem_union_initialization)
3421 << Field->getDeclName()
3422 << Init->getSourceRange();
3423 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3424 << 0 << En.second->getSourceRange();
3425 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003426 }
3427 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003428 En.first = Child;
3429 En.second = Init;
3430 }
David Blaikie6fe29652011-11-17 06:01:57 +00003431 if (!Parent->isAnonymousStructOrUnion())
3432 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003433 }
3434
3435 Child = Parent;
3436 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003437 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003438
3439 return false;
3440}
3441}
3442
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003443/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003444void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003445 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003446 CXXCtorInitializer **meminits,
3447 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003448 bool AnyErrors) {
3449 if (!ConstructorDecl)
3450 return;
3451
3452 AdjustDeclIfTemplate(ConstructorDecl);
3453
3454 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003455 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003456
3457 if (!Constructor) {
3458 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3459 return;
3460 }
3461
Sean Huntcbb67482011-01-08 20:30:50 +00003462 CXXCtorInitializer **MemInits =
3463 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003464
3465 // Mapping for the duplicate initializers check.
3466 // For member initializers, this is keyed with a FieldDecl*.
3467 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003468 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003469
3470 // Mapping for the inconsistent anonymous-union initializers check.
3471 RedundantUnionMap MemberUnions;
3472
Anders Carlssonea356fb2010-04-02 05:42:15 +00003473 bool HadError = false;
3474 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003475 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003476
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003477 // Set the source order index.
3478 Init->setSourceOrder(i);
3479
Francois Pichet00eb3f92010-12-04 09:14:42 +00003480 if (Init->isAnyMemberInitializer()) {
3481 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003482 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3483 CheckRedundantUnionInit(*this, Init, MemberUnions))
3484 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003485 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003486 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3487 if (CheckRedundantInit(*this, Init, Members[Key]))
3488 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003489 } else {
3490 assert(Init->isDelegatingInitializer());
3491 // This must be the only initializer
Richard Smitha6ddea62012-09-14 18:21:10 +00003492 if (NumMemInits != 1) {
3493 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003494 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003495 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003496 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003497 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003498 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003499 // Return immediately as the initializer is set.
3500 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003501 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003502 }
3503
Anders Carlssonea356fb2010-04-02 05:42:15 +00003504 if (HadError)
3505 return;
3506
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003507 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003508
Sean Huntcbb67482011-01-08 20:30:50 +00003509 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003510}
3511
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003512void
John McCallef027fe2010-03-16 21:39:52 +00003513Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3514 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003515 // Ignore dependent contexts. Also ignore unions, since their members never
3516 // have destructors implicitly called.
3517 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003518 return;
John McCall58e6f342010-03-16 05:22:47 +00003519
3520 // FIXME: all the access-control diagnostics are positioned on the
3521 // field/base declaration. That's probably good; that said, the
3522 // user might reasonably want to know why the destructor is being
3523 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003524
Anders Carlsson9f853df2009-11-17 04:44:12 +00003525 // Non-static data members.
3526 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3527 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003528 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003529 if (Field->isInvalidDecl())
3530 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003531
3532 // Don't destroy incomplete or zero-length arrays.
3533 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3534 continue;
3535
Anders Carlsson9f853df2009-11-17 04:44:12 +00003536 QualType FieldType = Context.getBaseElementType(Field->getType());
3537
3538 const RecordType* RT = FieldType->getAs<RecordType>();
3539 if (!RT)
3540 continue;
3541
3542 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003543 if (FieldClassDecl->isInvalidDecl())
3544 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003545 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003546 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003547 // The destructor for an implicit anonymous union member is never invoked.
3548 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3549 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003550
Douglas Gregordb89f282010-07-01 22:47:18 +00003551 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003552 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003553 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003554 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003555 << Field->getDeclName()
3556 << FieldType);
3557
Eli Friedman5f2987c2012-02-02 03:46:19 +00003558 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003559 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003560 }
3561
John McCall58e6f342010-03-16 05:22:47 +00003562 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3563
Anders Carlsson9f853df2009-11-17 04:44:12 +00003564 // Bases.
3565 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3566 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003567 // Bases are always records in a well-formed non-dependent class.
3568 const RecordType *RT = Base->getType()->getAs<RecordType>();
3569
3570 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003571 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003572 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003573
John McCall58e6f342010-03-16 05:22:47 +00003574 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003575 // If our base class is invalid, we probably can't get its dtor anyway.
3576 if (BaseClassDecl->isInvalidDecl())
3577 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003578 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003579 continue;
John McCall58e6f342010-03-16 05:22:47 +00003580
Douglas Gregordb89f282010-07-01 22:47:18 +00003581 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003582 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003583
3584 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003585 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003586 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003587 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003588 << Base->getSourceRange(),
3589 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003590
Eli Friedman5f2987c2012-02-02 03:46:19 +00003591 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003592 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003593 }
3594
3595 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003596 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3597 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003598
3599 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003600 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003601
3602 // Ignore direct virtual bases.
3603 if (DirectVirtualBases.count(RT))
3604 continue;
3605
John McCall58e6f342010-03-16 05:22:47 +00003606 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003607 // If our base class is invalid, we probably can't get its dtor anyway.
3608 if (BaseClassDecl->isInvalidDecl())
3609 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003610 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003611 continue;
John McCall58e6f342010-03-16 05:22:47 +00003612
Douglas Gregordb89f282010-07-01 22:47:18 +00003613 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003614 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003615 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003616 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003617 << VBase->getType(),
3618 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003619
Eli Friedman5f2987c2012-02-02 03:46:19 +00003620 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003621 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003622 }
3623}
3624
John McCalld226f652010-08-21 09:40:31 +00003625void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003626 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003627 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Mike Stump1eb44332009-09-09 15:08:12 +00003629 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003630 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003631 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003632}
3633
Mike Stump1eb44332009-09-09 15:08:12 +00003634bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003635 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003636 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3637 unsigned DiagID;
3638 AbstractDiagSelID SelID;
3639
3640 public:
3641 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3642 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3643
3644 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003645 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003646 if (SelID == -1)
3647 S.Diag(Loc, DiagID) << T;
3648 else
3649 S.Diag(Loc, DiagID) << SelID << T;
3650 }
3651 } Diagnoser(DiagID, SelID);
3652
3653 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003654}
3655
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003656bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003657 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003658 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003659 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Anders Carlsson11f21a02009-03-23 19:10:31 +00003661 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003662 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Ted Kremenek6217b802009-07-29 21:53:49 +00003664 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003665 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003666 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003667 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003669 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003670 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003671 }
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Ted Kremenek6217b802009-07-29 21:53:49 +00003673 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003674 if (!RT)
3675 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003676
John McCall86ff3082010-02-04 22:26:26 +00003677 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003678
John McCall94c3b562010-08-18 09:41:07 +00003679 // We can't answer whether something is abstract until it has a
3680 // definition. If it's currently being defined, we'll walk back
3681 // over all the declarations when we have a full definition.
3682 const CXXRecordDecl *Def = RD->getDefinition();
3683 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003684 return false;
3685
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003686 if (!RD->isAbstract())
3687 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003689 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003690 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003691
John McCall94c3b562010-08-18 09:41:07 +00003692 return true;
3693}
3694
3695void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3696 // Check if we've already emitted the list of pure virtual functions
3697 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003698 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003699 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003700
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003701 CXXFinalOverriderMap FinalOverriders;
3702 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003704 // Keep a set of seen pure methods so we won't diagnose the same method
3705 // more than once.
3706 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3707
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003708 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3709 MEnd = FinalOverriders.end();
3710 M != MEnd;
3711 ++M) {
3712 for (OverridingMethods::iterator SO = M->second.begin(),
3713 SOEnd = M->second.end();
3714 SO != SOEnd; ++SO) {
3715 // C++ [class.abstract]p4:
3716 // A class is abstract if it contains or inherits at least one
3717 // pure virtual function for which the final overrider is pure
3718 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003720 //
3721 if (SO->second.size() != 1)
3722 continue;
3723
3724 if (!SO->second.front().Method->isPure())
3725 continue;
3726
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003727 if (!SeenPureMethods.insert(SO->second.front().Method))
3728 continue;
3729
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003730 Diag(SO->second.front().Method->getLocation(),
3731 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003732 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003733 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003734 }
3735
3736 if (!PureVirtualClassDiagSet)
3737 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3738 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003739}
3740
Anders Carlsson8211eff2009-03-24 01:19:16 +00003741namespace {
John McCall94c3b562010-08-18 09:41:07 +00003742struct AbstractUsageInfo {
3743 Sema &S;
3744 CXXRecordDecl *Record;
3745 CanQualType AbstractType;
3746 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003747
John McCall94c3b562010-08-18 09:41:07 +00003748 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3749 : S(S), Record(Record),
3750 AbstractType(S.Context.getCanonicalType(
3751 S.Context.getTypeDeclType(Record))),
3752 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003753
John McCall94c3b562010-08-18 09:41:07 +00003754 void DiagnoseAbstractType() {
3755 if (Invalid) return;
3756 S.DiagnoseAbstractType(Record);
3757 Invalid = true;
3758 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003759
John McCall94c3b562010-08-18 09:41:07 +00003760 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3761};
3762
3763struct CheckAbstractUsage {
3764 AbstractUsageInfo &Info;
3765 const NamedDecl *Ctx;
3766
3767 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3768 : Info(Info), Ctx(Ctx) {}
3769
3770 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3771 switch (TL.getTypeLocClass()) {
3772#define ABSTRACT_TYPELOC(CLASS, PARENT)
3773#define TYPELOC(CLASS, PARENT) \
3774 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3775#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003776 }
John McCall94c3b562010-08-18 09:41:07 +00003777 }
Mike Stump1eb44332009-09-09 15:08:12 +00003778
John McCall94c3b562010-08-18 09:41:07 +00003779 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3780 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3781 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003782 if (!TL.getArg(I))
3783 continue;
3784
John McCall94c3b562010-08-18 09:41:07 +00003785 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3786 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003787 }
John McCall94c3b562010-08-18 09:41:07 +00003788 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003789
John McCall94c3b562010-08-18 09:41:07 +00003790 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3791 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3792 }
Mike Stump1eb44332009-09-09 15:08:12 +00003793
John McCall94c3b562010-08-18 09:41:07 +00003794 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3795 // Visit the type parameters from a permissive context.
3796 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3797 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3798 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3799 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3800 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3801 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003802 }
John McCall94c3b562010-08-18 09:41:07 +00003803 }
Mike Stump1eb44332009-09-09 15:08:12 +00003804
John McCall94c3b562010-08-18 09:41:07 +00003805 // Visit pointee types from a permissive context.
3806#define CheckPolymorphic(Type) \
3807 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3808 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3809 }
3810 CheckPolymorphic(PointerTypeLoc)
3811 CheckPolymorphic(ReferenceTypeLoc)
3812 CheckPolymorphic(MemberPointerTypeLoc)
3813 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003814 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003815
John McCall94c3b562010-08-18 09:41:07 +00003816 /// Handle all the types we haven't given a more specific
3817 /// implementation for above.
3818 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3819 // Every other kind of type that we haven't called out already
3820 // that has an inner type is either (1) sugar or (2) contains that
3821 // inner type in some way as a subobject.
3822 if (TypeLoc Next = TL.getNextTypeLoc())
3823 return Visit(Next, Sel);
3824
3825 // If there's no inner type and we're in a permissive context,
3826 // don't diagnose.
3827 if (Sel == Sema::AbstractNone) return;
3828
3829 // Check whether the type matches the abstract type.
3830 QualType T = TL.getType();
3831 if (T->isArrayType()) {
3832 Sel = Sema::AbstractArrayType;
3833 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003834 }
John McCall94c3b562010-08-18 09:41:07 +00003835 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3836 if (CT != Info.AbstractType) return;
3837
3838 // It matched; do some magic.
3839 if (Sel == Sema::AbstractArrayType) {
3840 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3841 << T << TL.getSourceRange();
3842 } else {
3843 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3844 << Sel << T << TL.getSourceRange();
3845 }
3846 Info.DiagnoseAbstractType();
3847 }
3848};
3849
3850void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3851 Sema::AbstractDiagSelID Sel) {
3852 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3853}
3854
3855}
3856
3857/// Check for invalid uses of an abstract type in a method declaration.
3858static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3859 CXXMethodDecl *MD) {
3860 // No need to do the check on definitions, which require that
3861 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003862 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003863 return;
3864
3865 // For safety's sake, just ignore it if we don't have type source
3866 // information. This should never happen for non-implicit methods,
3867 // but...
3868 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3869 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3870}
3871
3872/// Check for invalid uses of an abstract type within a class definition.
3873static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3874 CXXRecordDecl *RD) {
3875 for (CXXRecordDecl::decl_iterator
3876 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3877 Decl *D = *I;
3878 if (D->isImplicit()) continue;
3879
3880 // Methods and method templates.
3881 if (isa<CXXMethodDecl>(D)) {
3882 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3883 } else if (isa<FunctionTemplateDecl>(D)) {
3884 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3885 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3886
3887 // Fields and static variables.
3888 } else if (isa<FieldDecl>(D)) {
3889 FieldDecl *FD = cast<FieldDecl>(D);
3890 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3891 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3892 } else if (isa<VarDecl>(D)) {
3893 VarDecl *VD = cast<VarDecl>(D);
3894 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3895 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3896
3897 // Nested classes and class templates.
3898 } else if (isa<CXXRecordDecl>(D)) {
3899 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3900 } else if (isa<ClassTemplateDecl>(D)) {
3901 CheckAbstractClassUsage(Info,
3902 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3903 }
3904 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003905}
3906
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003907/// \brief Perform semantic checks on a class definition that has been
3908/// completing, introducing implicitly-declared members, checking for
3909/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003910void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003911 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003912 return;
3913
John McCall94c3b562010-08-18 09:41:07 +00003914 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3915 AbstractUsageInfo Info(*this, Record);
3916 CheckAbstractClassUsage(Info, Record);
3917 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003918
3919 // If this is not an aggregate type and has no user-declared constructor,
3920 // complain about any non-static data members of reference or const scalar
3921 // type, since they will never get initializers.
3922 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003923 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3924 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003925 bool Complained = false;
3926 for (RecordDecl::field_iterator F = Record->field_begin(),
3927 FEnd = Record->field_end();
3928 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003929 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003930 continue;
3931
Douglas Gregor325e5932010-04-15 00:00:53 +00003932 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003933 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003934 if (!Complained) {
3935 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3936 << Record->getTagKind() << Record;
3937 Complained = true;
3938 }
3939
3940 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3941 << F->getType()->isReferenceType()
3942 << F->getDeclName();
3943 }
3944 }
3945 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003946
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003947 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003948 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003949
3950 if (Record->getIdentifier()) {
3951 // C++ [class.mem]p13:
3952 // If T is the name of a class, then each of the following shall have a
3953 // name different from T:
3954 // - every member of every anonymous union that is a member of class T.
3955 //
3956 // C++ [class.mem]p14:
3957 // In addition, if class T has a user-declared constructor (12.1), every
3958 // non-static data member of class T shall have a name different from T.
3959 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003960 R.first != R.second; ++R.first) {
3961 NamedDecl *D = *R.first;
3962 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3963 isa<IndirectFieldDecl>(D)) {
3964 Diag(D->getLocation(), diag::err_member_name_of_class)
3965 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003966 break;
3967 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003968 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003969 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003970
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003971 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003972 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003973 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003974 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003975 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3976 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3977 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003978
David Blaikieb6b5b972012-09-21 03:21:07 +00003979 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3980 Diag(Record->getLocation(), diag::warn_abstract_final_class);
3981 DiagnoseAbstractType(Record);
3982 }
3983
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003984 // See if a method overloads virtual methods in a base
3985 /// class without overriding any.
3986 if (!Record->isDependentType()) {
3987 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3988 MEnd = Record->method_end();
3989 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003990 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003991 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003992 }
3993 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003994
3995 // Declare inherited constructors. We do this eagerly here because:
3996 // - The standard requires an eager diagnostic for conflicting inherited
3997 // constructors from different classes.
3998 // - The lazy declaration of the other implicit constructors is so as to not
3999 // waste space and performance on classes that are not meant to be
4000 // instantiated (e.g. meta-functions). This doesn't apply to classes that
4001 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00004002 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004003}
4004
Richard Smithac713512012-12-08 02:53:02 +00004005void Sema::CheckExplicitlyDefaultedAndDeletedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004006 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
4007 ME = Record->method_end();
Richard Smithac713512012-12-08 02:53:02 +00004008 MI != ME; ++MI) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004009 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00004010 CheckExplicitlyDefaultedSpecialMember(*MI);
Richard Smithac713512012-12-08 02:53:02 +00004011
4012 if (!MI->isImplicit() && !MI->isUserProvided()) {
4013 // For an explicitly defaulted or deleted special member, we defer
4014 // determining triviality until the class is complete. That time is now!
4015 CXXSpecialMember CSM = getSpecialMember(*MI);
4016 if (CSM != CXXInvalid) {
4017 MI->setTrivial(SpecialMemberIsTrivial(*MI, CSM));
4018
4019 // Inform the class that we've finished declaring this member.
4020 Record->finishedDefaultedOrDeletedMember(*MI);
4021 }
4022 }
4023 }
Sean Hunt001cad92011-05-10 00:49:42 +00004024}
4025
Richard Smith7756afa2012-06-10 05:43:50 +00004026/// Is the special member function which would be selected to perform the
4027/// specified operation on the specified class type a constexpr constructor?
4028static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4029 Sema::CXXSpecialMember CSM,
4030 bool ConstArg) {
4031 Sema::SpecialMemberOverloadResult *SMOR =
4032 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4033 false, false, false, false);
4034 if (!SMOR || !SMOR->getMethod())
4035 // A constructor we wouldn't select can't be "involved in initializing"
4036 // anything.
4037 return true;
4038 return SMOR->getMethod()->isConstexpr();
4039}
4040
4041/// Determine whether the specified special member function would be constexpr
4042/// if it were implicitly defined.
4043static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4044 Sema::CXXSpecialMember CSM,
4045 bool ConstArg) {
4046 if (!S.getLangOpts().CPlusPlus0x)
4047 return false;
4048
4049 // C++11 [dcl.constexpr]p4:
4050 // In the definition of a constexpr constructor [...]
4051 switch (CSM) {
4052 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004053 // Since default constructor lookup is essentially trivial (and cannot
4054 // involve, for instance, template instantiation), we compute whether a
4055 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4056 //
4057 // This is important for performance; we need to know whether the default
4058 // constructor is constexpr to determine whether the type is a literal type.
4059 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4060
Richard Smith7756afa2012-06-10 05:43:50 +00004061 case Sema::CXXCopyConstructor:
4062 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004063 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004064 break;
4065
4066 case Sema::CXXCopyAssignment:
4067 case Sema::CXXMoveAssignment:
4068 case Sema::CXXDestructor:
4069 case Sema::CXXInvalid:
4070 return false;
4071 }
4072
4073 // -- if the class is a non-empty union, or for each non-empty anonymous
4074 // union member of a non-union class, exactly one non-static data member
4075 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004076 //
4077 // If we squint, this is guaranteed, since exactly one non-static data member
4078 // will be initialized (if the constructor isn't deleted), we just don't know
4079 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00004080 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004081 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004082
4083 // -- the class shall not have any virtual base classes;
4084 if (ClassDecl->getNumVBases())
4085 return false;
4086
4087 // -- every constructor involved in initializing [...] base class
4088 // sub-objects shall be a constexpr constructor;
4089 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4090 BEnd = ClassDecl->bases_end();
4091 B != BEnd; ++B) {
4092 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4093 if (!BaseType) continue;
4094
4095 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4096 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4097 return false;
4098 }
4099
4100 // -- every constructor involved in initializing non-static data members
4101 // [...] shall be a constexpr constructor;
4102 // -- every non-static data member and base class sub-object shall be
4103 // initialized
4104 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4105 FEnd = ClassDecl->field_end();
4106 F != FEnd; ++F) {
4107 if (F->isInvalidDecl())
4108 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004109 if (const RecordType *RecordTy =
4110 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004111 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4112 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4113 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004114 }
4115 }
4116
4117 // All OK, it's constexpr!
4118 return true;
4119}
4120
Richard Smithb9d0b762012-07-27 04:22:15 +00004121static Sema::ImplicitExceptionSpecification
4122computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4123 switch (S.getSpecialMember(MD)) {
4124 case Sema::CXXDefaultConstructor:
4125 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4126 case Sema::CXXCopyConstructor:
4127 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4128 case Sema::CXXCopyAssignment:
4129 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4130 case Sema::CXXMoveConstructor:
4131 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4132 case Sema::CXXMoveAssignment:
4133 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4134 case Sema::CXXDestructor:
4135 return S.ComputeDefaultedDtorExceptionSpec(MD);
4136 case Sema::CXXInvalid:
4137 break;
4138 }
4139 llvm_unreachable("only special members have implicit exception specs");
4140}
4141
Richard Smithdd25e802012-07-30 23:48:14 +00004142static void
4143updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4144 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4145 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4146 ExceptSpec.getEPI(EPI);
4147 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4148 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4149 FPT->getNumArgs(), EPI));
4150 FD->setType(QualType(NewFPT, 0));
4151}
4152
Richard Smithb9d0b762012-07-27 04:22:15 +00004153void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4154 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4155 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4156 return;
4157
Richard Smithdd25e802012-07-30 23:48:14 +00004158 // Evaluate the exception specification.
4159 ImplicitExceptionSpecification ExceptSpec =
4160 computeImplicitExceptionSpec(*this, Loc, MD);
4161
4162 // Update the type of the special member to use it.
4163 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4164
4165 // A user-provided destructor can be defined outside the class. When that
4166 // happens, be sure to update the exception specification on both
4167 // declarations.
4168 const FunctionProtoType *CanonicalFPT =
4169 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4170 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4171 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4172 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004173}
4174
Richard Smith3003e1d2012-05-15 04:39:51 +00004175void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4176 CXXRecordDecl *RD = MD->getParent();
4177 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004178
Richard Smith3003e1d2012-05-15 04:39:51 +00004179 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4180 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004181
4182 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004183 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004184 bool First = MD == MD->getCanonicalDecl();
4185
4186 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004187
4188 // C++11 [dcl.fct.def.default]p1:
4189 // A function that is explicitly defaulted shall
4190 // -- be a special member function (checked elsewhere),
4191 // -- have the same type (except for ref-qualifiers, and except that a
4192 // copy operation can take a non-const reference) as an implicit
4193 // declaration, and
4194 // -- not have default arguments.
4195 unsigned ExpectedParams = 1;
4196 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4197 ExpectedParams = 0;
4198 if (MD->getNumParams() != ExpectedParams) {
4199 // This also checks for default arguments: a copy or move constructor with a
4200 // default argument is classified as a default constructor, and assignment
4201 // operations and destructors can't have default arguments.
4202 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4203 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004204 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004205 } else if (MD->isVariadic()) {
4206 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4207 << CSM << MD->getSourceRange();
4208 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004209 }
4210
Richard Smith3003e1d2012-05-15 04:39:51 +00004211 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004212
Richard Smith7756afa2012-06-10 05:43:50 +00004213 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004214 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004215 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004216 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004217 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004218
Richard Smith3003e1d2012-05-15 04:39:51 +00004219 QualType ReturnType = Context.VoidTy;
4220 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4221 // Check for return type matching.
4222 ReturnType = Type->getResultType();
4223 QualType ExpectedReturnType =
4224 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4225 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4226 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4227 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4228 HadError = true;
4229 }
4230
4231 // A defaulted special member cannot have cv-qualifiers.
4232 if (Type->getTypeQuals()) {
4233 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4234 << (CSM == CXXMoveAssignment);
4235 HadError = true;
4236 }
4237 }
4238
4239 // Check for parameter type matching.
4240 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004241 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004242 if (ExpectedParams && ArgType->isReferenceType()) {
4243 // Argument must be reference to possibly-const T.
4244 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004245 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004246
4247 if (ReferentType.isVolatileQualified()) {
4248 Diag(MD->getLocation(),
4249 diag::err_defaulted_special_member_volatile_param) << CSM;
4250 HadError = true;
4251 }
4252
Richard Smith7756afa2012-06-10 05:43:50 +00004253 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004254 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4255 Diag(MD->getLocation(),
4256 diag::err_defaulted_special_member_copy_const_param)
4257 << (CSM == CXXCopyAssignment);
4258 // FIXME: Explain why this special member can't be const.
4259 } else {
4260 Diag(MD->getLocation(),
4261 diag::err_defaulted_special_member_move_const_param)
4262 << (CSM == CXXMoveAssignment);
4263 }
4264 HadError = true;
4265 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004266 } else if (ExpectedParams) {
4267 // A copy assignment operator can take its argument by value, but a
4268 // defaulted one cannot.
4269 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004270 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004271 HadError = true;
4272 }
Sean Huntbe631222011-05-17 20:44:43 +00004273
Richard Smithb9d0b762012-07-27 04:22:15 +00004274 // Rebuild the type with the implicit exception specification added, if we
4275 // are going to need it.
4276 const FunctionProtoType *ImplicitType = 0;
4277 if (First || Type->hasExceptionSpec()) {
4278 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4279 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4280 ImplicitType = cast<FunctionProtoType>(
4281 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4282 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004283
Richard Smith61802452011-12-22 02:22:31 +00004284 // C++11 [dcl.fct.def.default]p2:
4285 // An explicitly-defaulted function may be declared constexpr only if it
4286 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004287 // Do not apply this rule to members of class templates, since core issue 1358
4288 // makes such functions always instantiate to constexpr functions. For
4289 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004290 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4291 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004292 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4293 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4294 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004295 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004296 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004297 }
4298 // and may have an explicit exception-specification only if it is compatible
4299 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004300 if (Type->hasExceptionSpec() &&
4301 CheckEquivalentExceptionSpec(
4302 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4303 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4304 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004305
4306 // If a function is explicitly defaulted on its first declaration,
4307 if (First) {
4308 // -- it is implicitly considered to be constexpr if the implicit
4309 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004310 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004311
Richard Smith3003e1d2012-05-15 04:39:51 +00004312 // -- it is implicitly considered to have the same exception-specification
4313 // as if it had been implicitly declared,
4314 MD->setType(QualType(ImplicitType, 0));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004315 }
4316
Richard Smith3003e1d2012-05-15 04:39:51 +00004317 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004318 if (First) {
4319 MD->setDeletedAsWritten();
4320 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004321 // C++11 [dcl.fct.def.default]p4:
4322 // [For a] user-provided explicitly-defaulted function [...] if such a
4323 // function is implicitly defined as deleted, the program is ill-formed.
4324 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4325 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004326 }
4327 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004328
Richard Smith3003e1d2012-05-15 04:39:51 +00004329 if (HadError)
4330 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004331}
4332
Richard Smith7d5088a2012-02-18 02:02:13 +00004333namespace {
4334struct SpecialMemberDeletionInfo {
4335 Sema &S;
4336 CXXMethodDecl *MD;
4337 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004338 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004339
4340 // Properties of the special member, computed for convenience.
4341 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4342 SourceLocation Loc;
4343
4344 bool AllFieldsAreConst;
4345
4346 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004347 Sema::CXXSpecialMember CSM, bool Diagnose)
4348 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004349 IsConstructor(false), IsAssignment(false), IsMove(false),
4350 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4351 AllFieldsAreConst(true) {
4352 switch (CSM) {
4353 case Sema::CXXDefaultConstructor:
4354 case Sema::CXXCopyConstructor:
4355 IsConstructor = true;
4356 break;
4357 case Sema::CXXMoveConstructor:
4358 IsConstructor = true;
4359 IsMove = true;
4360 break;
4361 case Sema::CXXCopyAssignment:
4362 IsAssignment = true;
4363 break;
4364 case Sema::CXXMoveAssignment:
4365 IsAssignment = true;
4366 IsMove = true;
4367 break;
4368 case Sema::CXXDestructor:
4369 break;
4370 case Sema::CXXInvalid:
4371 llvm_unreachable("invalid special member kind");
4372 }
4373
4374 if (MD->getNumParams()) {
4375 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4376 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4377 }
4378 }
4379
4380 bool inUnion() const { return MD->getParent()->isUnion(); }
4381
4382 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004383 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4384 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004385 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004386 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4387 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4388 Quals = 0;
4389 return S.LookupSpecialMember(Class, CSM,
4390 ConstArg || (Quals & Qualifiers::Const),
4391 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004392 MD->getRefQualifier() == RQ_RValue,
4393 TQ & Qualifiers::Const,
4394 TQ & Qualifiers::Volatile);
4395 }
4396
Richard Smith6c4c36c2012-03-30 20:53:28 +00004397 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004398
Richard Smith6c4c36c2012-03-30 20:53:28 +00004399 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004400 bool shouldDeleteForField(FieldDecl *FD);
4401 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004402
Richard Smith517bb842012-07-18 03:51:16 +00004403 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4404 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004405 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4406 Sema::SpecialMemberOverloadResult *SMOR,
4407 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004408
4409 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004410};
4411}
4412
John McCall12d8d802012-04-09 20:53:23 +00004413/// Is the given special member inaccessible when used on the given
4414/// sub-object.
4415bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4416 CXXMethodDecl *target) {
4417 /// If we're operating on a base class, the object type is the
4418 /// type of this special member.
4419 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004420 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004421 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4422 objectTy = S.Context.getTypeDeclType(MD->getParent());
4423 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4424
4425 // If we're operating on a field, the object type is the type of the field.
4426 } else {
4427 objectTy = S.Context.getTypeDeclType(target->getParent());
4428 }
4429
4430 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4431}
4432
Richard Smith6c4c36c2012-03-30 20:53:28 +00004433/// Check whether we should delete a special member due to the implicit
4434/// definition containing a call to a special member of a subobject.
4435bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4436 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4437 bool IsDtorCallInCtor) {
4438 CXXMethodDecl *Decl = SMOR->getMethod();
4439 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4440
4441 int DiagKind = -1;
4442
4443 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4444 DiagKind = !Decl ? 0 : 1;
4445 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4446 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004447 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004448 DiagKind = 3;
4449 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4450 !Decl->isTrivial()) {
4451 // A member of a union must have a trivial corresponding special member.
4452 // As a weird special case, a destructor call from a union's constructor
4453 // must be accessible and non-deleted, but need not be trivial. Such a
4454 // destructor is never actually called, but is semantically checked as
4455 // if it were.
4456 DiagKind = 4;
4457 }
4458
4459 if (DiagKind == -1)
4460 return false;
4461
4462 if (Diagnose) {
4463 if (Field) {
4464 S.Diag(Field->getLocation(),
4465 diag::note_deleted_special_member_class_subobject)
4466 << CSM << MD->getParent() << /*IsField*/true
4467 << Field << DiagKind << IsDtorCallInCtor;
4468 } else {
4469 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4470 S.Diag(Base->getLocStart(),
4471 diag::note_deleted_special_member_class_subobject)
4472 << CSM << MD->getParent() << /*IsField*/false
4473 << Base->getType() << DiagKind << IsDtorCallInCtor;
4474 }
4475
4476 if (DiagKind == 1)
4477 S.NoteDeletedFunction(Decl);
4478 // FIXME: Explain inaccessibility if DiagKind == 3.
4479 }
4480
4481 return true;
4482}
4483
Richard Smith9a561d52012-02-26 09:11:52 +00004484/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004485/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004486bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004487 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004488 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004489
4490 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004491 // -- any direct or virtual base class, or non-static data member with no
4492 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004493 // either M has no default constructor or overload resolution as applied
4494 // to M's default constructor results in an ambiguity or in a function
4495 // that is deleted or inaccessible
4496 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4497 // -- a direct or virtual base class B that cannot be copied/moved because
4498 // overload resolution, as applied to B's corresponding special member,
4499 // results in an ambiguity or a function that is deleted or inaccessible
4500 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004501 // C++11 [class.dtor]p5:
4502 // -- any direct or virtual base class [...] has a type with a destructor
4503 // that is deleted or inaccessible
4504 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004505 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004506 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004507 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004508
Richard Smith6c4c36c2012-03-30 20:53:28 +00004509 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4510 // -- any direct or virtual base class or non-static data member has a
4511 // type with a destructor that is deleted or inaccessible
4512 if (IsConstructor) {
4513 Sema::SpecialMemberOverloadResult *SMOR =
4514 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4515 false, false, false, false, false);
4516 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4517 return true;
4518 }
4519
Richard Smith9a561d52012-02-26 09:11:52 +00004520 return false;
4521}
4522
4523/// Check whether we should delete a special member function due to the class
4524/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004525bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004526 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004527 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004528}
4529
4530/// Check whether we should delete a special member function due to the class
4531/// having a particular non-static data member.
4532bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4533 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4534 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4535
4536 if (CSM == Sema::CXXDefaultConstructor) {
4537 // For a default constructor, all references must be initialized in-class
4538 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004539 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4540 if (Diagnose)
4541 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4542 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004543 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004544 }
Richard Smith79363f52012-02-27 06:07:25 +00004545 // C++11 [class.ctor]p5: any non-variant non-static data member of
4546 // const-qualified type (or array thereof) with no
4547 // brace-or-equal-initializer does not have a user-provided default
4548 // constructor.
4549 if (!inUnion() && FieldType.isConstQualified() &&
4550 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004551 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4552 if (Diagnose)
4553 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004554 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004555 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004556 }
4557
4558 if (inUnion() && !FieldType.isConstQualified())
4559 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004560 } else if (CSM == Sema::CXXCopyConstructor) {
4561 // For a copy constructor, data members must not be of rvalue reference
4562 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004563 if (FieldType->isRValueReferenceType()) {
4564 if (Diagnose)
4565 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4566 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004567 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004568 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004569 } else if (IsAssignment) {
4570 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004571 if (FieldType->isReferenceType()) {
4572 if (Diagnose)
4573 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4574 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004575 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004576 }
4577 if (!FieldRecord && FieldType.isConstQualified()) {
4578 // C++11 [class.copy]p23:
4579 // -- a non-static data member of const non-class type (or array thereof)
4580 if (Diagnose)
4581 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004582 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004583 return true;
4584 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004585 }
4586
4587 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004588 // Some additional restrictions exist on the variant members.
4589 if (!inUnion() && FieldRecord->isUnion() &&
4590 FieldRecord->isAnonymousStructOrUnion()) {
4591 bool AllVariantFieldsAreConst = true;
4592
Richard Smithdf8dc862012-03-29 19:00:10 +00004593 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004594 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4595 UE = FieldRecord->field_end();
4596 UI != UE; ++UI) {
4597 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004598
4599 if (!UnionFieldType.isConstQualified())
4600 AllVariantFieldsAreConst = false;
4601
Richard Smith9a561d52012-02-26 09:11:52 +00004602 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4603 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004604 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4605 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004606 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004607 }
4608
4609 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004610 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004611 FieldRecord->field_begin() != FieldRecord->field_end()) {
4612 if (Diagnose)
4613 S.Diag(FieldRecord->getLocation(),
4614 diag::note_deleted_default_ctor_all_const)
4615 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004616 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004617 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004618
Richard Smithdf8dc862012-03-29 19:00:10 +00004619 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004620 // This is technically non-conformant, but sanity demands it.
4621 return false;
4622 }
4623
Richard Smith517bb842012-07-18 03:51:16 +00004624 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4625 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004626 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004627 }
4628
4629 return false;
4630}
4631
4632/// C++11 [class.ctor] p5:
4633/// A defaulted default constructor for a class X is defined as deleted if
4634/// X is a union and all of its variant members are of const-qualified type.
4635bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004636 // This is a silly definition, because it gives an empty union a deleted
4637 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004638 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4639 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4640 if (Diagnose)
4641 S.Diag(MD->getParent()->getLocation(),
4642 diag::note_deleted_default_ctor_all_const)
4643 << MD->getParent() << /*not anonymous union*/0;
4644 return true;
4645 }
4646 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004647}
4648
4649/// Determine whether a defaulted special member function should be defined as
4650/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4651/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004652bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4653 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004654 if (MD->isInvalidDecl())
4655 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004656 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004657 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004658 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004659 return false;
4660
Richard Smith7d5088a2012-02-18 02:02:13 +00004661 // C++11 [expr.lambda.prim]p19:
4662 // The closure type associated with a lambda-expression has a
4663 // deleted (8.4.3) default constructor and a deleted copy
4664 // assignment operator.
4665 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004666 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4667 if (Diagnose)
4668 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004669 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004670 }
4671
Richard Smith5bdaac52012-04-02 20:59:25 +00004672 // For an anonymous struct or union, the copy and assignment special members
4673 // will never be used, so skip the check. For an anonymous union declared at
4674 // namespace scope, the constructor and destructor are used.
4675 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4676 RD->isAnonymousStructOrUnion())
4677 return false;
4678
Richard Smith6c4c36c2012-03-30 20:53:28 +00004679 // C++11 [class.copy]p7, p18:
4680 // If the class definition declares a move constructor or move assignment
4681 // operator, an implicitly declared copy constructor or copy assignment
4682 // operator is defined as deleted.
4683 if (MD->isImplicit() &&
4684 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4685 CXXMethodDecl *UserDeclaredMove = 0;
4686
4687 // In Microsoft mode, a user-declared move only causes the deletion of the
4688 // corresponding copy operation, not both copy operations.
4689 if (RD->hasUserDeclaredMoveConstructor() &&
4690 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4691 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004692
4693 // Find any user-declared move constructor.
4694 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4695 E = RD->ctor_end(); I != E; ++I) {
4696 if (I->isMoveConstructor()) {
4697 UserDeclaredMove = *I;
4698 break;
4699 }
4700 }
Richard Smith1c931be2012-04-02 18:40:40 +00004701 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004702 } else if (RD->hasUserDeclaredMoveAssignment() &&
4703 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4704 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00004705
4706 // Find any user-declared move assignment operator.
4707 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4708 E = RD->method_end(); I != E; ++I) {
4709 if (I->isMoveAssignmentOperator()) {
4710 UserDeclaredMove = *I;
4711 break;
4712 }
4713 }
Richard Smith1c931be2012-04-02 18:40:40 +00004714 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004715 }
4716
4717 if (UserDeclaredMove) {
4718 Diag(UserDeclaredMove->getLocation(),
4719 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004720 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004721 << UserDeclaredMove->isMoveAssignmentOperator();
4722 return true;
4723 }
4724 }
Sean Hunte16da072011-10-10 06:18:57 +00004725
Richard Smith5bdaac52012-04-02 20:59:25 +00004726 // Do access control from the special member function
4727 ContextRAII MethodContext(*this, MD);
4728
Richard Smith9a561d52012-02-26 09:11:52 +00004729 // C++11 [class.dtor]p5:
4730 // -- for a virtual destructor, lookup of the non-array deallocation function
4731 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004732 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004733 FunctionDecl *OperatorDelete = 0;
4734 DeclarationName Name =
4735 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4736 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004737 OperatorDelete, false)) {
4738 if (Diagnose)
4739 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004740 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004741 }
Richard Smith9a561d52012-02-26 09:11:52 +00004742 }
4743
Richard Smith6c4c36c2012-03-30 20:53:28 +00004744 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004745
Sean Huntcdee3fe2011-05-11 22:34:38 +00004746 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004747 BE = RD->bases_end(); BI != BE; ++BI)
4748 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004749 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004750 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004751
4752 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004753 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004754 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004755 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004756
4757 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004758 FE = RD->field_end(); FI != FE; ++FI)
4759 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004760 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004761 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004762
Richard Smith7d5088a2012-02-18 02:02:13 +00004763 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004764 return true;
4765
4766 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004767}
4768
Richard Smithac713512012-12-08 02:53:02 +00004769/// Perform lookup for a special member of the specified kind, and determine
4770/// whether it is trivial. If the triviality can be determined without the
4771/// lookup, skip it. This is intended for use when determining whether a
4772/// special member of a containing object is trivial, and thus does not ever
4773/// perform overload resolution for default constructors.
4774///
4775/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4776/// member that was most likely to be intended to be trivial, if any.
4777static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4778 Sema::CXXSpecialMember CSM, unsigned Quals,
4779 CXXMethodDecl **Selected) {
4780 if (Selected)
4781 *Selected = 0;
4782
4783 switch (CSM) {
4784 case Sema::CXXInvalid:
4785 llvm_unreachable("not a special member");
4786
4787 case Sema::CXXDefaultConstructor:
4788 // C++11 [class.ctor]p5:
4789 // A default constructor is trivial if:
4790 // - all the [direct subobjects] have trivial default constructors
4791 //
4792 // Note, no overload resolution is performed in this case.
4793 if (RD->hasTrivialDefaultConstructor())
4794 return true;
4795
4796 if (Selected) {
4797 // If there's a default constructor which could have been trivial, dig it
4798 // out. Otherwise, if there's any user-provided default constructor, point
4799 // to that as an example of why there's not a trivial one.
4800 CXXConstructorDecl *DefCtor = 0;
4801 if (RD->needsImplicitDefaultConstructor())
4802 S.DeclareImplicitDefaultConstructor(RD);
4803 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4804 CE = RD->ctor_end(); CI != CE; ++CI) {
4805 if (!CI->isDefaultConstructor())
4806 continue;
4807 DefCtor = *CI;
4808 if (!DefCtor->isUserProvided())
4809 break;
4810 }
4811
4812 *Selected = DefCtor;
4813 }
4814
4815 return false;
4816
4817 case Sema::CXXDestructor:
4818 // C++11 [class.dtor]p5:
4819 // A destructor is trivial if:
4820 // - all the direct [subobjects] have trivial destructors
4821 if (RD->hasTrivialDestructor())
4822 return true;
4823
4824 if (Selected) {
4825 if (RD->needsImplicitDestructor())
4826 S.DeclareImplicitDestructor(RD);
4827 *Selected = RD->getDestructor();
4828 }
4829
4830 return false;
4831
4832 case Sema::CXXCopyConstructor:
4833 // C++11 [class.copy]p12:
4834 // A copy constructor is trivial if:
4835 // - the constructor selected to copy each direct [subobject] is trivial
4836 if (RD->hasTrivialCopyConstructor()) {
4837 if (Quals == Qualifiers::Const)
4838 // We must either select the trivial copy constructor or reach an
4839 // ambiguity; no need to actually perform overload resolution.
4840 return true;
4841 } else if (!Selected) {
4842 return false;
4843 }
4844 // In C++98, we are not supposed to perform overload resolution here, but we
4845 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4846 // cases like B as having a non-trivial copy constructor:
4847 // struct A { template<typename T> A(T&); };
4848 // struct B { mutable A a; };
4849 goto NeedOverloadResolution;
4850
4851 case Sema::CXXCopyAssignment:
4852 // C++11 [class.copy]p25:
4853 // A copy assignment operator is trivial if:
4854 // - the assignment operator selected to copy each direct [subobject] is
4855 // trivial
4856 if (RD->hasTrivialCopyAssignment()) {
4857 if (Quals == Qualifiers::Const)
4858 return true;
4859 } else if (!Selected) {
4860 return false;
4861 }
4862 // In C++98, we are not supposed to perform overload resolution here, but we
4863 // treat that as a language defect.
4864 goto NeedOverloadResolution;
4865
4866 case Sema::CXXMoveConstructor:
4867 case Sema::CXXMoveAssignment:
4868 NeedOverloadResolution:
4869 Sema::SpecialMemberOverloadResult *SMOR =
4870 S.LookupSpecialMember(RD, CSM,
4871 Quals & Qualifiers::Const,
4872 Quals & Qualifiers::Volatile,
4873 /*RValueThis*/false, /*ConstThis*/false,
4874 /*VolatileThis*/false);
4875
4876 // The standard doesn't describe how to behave if the lookup is ambiguous.
4877 // We treat it as not making the member non-trivial, just like the standard
4878 // mandates for the default constructor. This should rarely matter, because
4879 // the member will also be deleted.
4880 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4881 return true;
4882
4883 if (!SMOR->getMethod()) {
4884 assert(SMOR->getKind() ==
4885 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4886 return false;
4887 }
4888
4889 // We deliberately don't check if we found a deleted special member. We're
4890 // not supposed to!
4891 if (Selected)
4892 *Selected = SMOR->getMethod();
4893 return SMOR->getMethod()->isTrivial();
4894 }
4895
4896 llvm_unreachable("unknown special method kind");
4897}
4898
4899CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4900 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4901 CI != CE; ++CI)
4902 if (!CI->isImplicit())
4903 return *CI;
4904
4905 // Look for constructor templates.
4906 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4907 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4908 if (CXXConstructorDecl *CD =
4909 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4910 return CD;
4911 }
4912
4913 return 0;
4914}
4915
4916/// The kind of subobject we are checking for triviality. The values of this
4917/// enumeration are used in diagnostics.
4918enum TrivialSubobjectKind {
4919 /// The subobject is a base class.
4920 TSK_BaseClass,
4921 /// The subobject is a non-static data member.
4922 TSK_Field,
4923 /// The object is actually the complete object.
4924 TSK_CompleteObject
4925};
4926
4927/// Check whether the special member selected for a given type would be trivial.
4928static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4929 QualType SubType,
4930 Sema::CXXSpecialMember CSM,
4931 TrivialSubobjectKind Kind,
4932 bool Diagnose) {
4933 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4934 if (!SubRD)
4935 return true;
4936
4937 CXXMethodDecl *Selected;
4938 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
4939 Diagnose ? &Selected : 0))
4940 return true;
4941
4942 if (Diagnose) {
4943 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
4944 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
4945 << Kind << SubType.getUnqualifiedType();
4946 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
4947 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
4948 } else if (!Selected)
4949 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
4950 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
4951 else if (Selected->isUserProvided()) {
4952 if (Kind == TSK_CompleteObject)
4953 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
4954 << Kind << SubType.getUnqualifiedType() << CSM;
4955 else {
4956 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
4957 << Kind << SubType.getUnqualifiedType() << CSM;
4958 S.Diag(Selected->getLocation(), diag::note_declared_at);
4959 }
4960 } else {
4961 if (Kind != TSK_CompleteObject)
4962 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
4963 << Kind << SubType.getUnqualifiedType() << CSM;
4964
4965 // Explain why the defaulted or deleted special member isn't trivial.
4966 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
4967 }
4968 }
4969
4970 return false;
4971}
4972
4973/// Check whether the members of a class type allow a special member to be
4974/// trivial.
4975static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
4976 Sema::CXXSpecialMember CSM,
4977 bool ConstArg, bool Diagnose) {
4978 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4979 FE = RD->field_end(); FI != FE; ++FI) {
4980 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
4981 continue;
4982
4983 QualType FieldType = S.Context.getBaseElementType(FI->getType());
4984
4985 // Pretend anonymous struct or union members are members of this class.
4986 if (FI->isAnonymousStructOrUnion()) {
4987 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
4988 CSM, ConstArg, Diagnose))
4989 return false;
4990 continue;
4991 }
4992
4993 // C++11 [class.ctor]p5:
4994 // A default constructor is trivial if [...]
4995 // -- no non-static data member of its class has a
4996 // brace-or-equal-initializer
4997 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
4998 if (Diagnose)
4999 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5000 return false;
5001 }
5002
5003 // Objective C ARC 4.3.5:
5004 // [...] nontrivally ownership-qualified types are [...] not trivially
5005 // default constructible, copy constructible, move constructible, copy
5006 // assignable, move assignable, or destructible [...]
5007 if (S.getLangOpts().ObjCAutoRefCount &&
5008 FieldType.hasNonTrivialObjCLifetime()) {
5009 if (Diagnose)
5010 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5011 << RD << FieldType.getObjCLifetime();
5012 return false;
5013 }
5014
5015 if (ConstArg && !FI->isMutable())
5016 FieldType.addConst();
5017 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5018 TSK_Field, Diagnose))
5019 return false;
5020 }
5021
5022 return true;
5023}
5024
5025/// Diagnose why the specified class does not have a trivial special member of
5026/// the given kind.
5027void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5028 QualType Ty = Context.getRecordType(RD);
5029 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5030 Ty.addConst();
5031
5032 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5033 TSK_CompleteObject, /*Diagnose*/true);
5034}
5035
5036/// Determine whether a defaulted or deleted special member function is trivial,
5037/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5038/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5039bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5040 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005041 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5042
5043 CXXRecordDecl *RD = MD->getParent();
5044
5045 bool ConstArg = false;
5046 ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5047
5048 // C++11 [class.copy]p12, p25:
5049 // A [special member] is trivial if its declared parameter type is the same
5050 // as if it had been implicitly declared [...]
5051 switch (CSM) {
5052 case CXXDefaultConstructor:
5053 case CXXDestructor:
5054 // Trivial default constructors and destructors cannot have parameters.
5055 break;
5056
5057 case CXXCopyConstructor:
5058 case CXXCopyAssignment: {
5059 // Trivial copy operations always have const, non-volatile parameter types.
5060 ConstArg = true;
5061 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5062 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5063 if (Diagnose)
5064 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5065 << Param0->getSourceRange() << Param0->getType()
5066 << Context.getLValueReferenceType(
5067 Context.getRecordType(RD).withConst());
5068 return false;
5069 }
5070 break;
5071 }
5072
5073 case CXXMoveConstructor:
5074 case CXXMoveAssignment: {
5075 // Trivial move operations always have non-cv-qualified parameters.
5076 const RValueReferenceType *RT =
5077 Param0->getType()->getAs<RValueReferenceType>();
5078 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5079 if (Diagnose)
5080 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5081 << Param0->getSourceRange() << Param0->getType()
5082 << Context.getRValueReferenceType(Context.getRecordType(RD));
5083 return false;
5084 }
5085 break;
5086 }
5087
5088 case CXXInvalid:
5089 llvm_unreachable("not a special member");
5090 }
5091
5092 // FIXME: We require that the parameter-declaration-clause is equivalent to
5093 // that of an implicit declaration, not just that the declared parameter type
5094 // matches, in order to prevent absuridities like a function simultaneously
5095 // being a trivial copy constructor and a non-trivial default constructor.
5096 // This issue has not yet been assigned a core issue number.
5097 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5098 if (Diagnose)
5099 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5100 diag::note_nontrivial_default_arg)
5101 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5102 return false;
5103 }
5104 if (MD->isVariadic()) {
5105 if (Diagnose)
5106 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5107 return false;
5108 }
5109
5110 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5111 // A copy/move [constructor or assignment operator] is trivial if
5112 // -- the [member] selected to copy/move each direct base class subobject
5113 // is trivial
5114 //
5115 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5116 // A [default constructor or destructor] is trivial if
5117 // -- all the direct base classes have trivial [default constructors or
5118 // destructors]
5119 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5120 BE = RD->bases_end(); BI != BE; ++BI)
5121 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5122 ConstArg ? BI->getType().withConst()
5123 : BI->getType(),
5124 CSM, TSK_BaseClass, Diagnose))
5125 return false;
5126
5127 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5128 // A copy/move [constructor or assignment operator] for a class X is
5129 // trivial if
5130 // -- for each non-static data member of X that is of class type (or array
5131 // thereof), the constructor selected to copy/move that member is
5132 // trivial
5133 //
5134 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5135 // A [default constructor or destructor] is trivial if
5136 // -- for all of the non-static data members of its class that are of class
5137 // type (or array thereof), each such class has a trivial [default
5138 // constructor or destructor]
5139 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5140 return false;
5141
5142 // C++11 [class.dtor]p5:
5143 // A destructor is trivial if [...]
5144 // -- the destructor is not virtual
5145 if (CSM == CXXDestructor && MD->isVirtual()) {
5146 if (Diagnose)
5147 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5148 return false;
5149 }
5150
5151 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5152 // A [special member] for class X is trivial if [...]
5153 // -- class X has no virtual functions and no virtual base classes
5154 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5155 if (!Diagnose)
5156 return false;
5157
5158 if (RD->getNumVBases()) {
5159 // Check for virtual bases. We already know that the corresponding
5160 // member in all bases is trivial, so vbases must all be direct.
5161 CXXBaseSpecifier &BS = *RD->vbases_begin();
5162 assert(BS.isVirtual());
5163 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5164 return false;
5165 }
5166
5167 // Must have a virtual method.
5168 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5169 ME = RD->method_end(); MI != ME; ++MI) {
5170 if (MI->isVirtual()) {
5171 SourceLocation MLoc = MI->getLocStart();
5172 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5173 return false;
5174 }
5175 }
5176
5177 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5178 }
5179
5180 // Looks like it's trivial!
5181 return true;
5182}
5183
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005184/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005185namespace {
5186 struct FindHiddenVirtualMethodData {
5187 Sema *S;
5188 CXXMethodDecl *Method;
5189 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005190 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005191 };
5192}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005193
David Blaikie5f750682012-10-19 00:53:08 +00005194/// \brief Check whether any most overriden method from MD in Methods
5195static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5196 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5197 if (MD->size_overridden_methods() == 0)
5198 return Methods.count(MD->getCanonicalDecl());
5199 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5200 E = MD->end_overridden_methods();
5201 I != E; ++I)
5202 if (CheckMostOverridenMethods(*I, Methods))
5203 return true;
5204 return false;
5205}
5206
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005207/// \brief Member lookup function that determines whether a given C++
5208/// method overloads virtual methods in a base class without overriding any,
5209/// to be used with CXXRecordDecl::lookupInBases().
5210static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5211 CXXBasePath &Path,
5212 void *UserData) {
5213 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5214
5215 FindHiddenVirtualMethodData &Data
5216 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5217
5218 DeclarationName Name = Data.Method->getDeclName();
5219 assert(Name.getNameKind() == DeclarationName::Identifier);
5220
5221 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005222 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005223 for (Path.Decls = BaseRecord->lookup(Name);
5224 Path.Decls.first != Path.Decls.second;
5225 ++Path.Decls.first) {
5226 NamedDecl *D = *Path.Decls.first;
5227 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005228 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005229 foundSameNameMethod = true;
5230 // Interested only in hidden virtual methods.
5231 if (!MD->isVirtual())
5232 continue;
5233 // If the method we are checking overrides a method from its base
5234 // don't warn about the other overloaded methods.
5235 if (!Data.S->IsOverload(Data.Method, MD, false))
5236 return true;
5237 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005238 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005239 overloadedMethods.push_back(MD);
5240 }
5241 }
5242
5243 if (foundSameNameMethod)
5244 Data.OverloadedMethods.append(overloadedMethods.begin(),
5245 overloadedMethods.end());
5246 return foundSameNameMethod;
5247}
5248
David Blaikie5f750682012-10-19 00:53:08 +00005249/// \brief Add the most overriden methods from MD to Methods
5250static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5251 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5252 if (MD->size_overridden_methods() == 0)
5253 Methods.insert(MD->getCanonicalDecl());
5254 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5255 E = MD->end_overridden_methods();
5256 I != E; ++I)
5257 AddMostOverridenMethods(*I, Methods);
5258}
5259
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005260/// \brief See if a method overloads virtual methods in a base class without
5261/// overriding any.
5262void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5263 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005264 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005265 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005266 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005267 return;
5268
5269 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5270 /*bool RecordPaths=*/false,
5271 /*bool DetectVirtual=*/false);
5272 FindHiddenVirtualMethodData Data;
5273 Data.Method = MD;
5274 Data.S = this;
5275
5276 // Keep the base methods that were overriden or introduced in the subclass
5277 // by 'using' in a set. A base method not in this set is hidden.
5278 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
5279 res.first != res.second; ++res.first) {
David Blaikie5f750682012-10-19 00:53:08 +00005280 NamedDecl *ND = *res.first;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005281 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
David Blaikie5f750682012-10-19 00:53:08 +00005282 ND = shad->getTargetDecl();
5283 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5284 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005285 }
5286
5287 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5288 !Data.OverloadedMethods.empty()) {
5289 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5290 << MD << (Data.OverloadedMethods.size() > 1);
5291
5292 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5293 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5294 Diag(overloadedMD->getLocation(),
5295 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5296 }
5297 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005298}
5299
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005300void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005301 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005302 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005303 SourceLocation RBrac,
5304 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005305 if (!TagDecl)
5306 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005307
Douglas Gregor42af25f2009-05-11 19:58:34 +00005308 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005309
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005310 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5311 if (l->getKind() != AttributeList::AT_Visibility)
5312 continue;
5313 l->setInvalid();
5314 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5315 l->getName();
5316 }
5317
David Blaikie77b6de02011-09-22 02:58:26 +00005318 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005319 // strict aliasing violation!
5320 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005321 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005322
Douglas Gregor23c94db2010-07-02 17:43:08 +00005323 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005324 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005325}
5326
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005327/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5328/// special functions, such as the default constructor, copy
5329/// constructor, or destructor, to the given C++ class (C++
5330/// [special]p1). This routine can only be executed just before the
5331/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005332void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005333 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005334 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005335
Richard Smithbc2a35d2012-12-08 08:32:28 +00005336 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005337 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005338
Richard Smithbc2a35d2012-12-08 08:32:28 +00005339 // If the properties or semantics of the copy constructor couldn't be
5340 // determined while the class was being declared, force a declaration
5341 // of it now.
5342 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5343 DeclareImplicitCopyConstructor(ClassDecl);
5344 }
5345
5346 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005347 ++ASTContext::NumImplicitMoveConstructors;
5348
Richard Smithbc2a35d2012-12-08 08:32:28 +00005349 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5350 DeclareImplicitMoveConstructor(ClassDecl);
5351 }
5352
Douglas Gregora376d102010-07-02 21:50:04 +00005353 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5354 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005355
5356 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005357 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005358 // it shows up in the right place in the vtable and that we diagnose
5359 // problems with the implicit exception specification.
5360 if (ClassDecl->isDynamicClass() ||
5361 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005362 DeclareImplicitCopyAssignment(ClassDecl);
5363 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005364
Richard Smith1c931be2012-04-02 18:40:40 +00005365 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005366 ++ASTContext::NumImplicitMoveAssignmentOperators;
5367
5368 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005369 if (ClassDecl->isDynamicClass() ||
5370 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005371 DeclareImplicitMoveAssignment(ClassDecl);
5372 }
5373
Douglas Gregor4923aa22010-07-02 20:37:36 +00005374 if (!ClassDecl->hasUserDeclaredDestructor()) {
5375 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005376
5377 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005378 // have to declare the destructor immediately. This ensures that, e.g., it
5379 // shows up in the right place in the vtable and that we diagnose problems
5380 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005381 if (ClassDecl->isDynamicClass() ||
5382 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005383 DeclareImplicitDestructor(ClassDecl);
5384 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005385}
5386
Francois Pichet8387e2a2011-04-22 22:18:13 +00005387void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5388 if (!D)
5389 return;
5390
5391 int NumParamList = D->getNumTemplateParameterLists();
5392 for (int i = 0; i < NumParamList; i++) {
5393 TemplateParameterList* Params = D->getTemplateParameterList(i);
5394 for (TemplateParameterList::iterator Param = Params->begin(),
5395 ParamEnd = Params->end();
5396 Param != ParamEnd; ++Param) {
5397 NamedDecl *Named = cast<NamedDecl>(*Param);
5398 if (Named->getDeclName()) {
5399 S->AddDecl(Named);
5400 IdResolver.AddDecl(Named);
5401 }
5402 }
5403 }
5404}
5405
John McCalld226f652010-08-21 09:40:31 +00005406void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005407 if (!D)
5408 return;
5409
5410 TemplateParameterList *Params = 0;
5411 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5412 Params = Template->getTemplateParameters();
5413 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5414 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5415 Params = PartialSpec->getTemplateParameters();
5416 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005417 return;
5418
Douglas Gregor6569d682009-05-27 23:11:45 +00005419 for (TemplateParameterList::iterator Param = Params->begin(),
5420 ParamEnd = Params->end();
5421 Param != ParamEnd; ++Param) {
5422 NamedDecl *Named = cast<NamedDecl>(*Param);
5423 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005424 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005425 IdResolver.AddDecl(Named);
5426 }
5427 }
5428}
5429
John McCalld226f652010-08-21 09:40:31 +00005430void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005431 if (!RecordD) return;
5432 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005433 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005434 PushDeclContext(S, Record);
5435}
5436
John McCalld226f652010-08-21 09:40:31 +00005437void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005438 if (!RecordD) return;
5439 PopDeclContext();
5440}
5441
Douglas Gregor72b505b2008-12-16 21:30:33 +00005442/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5443/// parsing a top-level (non-nested) C++ class, and we are now
5444/// parsing those parts of the given Method declaration that could
5445/// not be parsed earlier (C++ [class.mem]p2), such as default
5446/// arguments. This action should enter the scope of the given
5447/// Method declaration as if we had just parsed the qualified method
5448/// name. However, it should not bring the parameters into scope;
5449/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005450void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005451}
5452
5453/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5454/// C++ method declaration. We're (re-)introducing the given
5455/// function parameter into scope for use in parsing later parts of
5456/// the method declaration. For example, we could see an
5457/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005458void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005459 if (!ParamD)
5460 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005461
John McCalld226f652010-08-21 09:40:31 +00005462 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005463
5464 // If this parameter has an unparsed default argument, clear it out
5465 // to make way for the parsed default argument.
5466 if (Param->hasUnparsedDefaultArg())
5467 Param->setDefaultArg(0);
5468
John McCalld226f652010-08-21 09:40:31 +00005469 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005470 if (Param->getDeclName())
5471 IdResolver.AddDecl(Param);
5472}
5473
5474/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5475/// processing the delayed method declaration for Method. The method
5476/// declaration is now considered finished. There may be a separate
5477/// ActOnStartOfFunctionDef action later (not necessarily
5478/// immediately!) for this method, if it was also defined inside the
5479/// class body.
John McCalld226f652010-08-21 09:40:31 +00005480void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005481 if (!MethodD)
5482 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005483
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005484 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005485
John McCalld226f652010-08-21 09:40:31 +00005486 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005487
5488 // Now that we have our default arguments, check the constructor
5489 // again. It could produce additional diagnostics or affect whether
5490 // the class has implicitly-declared destructors, among other
5491 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005492 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5493 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005494
5495 // Check the default arguments, which we may have added.
5496 if (!Method->isInvalidDecl())
5497 CheckCXXDefaultArguments(Method);
5498}
5499
Douglas Gregor42a552f2008-11-05 20:51:48 +00005500/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005501/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005502/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005503/// emit diagnostics and set the invalid bit to true. In any case, the type
5504/// will be updated to reflect a well-formed type for the constructor and
5505/// returned.
5506QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005507 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005508 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005509
5510 // C++ [class.ctor]p3:
5511 // A constructor shall not be virtual (10.3) or static (9.4). A
5512 // constructor can be invoked for a const, volatile or const
5513 // volatile object. A constructor shall not be declared const,
5514 // volatile, or const volatile (9.3.2).
5515 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005516 if (!D.isInvalidType())
5517 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5518 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5519 << SourceRange(D.getIdentifierLoc());
5520 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005521 }
John McCalld931b082010-08-26 03:08:43 +00005522 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005523 if (!D.isInvalidType())
5524 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5525 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5526 << SourceRange(D.getIdentifierLoc());
5527 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005528 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005529 }
Mike Stump1eb44332009-09-09 15:08:12 +00005530
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005531 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005532 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005533 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005534 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5535 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005536 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005537 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5538 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005539 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005540 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5541 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005542 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005543 }
Mike Stump1eb44332009-09-09 15:08:12 +00005544
Douglas Gregorc938c162011-01-26 05:01:58 +00005545 // C++0x [class.ctor]p4:
5546 // A constructor shall not be declared with a ref-qualifier.
5547 if (FTI.hasRefQualifier()) {
5548 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5549 << FTI.RefQualifierIsLValueRef
5550 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5551 D.setInvalidType();
5552 }
5553
Douglas Gregor42a552f2008-11-05 20:51:48 +00005554 // Rebuild the function type "R" without any type qualifiers (in
5555 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005556 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005557 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005558 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5559 return R;
5560
5561 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5562 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005563 EPI.RefQualifier = RQ_None;
5564
Chris Lattner65401802009-04-25 08:28:21 +00005565 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005566 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005567}
5568
Douglas Gregor72b505b2008-12-16 21:30:33 +00005569/// CheckConstructor - Checks a fully-formed constructor for
5570/// well-formedness, issuing any diagnostics required. Returns true if
5571/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005572void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005573 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005574 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5575 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005576 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005577
5578 // C++ [class.copy]p3:
5579 // A declaration of a constructor for a class X is ill-formed if
5580 // its first parameter is of type (optionally cv-qualified) X and
5581 // either there are no other parameters or else all other
5582 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005583 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005584 ((Constructor->getNumParams() == 1) ||
5585 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005586 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5587 Constructor->getTemplateSpecializationKind()
5588 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005589 QualType ParamType = Constructor->getParamDecl(0)->getType();
5590 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5591 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005592 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005593 const char *ConstRef
5594 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5595 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005596 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005597 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005598
5599 // FIXME: Rather that making the constructor invalid, we should endeavor
5600 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005601 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005602 }
5603 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005604}
5605
John McCall15442822010-08-04 01:04:25 +00005606/// CheckDestructor - Checks a fully-formed destructor definition for
5607/// well-formedness, issuing any diagnostics required. Returns true
5608/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005609bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005610 CXXRecordDecl *RD = Destructor->getParent();
5611
5612 if (Destructor->isVirtual()) {
5613 SourceLocation Loc;
5614
5615 if (!Destructor->isImplicit())
5616 Loc = Destructor->getLocation();
5617 else
5618 Loc = RD->getLocation();
5619
5620 // If we have a virtual destructor, look up the deallocation function
5621 FunctionDecl *OperatorDelete = 0;
5622 DeclarationName Name =
5623 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005624 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005625 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005626
Eli Friedman5f2987c2012-02-02 03:46:19 +00005627 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005628
5629 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005630 }
Anders Carlsson37909802009-11-30 21:24:50 +00005631
5632 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005633}
5634
Mike Stump1eb44332009-09-09 15:08:12 +00005635static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005636FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5637 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5638 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005639 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005640}
5641
Douglas Gregor42a552f2008-11-05 20:51:48 +00005642/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5643/// the well-formednes of the destructor declarator @p D with type @p
5644/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005645/// emit diagnostics and set the declarator to invalid. Even if this happens,
5646/// will be updated to reflect a well-formed type for the destructor and
5647/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005648QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005649 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005650 // C++ [class.dtor]p1:
5651 // [...] A typedef-name that names a class is a class-name
5652 // (7.1.3); however, a typedef-name that names a class shall not
5653 // be used as the identifier in the declarator for a destructor
5654 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005655 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005656 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005657 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005658 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005659 else if (const TemplateSpecializationType *TST =
5660 DeclaratorType->getAs<TemplateSpecializationType>())
5661 if (TST->isTypeAlias())
5662 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5663 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005664
5665 // C++ [class.dtor]p2:
5666 // A destructor is used to destroy objects of its class type. A
5667 // destructor takes no parameters, and no return type can be
5668 // specified for it (not even void). The address of a destructor
5669 // shall not be taken. A destructor shall not be static. A
5670 // destructor can be invoked for a const, volatile or const
5671 // volatile object. A destructor shall not be declared const,
5672 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005673 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005674 if (!D.isInvalidType())
5675 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5676 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005677 << SourceRange(D.getIdentifierLoc())
5678 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5679
John McCalld931b082010-08-26 03:08:43 +00005680 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005681 }
Chris Lattner65401802009-04-25 08:28:21 +00005682 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005683 // Destructors don't have return types, but the parser will
5684 // happily parse something like:
5685 //
5686 // class X {
5687 // float ~X();
5688 // };
5689 //
5690 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005691 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5692 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5693 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005694 }
Mike Stump1eb44332009-09-09 15:08:12 +00005695
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005696 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005697 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005698 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005699 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5700 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005701 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005702 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5703 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005704 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005705 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5706 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005707 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005708 }
5709
Douglas Gregorc938c162011-01-26 05:01:58 +00005710 // C++0x [class.dtor]p2:
5711 // A destructor shall not be declared with a ref-qualifier.
5712 if (FTI.hasRefQualifier()) {
5713 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5714 << FTI.RefQualifierIsLValueRef
5715 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5716 D.setInvalidType();
5717 }
5718
Douglas Gregor42a552f2008-11-05 20:51:48 +00005719 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005720 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005721 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5722
5723 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005724 FTI.freeArgs();
5725 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005726 }
5727
Mike Stump1eb44332009-09-09 15:08:12 +00005728 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005729 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005730 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005731 D.setInvalidType();
5732 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005733
5734 // Rebuild the function type "R" without any type qualifiers or
5735 // parameters (in case any of the errors above fired) and with
5736 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005737 // types.
John McCalle23cf432010-12-14 08:05:40 +00005738 if (!D.isInvalidType())
5739 return R;
5740
Douglas Gregord92ec472010-07-01 05:10:53 +00005741 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005742 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5743 EPI.Variadic = false;
5744 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005745 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005746 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005747}
5748
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005749/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5750/// well-formednes of the conversion function declarator @p D with
5751/// type @p R. If there are any errors in the declarator, this routine
5752/// will emit diagnostics and return true. Otherwise, it will return
5753/// false. Either way, the type @p R will be updated to reflect a
5754/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005755void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005756 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005757 // C++ [class.conv.fct]p1:
5758 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005759 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005760 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005761 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005762 if (!D.isInvalidType())
5763 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5764 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5765 << SourceRange(D.getIdentifierLoc());
5766 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005767 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005768 }
John McCalla3f81372010-04-13 00:04:31 +00005769
5770 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5771
Chris Lattner6e475012009-04-25 08:35:12 +00005772 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005773 // Conversion functions don't have return types, but the parser will
5774 // happily parse something like:
5775 //
5776 // class X {
5777 // float operator bool();
5778 // };
5779 //
5780 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005781 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5782 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5783 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005784 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005785 }
5786
John McCalla3f81372010-04-13 00:04:31 +00005787 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5788
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005789 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005790 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005791 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5792
5793 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005794 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005795 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005796 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005797 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005798 D.setInvalidType();
5799 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005800
John McCalla3f81372010-04-13 00:04:31 +00005801 // Diagnose "&operator bool()" and other such nonsense. This
5802 // is actually a gcc extension which we don't support.
5803 if (Proto->getResultType() != ConvType) {
5804 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5805 << Proto->getResultType();
5806 D.setInvalidType();
5807 ConvType = Proto->getResultType();
5808 }
5809
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005810 // C++ [class.conv.fct]p4:
5811 // The conversion-type-id shall not represent a function type nor
5812 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005813 if (ConvType->isArrayType()) {
5814 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5815 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005816 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005817 } else if (ConvType->isFunctionType()) {
5818 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5819 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005820 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005821 }
5822
5823 // Rebuild the function type "R" without any parameters (in case any
5824 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005825 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005826 if (D.isInvalidType())
5827 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005828
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005829 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005830 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005831 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005832 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005833 diag::warn_cxx98_compat_explicit_conversion_functions :
5834 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005835 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005836}
5837
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005838/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5839/// the declaration of the given C++ conversion function. This routine
5840/// is responsible for recording the conversion function in the C++
5841/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005842Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005843 assert(Conversion && "Expected to receive a conversion function declaration");
5844
Douglas Gregor9d350972008-12-12 08:25:50 +00005845 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005846
5847 // Make sure we aren't redeclaring the conversion function.
5848 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005849
5850 // C++ [class.conv.fct]p1:
5851 // [...] A conversion function is never used to convert a
5852 // (possibly cv-qualified) object to the (possibly cv-qualified)
5853 // same object type (or a reference to it), to a (possibly
5854 // cv-qualified) base class of that type (or a reference to it),
5855 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005856 // FIXME: Suppress this warning if the conversion function ends up being a
5857 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005858 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005859 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005860 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005861 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005862 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5863 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005864 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005865 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005866 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5867 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005868 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005869 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005870 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005871 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005872 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005873 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005874 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005875 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005876 }
5877
Douglas Gregore80622f2010-09-29 04:25:11 +00005878 if (FunctionTemplateDecl *ConversionTemplate
5879 = Conversion->getDescribedFunctionTemplate())
5880 return ConversionTemplate;
5881
John McCalld226f652010-08-21 09:40:31 +00005882 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005883}
5884
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005885//===----------------------------------------------------------------------===//
5886// Namespace Handling
5887//===----------------------------------------------------------------------===//
5888
Richard Smithd1a55a62012-10-04 22:13:39 +00005889/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5890/// reopened.
5891static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5892 SourceLocation Loc,
5893 IdentifierInfo *II, bool *IsInline,
5894 NamespaceDecl *PrevNS) {
5895 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00005896
Richard Smithc969e6a2012-10-05 01:46:25 +00005897 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5898 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5899 // inline namespaces, with the intention of bringing names into namespace std.
5900 //
5901 // We support this just well enough to get that case working; this is not
5902 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00005903 if (*IsInline && II && II->getName().startswith("__atomic") &&
5904 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00005905 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00005906 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5907 NS = NS->getPreviousDecl())
5908 NS->setInline(*IsInline);
5909 // Patch up the lookup table for the containing namespace. This isn't really
5910 // correct, but it's good enough for this particular case.
5911 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5912 E = PrevNS->decls_end(); I != E; ++I)
5913 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5914 PrevNS->getParent()->makeDeclVisibleInContext(ND);
5915 return;
5916 }
5917
5918 if (PrevNS->isInline())
5919 // The user probably just forgot the 'inline', so suggest that it
5920 // be added back.
5921 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5922 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5923 else
5924 S.Diag(Loc, diag::err_inline_namespace_mismatch)
5925 << IsInline;
5926
5927 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5928 *IsInline = PrevNS->isInline();
5929}
John McCallea318642010-08-26 09:15:37 +00005930
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005931/// ActOnStartNamespaceDef - This is called at the start of a namespace
5932/// definition.
John McCalld226f652010-08-21 09:40:31 +00005933Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005934 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005935 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005936 SourceLocation IdentLoc,
5937 IdentifierInfo *II,
5938 SourceLocation LBrace,
5939 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005940 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5941 // For anonymous namespace, take the location of the left brace.
5942 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005943 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005944 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005945 bool IsStd = false;
5946 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005947 Scope *DeclRegionScope = NamespcScope->getParent();
5948
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005949 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005950 if (II) {
5951 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005952 // The identifier in an original-namespace-definition shall not
5953 // have been previously defined in the declarative region in
5954 // which the original-namespace-definition appears. The
5955 // identifier in an original-namespace-definition is the name of
5956 // the namespace. Subsequently in that declarative region, it is
5957 // treated as an original-namespace-name.
5958 //
5959 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005960 // look through using directives, just look for any ordinary names.
5961
5962 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005963 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5964 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005965 NamedDecl *PrevDecl = 0;
5966 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005967 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005968 R.first != R.second; ++R.first) {
5969 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5970 PrevDecl = *R.first;
5971 break;
5972 }
5973 }
5974
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005975 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5976
5977 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005978 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00005979 if (IsInline != PrevNS->isInline())
5980 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
5981 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00005982 } else if (PrevDecl) {
5983 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005984 Diag(Loc, diag::err_redefinition_different_kind)
5985 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005986 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005987 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005988 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005989 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005990 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005991 // This is the first "real" definition of the namespace "std", so update
5992 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005993 PrevNS = getStdNamespace();
5994 IsStd = true;
5995 AddToKnown = !IsInline;
5996 } else {
5997 // We've seen this namespace for the first time.
5998 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005999 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006000 } else {
John McCall9aeed322009-10-01 00:25:31 +00006001 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006002
6003 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006004 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006005 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006006 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006007 } else {
6008 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006009 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006010 }
6011
Richard Smithd1a55a62012-10-04 22:13:39 +00006012 if (PrevNS && IsInline != PrevNS->isInline())
6013 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6014 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006015 }
6016
6017 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6018 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006019 if (IsInvalid)
6020 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006021
6022 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006023
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006024 // FIXME: Should we be merging attributes?
6025 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006026 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006027
6028 if (IsStd)
6029 StdNamespace = Namespc;
6030 if (AddToKnown)
6031 KnownNamespaces[Namespc] = false;
6032
6033 if (II) {
6034 PushOnScopeChains(Namespc, DeclRegionScope);
6035 } else {
6036 // Link the anonymous namespace into its parent.
6037 DeclContext *Parent = CurContext->getRedeclContext();
6038 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6039 TU->setAnonymousNamespace(Namespc);
6040 } else {
6041 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006042 }
John McCall9aeed322009-10-01 00:25:31 +00006043
Douglas Gregora4181472010-03-24 00:46:35 +00006044 CurContext->addDecl(Namespc);
6045
John McCall9aeed322009-10-01 00:25:31 +00006046 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6047 // behaves as if it were replaced by
6048 // namespace unique { /* empty body */ }
6049 // using namespace unique;
6050 // namespace unique { namespace-body }
6051 // where all occurrences of 'unique' in a translation unit are
6052 // replaced by the same identifier and this identifier differs
6053 // from all other identifiers in the entire program.
6054
6055 // We just create the namespace with an empty name and then add an
6056 // implicit using declaration, just like the standard suggests.
6057 //
6058 // CodeGen enforces the "universally unique" aspect by giving all
6059 // declarations semantically contained within an anonymous
6060 // namespace internal linkage.
6061
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006062 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006063 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006064 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006065 /* 'using' */ LBrace,
6066 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006067 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006068 /* identifier */ SourceLocation(),
6069 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006070 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006071 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006072 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006073 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006074 }
6075
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006076 ActOnDocumentableDecl(Namespc);
6077
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006078 // Although we could have an invalid decl (i.e. the namespace name is a
6079 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006080 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6081 // for the namespace has the declarations that showed up in that particular
6082 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006083 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006084 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006085}
6086
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006087/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6088/// is a namespace alias, returns the namespace it points to.
6089static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6090 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6091 return AD->getNamespace();
6092 return dyn_cast_or_null<NamespaceDecl>(D);
6093}
6094
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006095/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6096/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006097void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006098 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6099 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006100 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006101 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006102 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006103 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006104}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006105
John McCall384aff82010-08-25 07:42:41 +00006106CXXRecordDecl *Sema::getStdBadAlloc() const {
6107 return cast_or_null<CXXRecordDecl>(
6108 StdBadAlloc.get(Context.getExternalSource()));
6109}
6110
6111NamespaceDecl *Sema::getStdNamespace() const {
6112 return cast_or_null<NamespaceDecl>(
6113 StdNamespace.get(Context.getExternalSource()));
6114}
6115
Douglas Gregor66992202010-06-29 17:53:46 +00006116/// \brief Retrieve the special "std" namespace, which may require us to
6117/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006118NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006119 if (!StdNamespace) {
6120 // The "std" namespace has not yet been defined, so build one implicitly.
6121 StdNamespace = NamespaceDecl::Create(Context,
6122 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006123 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006124 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006125 &PP.getIdentifierTable().get("std"),
6126 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006127 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006128 }
6129
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006130 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006131}
6132
Sebastian Redl395e04d2012-01-17 22:49:33 +00006133bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006134 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006135 "Looking for std::initializer_list outside of C++.");
6136
6137 // We're looking for implicit instantiations of
6138 // template <typename E> class std::initializer_list.
6139
6140 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6141 return false;
6142
Sebastian Redl84760e32012-01-17 22:49:58 +00006143 ClassTemplateDecl *Template = 0;
6144 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006145
Sebastian Redl84760e32012-01-17 22:49:58 +00006146 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006147
Sebastian Redl84760e32012-01-17 22:49:58 +00006148 ClassTemplateSpecializationDecl *Specialization =
6149 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6150 if (!Specialization)
6151 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006152
Sebastian Redl84760e32012-01-17 22:49:58 +00006153 Template = Specialization->getSpecializedTemplate();
6154 Arguments = Specialization->getTemplateArgs().data();
6155 } else if (const TemplateSpecializationType *TST =
6156 Ty->getAs<TemplateSpecializationType>()) {
6157 Template = dyn_cast_or_null<ClassTemplateDecl>(
6158 TST->getTemplateName().getAsTemplateDecl());
6159 Arguments = TST->getArgs();
6160 }
6161 if (!Template)
6162 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006163
6164 if (!StdInitializerList) {
6165 // Haven't recognized std::initializer_list yet, maybe this is it.
6166 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6167 if (TemplateClass->getIdentifier() !=
6168 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006169 !getStdNamespace()->InEnclosingNamespaceSetOf(
6170 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006171 return false;
6172 // This is a template called std::initializer_list, but is it the right
6173 // template?
6174 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006175 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006176 return false;
6177 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6178 return false;
6179
6180 // It's the right template.
6181 StdInitializerList = Template;
6182 }
6183
6184 if (Template != StdInitializerList)
6185 return false;
6186
6187 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006188 if (Element)
6189 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006190 return true;
6191}
6192
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006193static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6194 NamespaceDecl *Std = S.getStdNamespace();
6195 if (!Std) {
6196 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6197 return 0;
6198 }
6199
6200 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6201 Loc, Sema::LookupOrdinaryName);
6202 if (!S.LookupQualifiedName(Result, Std)) {
6203 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6204 return 0;
6205 }
6206 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6207 if (!Template) {
6208 Result.suppressDiagnostics();
6209 // We found something weird. Complain about the first thing we found.
6210 NamedDecl *Found = *Result.begin();
6211 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6212 return 0;
6213 }
6214
6215 // We found some template called std::initializer_list. Now verify that it's
6216 // correct.
6217 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006218 if (Params->getMinRequiredArguments() != 1 ||
6219 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006220 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6221 return 0;
6222 }
6223
6224 return Template;
6225}
6226
6227QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6228 if (!StdInitializerList) {
6229 StdInitializerList = LookupStdInitializerList(*this, Loc);
6230 if (!StdInitializerList)
6231 return QualType();
6232 }
6233
6234 TemplateArgumentListInfo Args(Loc, Loc);
6235 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6236 Context.getTrivialTypeSourceInfo(Element,
6237 Loc)));
6238 return Context.getCanonicalType(
6239 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6240}
6241
Sebastian Redl98d36062012-01-17 22:50:14 +00006242bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6243 // C++ [dcl.init.list]p2:
6244 // A constructor is an initializer-list constructor if its first parameter
6245 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6246 // std::initializer_list<E> for some type E, and either there are no other
6247 // parameters or else all other parameters have default arguments.
6248 if (Ctor->getNumParams() < 1 ||
6249 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6250 return false;
6251
6252 QualType ArgType = Ctor->getParamDecl(0)->getType();
6253 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6254 ArgType = RT->getPointeeType().getUnqualifiedType();
6255
6256 return isStdInitializerList(ArgType, 0);
6257}
6258
Douglas Gregor9172aa62011-03-26 22:25:30 +00006259/// \brief Determine whether a using statement is in a context where it will be
6260/// apply in all contexts.
6261static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6262 switch (CurContext->getDeclKind()) {
6263 case Decl::TranslationUnit:
6264 return true;
6265 case Decl::LinkageSpec:
6266 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6267 default:
6268 return false;
6269 }
6270}
6271
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006272namespace {
6273
6274// Callback to only accept typo corrections that are namespaces.
6275class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6276 public:
6277 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6278 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6279 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6280 }
6281 return false;
6282 }
6283};
6284
6285}
6286
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006287static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6288 CXXScopeSpec &SS,
6289 SourceLocation IdentLoc,
6290 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006291 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006292 R.clear();
6293 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006294 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006295 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006296 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6297 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006298 if (DeclContext *DC = S.computeDeclContext(SS, false))
6299 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6300 << Ident << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +00006301 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6302 CorrectedStr);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006303 else
6304 S.Diag(IdentLoc, diag::err_using_directive_suggest)
6305 << Ident << CorrectedQuotedStr
6306 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006307
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006308 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6309 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006310
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006311 R.addDecl(Corrected.getCorrectionDecl());
6312 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006313 }
6314 return false;
6315}
6316
John McCalld226f652010-08-21 09:40:31 +00006317Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006318 SourceLocation UsingLoc,
6319 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006320 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006321 SourceLocation IdentLoc,
6322 IdentifierInfo *NamespcName,
6323 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006324 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6325 assert(NamespcName && "Invalid NamespcName.");
6326 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006327
6328 // This can only happen along a recovery path.
6329 while (S->getFlags() & Scope::TemplateParamScope)
6330 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006331 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006332
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006333 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006334 NestedNameSpecifier *Qualifier = 0;
6335 if (SS.isSet())
6336 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6337
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006338 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006339 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6340 LookupParsedName(R, S, &SS);
6341 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006342 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006343
Douglas Gregor66992202010-06-29 17:53:46 +00006344 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006345 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006346 // Allow "using namespace std;" or "using namespace ::std;" even if
6347 // "std" hasn't been defined yet, for GCC compatibility.
6348 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6349 NamespcName->isStr("std")) {
6350 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006351 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006352 R.resolveKind();
6353 }
6354 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006355 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006356 }
6357
John McCallf36e02d2009-10-09 21:13:30 +00006358 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006359 NamedDecl *Named = R.getFoundDecl();
6360 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6361 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006362 // C++ [namespace.udir]p1:
6363 // A using-directive specifies that the names in the nominated
6364 // namespace can be used in the scope in which the
6365 // using-directive appears after the using-directive. During
6366 // unqualified name lookup (3.4.1), the names appear as if they
6367 // were declared in the nearest enclosing namespace which
6368 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006369 // namespace. [Note: in this context, "contains" means "contains
6370 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006371
6372 // Find enclosing context containing both using-directive and
6373 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006374 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006375 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6376 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6377 CommonAncestor = CommonAncestor->getParent();
6378
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006379 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006380 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006381 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006382
Douglas Gregor9172aa62011-03-26 22:25:30 +00006383 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006384 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006385 Diag(IdentLoc, diag::warn_using_directive_in_header);
6386 }
6387
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006388 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006389 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006390 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006391 }
6392
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006393 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006394 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006395}
6396
6397void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006398 // If the scope has an associated entity and the using directive is at
6399 // namespace or translation unit scope, add the UsingDirectiveDecl into
6400 // its lookup structure so qualified name lookup can find it.
6401 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6402 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006403 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006404 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006405 // Otherwise, it is at block sope. The using-directives will affect lookup
6406 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006407 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006408}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006409
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006410
John McCalld226f652010-08-21 09:40:31 +00006411Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006412 AccessSpecifier AS,
6413 bool HasUsingKeyword,
6414 SourceLocation UsingLoc,
6415 CXXScopeSpec &SS,
6416 UnqualifiedId &Name,
6417 AttributeList *AttrList,
6418 bool IsTypeName,
6419 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006420 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006421
Douglas Gregor12c118a2009-11-04 16:30:06 +00006422 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006423 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006424 case UnqualifiedId::IK_Identifier:
6425 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006426 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006427 case UnqualifiedId::IK_ConversionFunctionId:
6428 break;
6429
6430 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006431 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006432 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006433 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00006434 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00006435 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6436 // instead once inheriting constructors work.
6437 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00006438 diag::err_using_decl_constructor)
6439 << SS.getRange();
6440
David Blaikie4e4d0842012-03-11 07:00:24 +00006441 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00006442
John McCalld226f652010-08-21 09:40:31 +00006443 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006444
6445 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006446 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006447 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006448 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006449
6450 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006451 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006452 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006453 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006454 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006455
6456 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6457 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006458 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006459 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006460
John McCall60fa3cf2009-12-11 02:10:03 +00006461 // Warn about using declarations.
6462 // TODO: store that the declaration was written without 'using' and
6463 // talk about access decls instead of using decls in the
6464 // diagnostics.
6465 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00006466 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00006467
6468 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006469 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006470 }
6471
Douglas Gregor56c04582010-12-16 00:46:58 +00006472 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6473 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6474 return 0;
6475
John McCall9488ea12009-11-17 05:59:44 +00006476 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006477 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006478 /* IsInstantiation */ false,
6479 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006480 if (UD)
6481 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006482
John McCalld226f652010-08-21 09:40:31 +00006483 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006484}
6485
Douglas Gregor09acc982010-07-07 23:08:52 +00006486/// \brief Determine whether a using declaration considers the given
6487/// declarations as "equivalent", e.g., if they are redeclarations of
6488/// the same entity or are both typedefs of the same type.
6489static bool
6490IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6491 bool &SuppressRedeclaration) {
6492 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6493 SuppressRedeclaration = false;
6494 return true;
6495 }
6496
Richard Smith162e1c12011-04-15 14:24:37 +00006497 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6498 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006499 SuppressRedeclaration = true;
6500 return Context.hasSameType(TD1->getUnderlyingType(),
6501 TD2->getUnderlyingType());
6502 }
6503
6504 return false;
6505}
6506
6507
John McCall9f54ad42009-12-10 09:41:52 +00006508/// Determines whether to create a using shadow decl for a particular
6509/// decl, given the set of decls existing prior to this using lookup.
6510bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6511 const LookupResult &Previous) {
6512 // Diagnose finding a decl which is not from a base class of the
6513 // current class. We do this now because there are cases where this
6514 // function will silently decide not to build a shadow decl, which
6515 // will pre-empt further diagnostics.
6516 //
6517 // We don't need to do this in C++0x because we do the check once on
6518 // the qualifier.
6519 //
6520 // FIXME: diagnose the following if we care enough:
6521 // struct A { int foo; };
6522 // struct B : A { using A::foo; };
6523 // template <class T> struct C : A {};
6524 // template <class T> struct D : C<T> { using B::foo; } // <---
6525 // This is invalid (during instantiation) in C++03 because B::foo
6526 // resolves to the using decl in B, which is not a base class of D<T>.
6527 // We can't diagnose it immediately because C<T> is an unknown
6528 // specialization. The UsingShadowDecl in D<T> then points directly
6529 // to A::foo, which will look well-formed when we instantiate.
6530 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00006531 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006532 DeclContext *OrigDC = Orig->getDeclContext();
6533
6534 // Handle enums and anonymous structs.
6535 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6536 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6537 while (OrigRec->isAnonymousStructOrUnion())
6538 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6539
6540 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6541 if (OrigDC == CurContext) {
6542 Diag(Using->getLocation(),
6543 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006544 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006545 Diag(Orig->getLocation(), diag::note_using_decl_target);
6546 return true;
6547 }
6548
Douglas Gregordc355712011-02-25 00:36:19 +00006549 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006550 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006551 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006552 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006553 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006554 Diag(Orig->getLocation(), diag::note_using_decl_target);
6555 return true;
6556 }
6557 }
6558
6559 if (Previous.empty()) return false;
6560
6561 NamedDecl *Target = Orig;
6562 if (isa<UsingShadowDecl>(Target))
6563 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6564
John McCalld7533ec2009-12-11 02:33:26 +00006565 // If the target happens to be one of the previous declarations, we
6566 // don't have a conflict.
6567 //
6568 // FIXME: but we might be increasing its access, in which case we
6569 // should redeclare it.
6570 NamedDecl *NonTag = 0, *Tag = 0;
6571 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6572 I != E; ++I) {
6573 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006574 bool Result;
6575 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6576 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006577
6578 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6579 }
6580
John McCall9f54ad42009-12-10 09:41:52 +00006581 if (Target->isFunctionOrFunctionTemplate()) {
6582 FunctionDecl *FD;
6583 if (isa<FunctionTemplateDecl>(Target))
6584 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6585 else
6586 FD = cast<FunctionDecl>(Target);
6587
6588 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006589 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006590 case Ovl_Overload:
6591 return false;
6592
6593 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006594 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006595 break;
6596
6597 // We found a decl with the exact signature.
6598 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006599 // If we're in a record, we want to hide the target, so we
6600 // return true (without a diagnostic) to tell the caller not to
6601 // build a shadow decl.
6602 if (CurContext->isRecord())
6603 return true;
6604
6605 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006606 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006607 break;
6608 }
6609
6610 Diag(Target->getLocation(), diag::note_using_decl_target);
6611 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6612 return true;
6613 }
6614
6615 // Target is not a function.
6616
John McCall9f54ad42009-12-10 09:41:52 +00006617 if (isa<TagDecl>(Target)) {
6618 // No conflict between a tag and a non-tag.
6619 if (!Tag) return false;
6620
John McCall41ce66f2009-12-10 19:51:03 +00006621 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006622 Diag(Target->getLocation(), diag::note_using_decl_target);
6623 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6624 return true;
6625 }
6626
6627 // No conflict between a tag and a non-tag.
6628 if (!NonTag) return false;
6629
John McCall41ce66f2009-12-10 19:51:03 +00006630 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006631 Diag(Target->getLocation(), diag::note_using_decl_target);
6632 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6633 return true;
6634}
6635
John McCall9488ea12009-11-17 05:59:44 +00006636/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006637UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006638 UsingDecl *UD,
6639 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006640
6641 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006642 NamedDecl *Target = Orig;
6643 if (isa<UsingShadowDecl>(Target)) {
6644 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6645 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006646 }
6647
6648 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006649 = UsingShadowDecl::Create(Context, CurContext,
6650 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006651 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006652
6653 Shadow->setAccess(UD->getAccess());
6654 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6655 Shadow->setInvalidDecl();
6656
John McCall9488ea12009-11-17 05:59:44 +00006657 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006658 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006659 else
John McCall604e7f12009-12-08 07:46:18 +00006660 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006661
John McCall604e7f12009-12-08 07:46:18 +00006662
John McCall9f54ad42009-12-10 09:41:52 +00006663 return Shadow;
6664}
John McCall604e7f12009-12-08 07:46:18 +00006665
John McCall9f54ad42009-12-10 09:41:52 +00006666/// Hides a using shadow declaration. This is required by the current
6667/// using-decl implementation when a resolvable using declaration in a
6668/// class is followed by a declaration which would hide or override
6669/// one or more of the using decl's targets; for example:
6670///
6671/// struct Base { void foo(int); };
6672/// struct Derived : Base {
6673/// using Base::foo;
6674/// void foo(int);
6675/// };
6676///
6677/// The governing language is C++03 [namespace.udecl]p12:
6678///
6679/// When a using-declaration brings names from a base class into a
6680/// derived class scope, member functions in the derived class
6681/// override and/or hide member functions with the same name and
6682/// parameter types in a base class (rather than conflicting).
6683///
6684/// There are two ways to implement this:
6685/// (1) optimistically create shadow decls when they're not hidden
6686/// by existing declarations, or
6687/// (2) don't create any shadow decls (or at least don't make them
6688/// visible) until we've fully parsed/instantiated the class.
6689/// The problem with (1) is that we might have to retroactively remove
6690/// a shadow decl, which requires several O(n) operations because the
6691/// decl structures are (very reasonably) not designed for removal.
6692/// (2) avoids this but is very fiddly and phase-dependent.
6693void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006694 if (Shadow->getDeclName().getNameKind() ==
6695 DeclarationName::CXXConversionFunctionName)
6696 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6697
John McCall9f54ad42009-12-10 09:41:52 +00006698 // Remove it from the DeclContext...
6699 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006700
John McCall9f54ad42009-12-10 09:41:52 +00006701 // ...and the scope, if applicable...
6702 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006703 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006704 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006705 }
6706
John McCall9f54ad42009-12-10 09:41:52 +00006707 // ...and the using decl.
6708 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6709
6710 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006711 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006712}
6713
John McCall7ba107a2009-11-18 02:36:19 +00006714/// Builds a using declaration.
6715///
6716/// \param IsInstantiation - Whether this call arises from an
6717/// instantiation of an unresolved using declaration. We treat
6718/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006719NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6720 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006721 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006722 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006723 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006724 bool IsInstantiation,
6725 bool IsTypeName,
6726 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006727 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006728 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006729 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006730
Anders Carlsson550b14b2009-08-28 05:49:21 +00006731 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006732
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006733 if (SS.isEmpty()) {
6734 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006735 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006736 }
Mike Stump1eb44332009-09-09 15:08:12 +00006737
John McCall9f54ad42009-12-10 09:41:52 +00006738 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006739 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006740 ForRedeclaration);
6741 Previous.setHideTags(false);
6742 if (S) {
6743 LookupName(Previous, S);
6744
6745 // It is really dumb that we have to do this.
6746 LookupResult::Filter F = Previous.makeFilter();
6747 while (F.hasNext()) {
6748 NamedDecl *D = F.next();
6749 if (!isDeclInScope(D, CurContext, S))
6750 F.erase();
6751 }
6752 F.done();
6753 } else {
6754 assert(IsInstantiation && "no scope in non-instantiation");
6755 assert(CurContext->isRecord() && "scope not record in instantiation");
6756 LookupQualifiedName(Previous, CurContext);
6757 }
6758
John McCall9f54ad42009-12-10 09:41:52 +00006759 // Check for invalid redeclarations.
6760 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6761 return 0;
6762
6763 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006764 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6765 return 0;
6766
John McCallaf8e6ed2009-11-12 03:15:40 +00006767 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006768 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006769 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006770 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006771 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006772 // FIXME: not all declaration name kinds are legal here
6773 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6774 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006775 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006776 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006777 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006778 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6779 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006780 }
John McCalled976492009-12-04 22:46:56 +00006781 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006782 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6783 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006784 }
John McCalled976492009-12-04 22:46:56 +00006785 D->setAccess(AS);
6786 CurContext->addDecl(D);
6787
6788 if (!LookupContext) return D;
6789 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006790
John McCall77bb1aa2010-05-01 00:40:08 +00006791 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006792 UD->setInvalidDecl();
6793 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006794 }
6795
Richard Smithc5a89a12012-04-02 01:30:27 +00006796 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006797 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006798 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006799 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006800 return UD;
6801 }
6802
6803 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006804
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006805 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006806
John McCall604e7f12009-12-08 07:46:18 +00006807 // Unlike most lookups, we don't always want to hide tag
6808 // declarations: tag names are visible through the using declaration
6809 // even if hidden by ordinary names, *except* in a dependent context
6810 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006811 if (!IsInstantiation)
6812 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006813
John McCallb9abd8722012-04-07 03:04:20 +00006814 // For the purposes of this lookup, we have a base object type
6815 // equal to that of the current context.
6816 if (CurContext->isRecord()) {
6817 R.setBaseObjectType(
6818 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6819 }
6820
John McCalla24dc2e2009-11-17 02:14:36 +00006821 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006822
John McCallf36e02d2009-10-09 21:13:30 +00006823 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006824 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006825 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006826 UD->setInvalidDecl();
6827 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006828 }
6829
John McCalled976492009-12-04 22:46:56 +00006830 if (R.isAmbiguous()) {
6831 UD->setInvalidDecl();
6832 return UD;
6833 }
Mike Stump1eb44332009-09-09 15:08:12 +00006834
John McCall7ba107a2009-11-18 02:36:19 +00006835 if (IsTypeName) {
6836 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006837 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006838 Diag(IdentLoc, diag::err_using_typename_non_type);
6839 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6840 Diag((*I)->getUnderlyingDecl()->getLocation(),
6841 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006842 UD->setInvalidDecl();
6843 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006844 }
6845 } else {
6846 // If we asked for a non-typename and we got a type, error out,
6847 // but only if this is an instantiation of an unresolved using
6848 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006849 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006850 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6851 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006852 UD->setInvalidDecl();
6853 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006854 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006855 }
6856
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006857 // C++0x N2914 [namespace.udecl]p6:
6858 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006859 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006860 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6861 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006862 UD->setInvalidDecl();
6863 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006864 }
Mike Stump1eb44332009-09-09 15:08:12 +00006865
John McCall9f54ad42009-12-10 09:41:52 +00006866 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6867 if (!CheckUsingShadowDecl(UD, *I, Previous))
6868 BuildUsingShadowDecl(S, UD, *I);
6869 }
John McCall9488ea12009-11-17 05:59:44 +00006870
6871 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006872}
6873
Sebastian Redlf677ea32011-02-05 19:23:19 +00006874/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006875bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6876 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006877
Douglas Gregordc355712011-02-25 00:36:19 +00006878 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006879 assert(SourceType &&
6880 "Using decl naming constructor doesn't have type in scope spec.");
6881 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6882
6883 // Check whether the named type is a direct base class.
6884 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6885 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6886 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6887 BaseIt != BaseE; ++BaseIt) {
6888 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6889 if (CanonicalSourceType == BaseType)
6890 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006891 if (BaseIt->getType()->isDependentType())
6892 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006893 }
6894
6895 if (BaseIt == BaseE) {
6896 // Did not find SourceType in the bases.
6897 Diag(UD->getUsingLocation(),
6898 diag::err_using_decl_constructor_not_in_direct_base)
6899 << UD->getNameInfo().getSourceRange()
6900 << QualType(SourceType, 0) << TargetClass;
6901 return true;
6902 }
6903
Richard Smithc5a89a12012-04-02 01:30:27 +00006904 if (!CurContext->isDependentContext())
6905 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006906
6907 return false;
6908}
6909
John McCall9f54ad42009-12-10 09:41:52 +00006910/// Checks that the given using declaration is not an invalid
6911/// redeclaration. Note that this is checking only for the using decl
6912/// itself, not for any ill-formedness among the UsingShadowDecls.
6913bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6914 bool isTypeName,
6915 const CXXScopeSpec &SS,
6916 SourceLocation NameLoc,
6917 const LookupResult &Prev) {
6918 // C++03 [namespace.udecl]p8:
6919 // C++0x [namespace.udecl]p10:
6920 // A using-declaration is a declaration and can therefore be used
6921 // repeatedly where (and only where) multiple declarations are
6922 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006923 //
John McCall8a726212010-11-29 18:01:58 +00006924 // That's in non-member contexts.
6925 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006926 return false;
6927
6928 NestedNameSpecifier *Qual
6929 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6930
6931 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6932 NamedDecl *D = *I;
6933
6934 bool DTypename;
6935 NestedNameSpecifier *DQual;
6936 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6937 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006938 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006939 } else if (UnresolvedUsingValueDecl *UD
6940 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6941 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006942 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006943 } else if (UnresolvedUsingTypenameDecl *UD
6944 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6945 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006946 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006947 } else continue;
6948
6949 // using decls differ if one says 'typename' and the other doesn't.
6950 // FIXME: non-dependent using decls?
6951 if (isTypeName != DTypename) continue;
6952
6953 // using decls differ if they name different scopes (but note that
6954 // template instantiation can cause this check to trigger when it
6955 // didn't before instantiation).
6956 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6957 Context.getCanonicalNestedNameSpecifier(DQual))
6958 continue;
6959
6960 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006961 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006962 return true;
6963 }
6964
6965 return false;
6966}
6967
John McCall604e7f12009-12-08 07:46:18 +00006968
John McCalled976492009-12-04 22:46:56 +00006969/// Checks that the given nested-name qualifier used in a using decl
6970/// in the current context is appropriately related to the current
6971/// scope. If an error is found, diagnoses it and returns true.
6972bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6973 const CXXScopeSpec &SS,
6974 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006975 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006976
John McCall604e7f12009-12-08 07:46:18 +00006977 if (!CurContext->isRecord()) {
6978 // C++03 [namespace.udecl]p3:
6979 // C++0x [namespace.udecl]p8:
6980 // A using-declaration for a class member shall be a member-declaration.
6981
6982 // If we weren't able to compute a valid scope, it must be a
6983 // dependent class scope.
6984 if (!NamedContext || NamedContext->isRecord()) {
6985 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6986 << SS.getRange();
6987 return true;
6988 }
6989
6990 // Otherwise, everything is known to be fine.
6991 return false;
6992 }
6993
6994 // The current scope is a record.
6995
6996 // If the named context is dependent, we can't decide much.
6997 if (!NamedContext) {
6998 // FIXME: in C++0x, we can diagnose if we can prove that the
6999 // nested-name-specifier does not refer to a base class, which is
7000 // still possible in some cases.
7001
7002 // Otherwise we have to conservatively report that things might be
7003 // okay.
7004 return false;
7005 }
7006
7007 if (!NamedContext->isRecord()) {
7008 // Ideally this would point at the last name in the specifier,
7009 // but we don't have that level of source info.
7010 Diag(SS.getRange().getBegin(),
7011 diag::err_using_decl_nested_name_specifier_is_not_class)
7012 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7013 return true;
7014 }
7015
Douglas Gregor6fb07292010-12-21 07:41:49 +00007016 if (!NamedContext->isDependentContext() &&
7017 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7018 return true;
7019
David Blaikie4e4d0842012-03-11 07:00:24 +00007020 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00007021 // C++0x [namespace.udecl]p3:
7022 // In a using-declaration used as a member-declaration, the
7023 // nested-name-specifier shall name a base class of the class
7024 // being defined.
7025
7026 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7027 cast<CXXRecordDecl>(NamedContext))) {
7028 if (CurContext == NamedContext) {
7029 Diag(NameLoc,
7030 diag::err_using_decl_nested_name_specifier_is_current_class)
7031 << SS.getRange();
7032 return true;
7033 }
7034
7035 Diag(SS.getRange().getBegin(),
7036 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7037 << (NestedNameSpecifier*) SS.getScopeRep()
7038 << cast<CXXRecordDecl>(CurContext)
7039 << SS.getRange();
7040 return true;
7041 }
7042
7043 return false;
7044 }
7045
7046 // C++03 [namespace.udecl]p4:
7047 // A using-declaration used as a member-declaration shall refer
7048 // to a member of a base class of the class being defined [etc.].
7049
7050 // Salient point: SS doesn't have to name a base class as long as
7051 // lookup only finds members from base classes. Therefore we can
7052 // diagnose here only if we can prove that that can't happen,
7053 // i.e. if the class hierarchies provably don't intersect.
7054
7055 // TODO: it would be nice if "definitely valid" results were cached
7056 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7057 // need to be repeated.
7058
7059 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007060 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007061
7062 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7063 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7064 Data->Bases.insert(Base);
7065 return true;
7066 }
7067
7068 bool hasDependentBases(const CXXRecordDecl *Class) {
7069 return !Class->forallBases(collect, this);
7070 }
7071
7072 /// Returns true if the base is dependent or is one of the
7073 /// accumulated base classes.
7074 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7075 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7076 return !Data->Bases.count(Base);
7077 }
7078
7079 bool mightShareBases(const CXXRecordDecl *Class) {
7080 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7081 }
7082 };
7083
7084 UserData Data;
7085
7086 // Returns false if we find a dependent base.
7087 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7088 return false;
7089
7090 // Returns false if the class has a dependent base or if it or one
7091 // of its bases is present in the base set of the current context.
7092 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7093 return false;
7094
7095 Diag(SS.getRange().getBegin(),
7096 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7097 << (NestedNameSpecifier*) SS.getScopeRep()
7098 << cast<CXXRecordDecl>(CurContext)
7099 << SS.getRange();
7100
7101 return true;
John McCalled976492009-12-04 22:46:56 +00007102}
7103
Richard Smith162e1c12011-04-15 14:24:37 +00007104Decl *Sema::ActOnAliasDeclaration(Scope *S,
7105 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007106 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007107 SourceLocation UsingLoc,
7108 UnqualifiedId &Name,
7109 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007110 // Skip up to the relevant declaration scope.
7111 while (S->getFlags() & Scope::TemplateParamScope)
7112 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007113 assert((S->getFlags() & Scope::DeclScope) &&
7114 "got alias-declaration outside of declaration scope");
7115
7116 if (Type.isInvalid())
7117 return 0;
7118
7119 bool Invalid = false;
7120 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7121 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007122 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007123
7124 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7125 return 0;
7126
7127 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007128 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007129 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007130 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7131 TInfo->getTypeLoc().getBeginLoc());
7132 }
Richard Smith162e1c12011-04-15 14:24:37 +00007133
7134 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7135 LookupName(Previous, S);
7136
7137 // Warn about shadowing the name of a template parameter.
7138 if (Previous.isSingleResult() &&
7139 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007140 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007141 Previous.clear();
7142 }
7143
7144 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7145 "name in alias declaration must be an identifier");
7146 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7147 Name.StartLocation,
7148 Name.Identifier, TInfo);
7149
7150 NewTD->setAccess(AS);
7151
7152 if (Invalid)
7153 NewTD->setInvalidDecl();
7154
Richard Smith3e4c6c42011-05-05 21:57:07 +00007155 CheckTypedefForVariablyModifiedType(S, NewTD);
7156 Invalid |= NewTD->isInvalidDecl();
7157
Richard Smith162e1c12011-04-15 14:24:37 +00007158 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007159
7160 NamedDecl *NewND;
7161 if (TemplateParamLists.size()) {
7162 TypeAliasTemplateDecl *OldDecl = 0;
7163 TemplateParameterList *OldTemplateParams = 0;
7164
7165 if (TemplateParamLists.size() != 1) {
7166 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007167 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7168 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007169 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007170 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007171
7172 // Only consider previous declarations in the same scope.
7173 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7174 /*ExplicitInstantiationOrSpecialization*/false);
7175 if (!Previous.empty()) {
7176 Redeclaration = true;
7177
7178 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7179 if (!OldDecl && !Invalid) {
7180 Diag(UsingLoc, diag::err_redefinition_different_kind)
7181 << Name.Identifier;
7182
7183 NamedDecl *OldD = Previous.getRepresentativeDecl();
7184 if (OldD->getLocation().isValid())
7185 Diag(OldD->getLocation(), diag::note_previous_definition);
7186
7187 Invalid = true;
7188 }
7189
7190 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7191 if (TemplateParameterListsAreEqual(TemplateParams,
7192 OldDecl->getTemplateParameters(),
7193 /*Complain=*/true,
7194 TPL_TemplateMatch))
7195 OldTemplateParams = OldDecl->getTemplateParameters();
7196 else
7197 Invalid = true;
7198
7199 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7200 if (!Invalid &&
7201 !Context.hasSameType(OldTD->getUnderlyingType(),
7202 NewTD->getUnderlyingType())) {
7203 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7204 // but we can't reasonably accept it.
7205 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7206 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7207 if (OldTD->getLocation().isValid())
7208 Diag(OldTD->getLocation(), diag::note_previous_definition);
7209 Invalid = true;
7210 }
7211 }
7212 }
7213
7214 // Merge any previous default template arguments into our parameters,
7215 // and check the parameter list.
7216 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7217 TPC_TypeAliasTemplate))
7218 return 0;
7219
7220 TypeAliasTemplateDecl *NewDecl =
7221 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7222 Name.Identifier, TemplateParams,
7223 NewTD);
7224
7225 NewDecl->setAccess(AS);
7226
7227 if (Invalid)
7228 NewDecl->setInvalidDecl();
7229 else if (OldDecl)
7230 NewDecl->setPreviousDeclaration(OldDecl);
7231
7232 NewND = NewDecl;
7233 } else {
7234 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7235 NewND = NewTD;
7236 }
Richard Smith162e1c12011-04-15 14:24:37 +00007237
7238 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007239 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007240
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007241 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007242 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007243}
7244
John McCalld226f652010-08-21 09:40:31 +00007245Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007246 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007247 SourceLocation AliasLoc,
7248 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007249 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007250 SourceLocation IdentLoc,
7251 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007252
Anders Carlsson81c85c42009-03-28 23:53:49 +00007253 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007254 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7255 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007256
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007257 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007258 NamedDecl *PrevDecl
7259 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7260 ForRedeclaration);
7261 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7262 PrevDecl = 0;
7263
7264 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007265 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007266 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007267 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007268 // FIXME: At some point, we'll want to create the (redundant)
7269 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007270 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007271 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007272 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007273 }
Mike Stump1eb44332009-09-09 15:08:12 +00007274
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007275 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7276 diag::err_redefinition_different_kind;
7277 Diag(AliasLoc, DiagID) << Alias;
7278 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007279 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007280 }
7281
John McCalla24dc2e2009-11-17 02:14:36 +00007282 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007283 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007284
John McCallf36e02d2009-10-09 21:13:30 +00007285 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007286 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007287 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007288 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007289 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007290 }
Mike Stump1eb44332009-09-09 15:08:12 +00007291
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007292 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007293 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007294 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007295 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007296
John McCall3dbd3d52010-02-16 06:53:13 +00007297 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007298 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007299}
7300
Sean Hunt001cad92011-05-10 00:49:42 +00007301Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007302Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7303 CXXMethodDecl *MD) {
7304 CXXRecordDecl *ClassDecl = MD->getParent();
7305
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007306 // C++ [except.spec]p14:
7307 // An implicitly declared special member function (Clause 12) shall have an
7308 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007309 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007310 if (ClassDecl->isInvalidDecl())
7311 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007312
Sebastian Redl60618fa2011-03-12 11:50:43 +00007313 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007314 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7315 BEnd = ClassDecl->bases_end();
7316 B != BEnd; ++B) {
7317 if (B->isVirtual()) // Handled below.
7318 continue;
7319
Douglas Gregor18274032010-07-03 00:47:00 +00007320 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7321 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007322 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7323 // If this is a deleted function, add it anyway. This might be conformant
7324 // with the standard. This might not. I'm not sure. It might not matter.
7325 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007326 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007327 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007328 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007329
7330 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007331 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7332 BEnd = ClassDecl->vbases_end();
7333 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007334 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7335 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007336 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7337 // If this is a deleted function, add it anyway. This might be conformant
7338 // with the standard. This might not. I'm not sure. It might not matter.
7339 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007340 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007341 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007342 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007343
7344 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007345 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7346 FEnd = ClassDecl->field_end();
7347 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007348 if (F->hasInClassInitializer()) {
7349 if (Expr *E = F->getInClassInitializer())
7350 ExceptSpec.CalledExpr(E);
7351 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007352 // DR1351:
7353 // If the brace-or-equal-initializer of a non-static data member
7354 // invokes a defaulted default constructor of its class or of an
7355 // enclosing class in a potentially evaluated subexpression, the
7356 // program is ill-formed.
7357 //
7358 // This resolution is unworkable: the exception specification of the
7359 // default constructor can be needed in an unevaluated context, in
7360 // particular, in the operand of a noexcept-expression, and we can be
7361 // unable to compute an exception specification for an enclosed class.
7362 //
7363 // We do not allow an in-class initializer to require the evaluation
7364 // of the exception specification for any in-class initializer whose
7365 // definition is not lexically complete.
7366 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007367 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007368 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007369 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7370 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7371 // If this is a deleted function, add it anyway. This might be conformant
7372 // with the standard. This might not. I'm not sure. It might not matter.
7373 // In particular, the problem is that this function never gets called. It
7374 // might just be ill-formed because this function attempts to refer to
7375 // a deleted function here.
7376 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007377 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007378 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007379 }
John McCalle23cf432010-12-14 08:05:40 +00007380
Sean Hunt001cad92011-05-10 00:49:42 +00007381 return ExceptSpec;
7382}
7383
Richard Smithafb49182012-11-29 01:34:07 +00007384namespace {
7385/// RAII object to register a special member as being currently declared.
7386struct DeclaringSpecialMember {
7387 Sema &S;
7388 Sema::SpecialMemberDecl D;
7389 bool WasAlreadyBeingDeclared;
7390
7391 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7392 : S(S), D(RD, CSM) {
7393 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7394 if (WasAlreadyBeingDeclared)
7395 // This almost never happens, but if it does, ensure that our cache
7396 // doesn't contain a stale result.
7397 S.SpecialMemberCache.clear();
7398
7399 // FIXME: Register a note to be produced if we encounter an error while
7400 // declaring the special member.
7401 }
7402 ~DeclaringSpecialMember() {
7403 if (!WasAlreadyBeingDeclared)
7404 S.SpecialMembersBeingDeclared.erase(D);
7405 }
7406
7407 /// \brief Are we already trying to declare this special member?
7408 bool isAlreadyBeingDeclared() const {
7409 return WasAlreadyBeingDeclared;
7410 }
7411};
7412}
7413
Sean Hunt001cad92011-05-10 00:49:42 +00007414CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7415 CXXRecordDecl *ClassDecl) {
7416 // C++ [class.ctor]p5:
7417 // A default constructor for a class X is a constructor of class X
7418 // that can be called without an argument. If there is no
7419 // user-declared constructor for class X, a default constructor is
7420 // implicitly declared. An implicitly-declared default constructor
7421 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007422 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007423 "Should not build implicit default constructor!");
7424
Richard Smithafb49182012-11-29 01:34:07 +00007425 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7426 if (DSM.isAlreadyBeingDeclared())
7427 return 0;
7428
Richard Smith7756afa2012-06-10 05:43:50 +00007429 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7430 CXXDefaultConstructor,
7431 false);
7432
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007433 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007434 CanQualType ClassType
7435 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007436 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007437 DeclarationName Name
7438 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007439 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007440 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007441 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007442 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007443 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007444 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007445 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007446 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007447
7448 // Build an exception specification pointing back at this constructor.
7449 FunctionProtoType::ExtProtoInfo EPI;
7450 EPI.ExceptionSpecType = EST_Unevaluated;
7451 EPI.ExceptionSpecDecl = DefaultCon;
7452 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7453
Richard Smithbc2a35d2012-12-08 08:32:28 +00007454 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7455 // constructors is easy to compute.
7456 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7457
7458 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7459 DefaultCon->setDeletedAsWritten();
7460
Douglas Gregor18274032010-07-03 00:47:00 +00007461 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007462 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007463
Douglas Gregor23c94db2010-07-02 17:43:08 +00007464 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007465 PushOnScopeChains(DefaultCon, S, false);
7466 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007467
Douglas Gregor32df23e2010-07-01 22:02:46 +00007468 return DefaultCon;
7469}
7470
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007471void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7472 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007473 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007474 !Constructor->doesThisDeclarationHaveABody() &&
7475 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007476 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007477
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007478 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007479 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007480
Eli Friedman9a14db32012-10-18 20:14:08 +00007481 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007482 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007483 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007484 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007485 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007486 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007487 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007488 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007489 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007490
7491 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007492 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007493
7494 Constructor->setUsed();
7495 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007496
7497 if (ASTMutationListener *L = getASTMutationListener()) {
7498 L->CompletedImplicitDefinition(Constructor);
7499 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007500}
7501
Richard Smith7a614d82011-06-11 17:19:42 +00007502void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7503 if (!D) return;
7504 AdjustDeclIfTemplate(D);
7505
7506 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
Richard Smith7a614d82011-06-11 17:19:42 +00007507
Richard Smithb9d0b762012-07-27 04:22:15 +00007508 if (!ClassDecl->isDependentType())
Richard Smithac713512012-12-08 02:53:02 +00007509 CheckExplicitlyDefaultedAndDeletedMethods(ClassDecl);
7510
7511 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
7512 // function that is not a constructor declares that member function to be
7513 // const. [...] The class of which that function is a member shall be
7514 // a literal type.
7515 //
7516 // If the class has virtual bases, any constexpr members will already have
7517 // been diagnosed by the checks performed on the member declaration, so
7518 // suppress this (less useful) diagnostic.
7519 //
7520 // We delay this until we know whether an explicitly-defaulted (or deleted)
7521 // destructor for the class is trivial.
7522 if (LangOpts.CPlusPlus0x && !ClassDecl->isDependentType() &&
7523 !ClassDecl->isLiteral() && !ClassDecl->getNumVBases()) {
7524 for (CXXRecordDecl::method_iterator M = ClassDecl->method_begin(),
7525 MEnd = ClassDecl->method_end();
7526 M != MEnd; ++M) {
7527 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
7528 switch (ClassDecl->getTemplateSpecializationKind()) {
7529 case TSK_ImplicitInstantiation:
7530 case TSK_ExplicitInstantiationDeclaration:
7531 case TSK_ExplicitInstantiationDefinition:
7532 // If a template instantiates to a non-literal type, but its members
7533 // instantiate to constexpr functions, the template is technically
7534 // ill-formed, but we allow it for sanity.
7535 continue;
7536
7537 case TSK_Undeclared:
7538 case TSK_ExplicitSpecialization:
7539 RequireLiteralType(M->getLocation(), Context.getRecordType(ClassDecl),
7540 diag::err_constexpr_method_non_literal);
7541 break;
7542 }
7543
7544 // Only produce one error per class.
7545 break;
7546 }
7547 }
7548 }
Richard Smith7a614d82011-06-11 17:19:42 +00007549}
7550
Sebastian Redlf677ea32011-02-05 19:23:19 +00007551void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7552 // We start with an initial pass over the base classes to collect those that
7553 // inherit constructors from. If there are none, we can forgo all further
7554 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007555 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007556 BasesVector BasesToInheritFrom;
7557 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7558 BaseE = ClassDecl->bases_end();
7559 BaseIt != BaseE; ++BaseIt) {
7560 if (BaseIt->getInheritConstructors()) {
7561 QualType Base = BaseIt->getType();
7562 if (Base->isDependentType()) {
7563 // If we inherit constructors from anything that is dependent, just
7564 // abort processing altogether. We'll get another chance for the
7565 // instantiations.
7566 return;
7567 }
7568 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7569 }
7570 }
7571 if (BasesToInheritFrom.empty())
7572 return;
7573
7574 // Now collect the constructors that we already have in the current class.
7575 // Those take precedence over inherited constructors.
7576 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7577 // unless there is a user-declared constructor with the same signature in
7578 // the class where the using-declaration appears.
7579 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7580 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7581 CtorE = ClassDecl->ctor_end();
7582 CtorIt != CtorE; ++CtorIt) {
7583 ExistingConstructors.insert(
7584 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7585 }
7586
Sebastian Redlf677ea32011-02-05 19:23:19 +00007587 DeclarationName CreatedCtorName =
7588 Context.DeclarationNames.getCXXConstructorName(
7589 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7590
7591 // Now comes the true work.
7592 // First, we keep a map from constructor types to the base that introduced
7593 // them. Needed for finding conflicting constructors. We also keep the
7594 // actually inserted declarations in there, for pretty diagnostics.
7595 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7596 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7597 ConstructorToSourceMap InheritedConstructors;
7598 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7599 BaseE = BasesToInheritFrom.end();
7600 BaseIt != BaseE; ++BaseIt) {
7601 const RecordType *Base = *BaseIt;
7602 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7603 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7604 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7605 CtorE = BaseDecl->ctor_end();
7606 CtorIt != CtorE; ++CtorIt) {
7607 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00007608 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00007609 DeclarationName Name =
7610 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00007611 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7612 LookupQualifiedName(Result, CurContext);
7613 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007614 SourceLocation UsingLoc = UD ? UD->getLocation() :
7615 ClassDecl->getLocation();
7616
7617 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7618 // from the class X named in the using-declaration consists of actual
7619 // constructors and notional constructors that result from the
7620 // transformation of defaulted parameters as follows:
7621 // - all non-template default constructors of X, and
7622 // - for each non-template constructor of X that has at least one
7623 // parameter with a default argument, the set of constructors that
7624 // results from omitting any ellipsis parameter specification and
7625 // successively omitting parameters with a default argument from the
7626 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00007627 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007628 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7629 const FunctionProtoType *BaseCtorType =
7630 BaseCtor->getType()->getAs<FunctionProtoType>();
7631
7632 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7633 maxParams = BaseCtor->getNumParams();
7634 params <= maxParams; ++params) {
7635 // Skip default constructors. They're never inherited.
7636 if (params == 0)
7637 continue;
7638 // Skip copy and move constructors for the same reason.
7639 if (CanBeCopyOrMove && params == 1)
7640 continue;
7641
7642 // Build up a function type for this particular constructor.
7643 // FIXME: The working paper does not consider that the exception spec
7644 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007645 // source. This code doesn't yet, either. When it does, this code will
7646 // need to be delayed until after exception specifications and in-class
7647 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007648 const Type *NewCtorType;
7649 if (params == maxParams)
7650 NewCtorType = BaseCtorType;
7651 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007652 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007653 for (unsigned i = 0; i < params; ++i) {
7654 Args.push_back(BaseCtorType->getArgType(i));
7655 }
7656 FunctionProtoType::ExtProtoInfo ExtInfo =
7657 BaseCtorType->getExtProtoInfo();
7658 ExtInfo.Variadic = false;
7659 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7660 Args.data(), params, ExtInfo)
7661 .getTypePtr();
7662 }
7663 const Type *CanonicalNewCtorType =
7664 Context.getCanonicalType(NewCtorType);
7665
7666 // Now that we have the type, first check if the class already has a
7667 // constructor with this signature.
7668 if (ExistingConstructors.count(CanonicalNewCtorType))
7669 continue;
7670
7671 // Then we check if we have already declared an inherited constructor
7672 // with this signature.
7673 std::pair<ConstructorToSourceMap::iterator, bool> result =
7674 InheritedConstructors.insert(std::make_pair(
7675 CanonicalNewCtorType,
7676 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7677 if (!result.second) {
7678 // Already in the map. If it came from a different class, that's an
7679 // error. Not if it's from the same.
7680 CanQualType PreviousBase = result.first->second.first;
7681 if (CanonicalBase != PreviousBase) {
7682 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7683 const CXXConstructorDecl *PrevBaseCtor =
7684 PrevCtor->getInheritedConstructor();
7685 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7686
7687 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7688 Diag(BaseCtor->getLocation(),
7689 diag::note_using_decl_constructor_conflict_current_ctor);
7690 Diag(PrevBaseCtor->getLocation(),
7691 diag::note_using_decl_constructor_conflict_previous_ctor);
7692 Diag(PrevCtor->getLocation(),
7693 diag::note_using_decl_constructor_conflict_previous_using);
7694 }
7695 continue;
7696 }
7697
7698 // OK, we're there, now add the constructor.
7699 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007700 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007701 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7702 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007703 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7704 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007705 /*ImplicitlyDeclared=*/true,
7706 // FIXME: Due to a defect in the standard, we treat inherited
7707 // constructors as constexpr even if that makes them ill-formed.
7708 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007709 NewCtor->setAccess(BaseCtor->getAccess());
7710
7711 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007712 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007713 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007714 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7715 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007716 /*IdentifierInfo=*/0,
7717 BaseCtorType->getArgType(i),
7718 /*TInfo=*/0, SC_None,
7719 SC_None, /*DefaultArg=*/0));
7720 }
David Blaikie4278c652011-09-21 18:16:56 +00007721 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007722 NewCtor->setInheritedConstructor(BaseCtor);
7723
Sebastian Redlf677ea32011-02-05 19:23:19 +00007724 ClassDecl->addDecl(NewCtor);
7725 result.first->second.second = NewCtor;
7726 }
7727 }
7728 }
7729}
7730
Sean Huntcb45a0f2011-05-12 22:46:25 +00007731Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007732Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7733 CXXRecordDecl *ClassDecl = MD->getParent();
7734
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007735 // C++ [except.spec]p14:
7736 // An implicitly declared special member function (Clause 12) shall have
7737 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007738 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007739 if (ClassDecl->isInvalidDecl())
7740 return ExceptSpec;
7741
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007742 // Direct base-class destructors.
7743 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7744 BEnd = ClassDecl->bases_end();
7745 B != BEnd; ++B) {
7746 if (B->isVirtual()) // Handled below.
7747 continue;
7748
7749 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007750 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007751 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007752 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007753
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007754 // Virtual base-class destructors.
7755 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7756 BEnd = ClassDecl->vbases_end();
7757 B != BEnd; ++B) {
7758 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007759 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007760 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007761 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007762
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007763 // Field destructors.
7764 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7765 FEnd = ClassDecl->field_end();
7766 F != FEnd; ++F) {
7767 if (const RecordType *RecordTy
7768 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007769 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007770 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007771 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007772
Sean Huntcb45a0f2011-05-12 22:46:25 +00007773 return ExceptSpec;
7774}
7775
7776CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7777 // C++ [class.dtor]p2:
7778 // If a class has no user-declared destructor, a destructor is
7779 // declared implicitly. An implicitly-declared destructor is an
7780 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00007781 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00007782
Richard Smithafb49182012-11-29 01:34:07 +00007783 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7784 if (DSM.isAlreadyBeingDeclared())
7785 return 0;
7786
Douglas Gregor4923aa22010-07-02 20:37:36 +00007787 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007788 CanQualType ClassType
7789 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007790 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007791 DeclarationName Name
7792 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007793 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007794 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007795 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7796 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007797 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007798 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007799 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007800 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007801
7802 // Build an exception specification pointing back at this destructor.
7803 FunctionProtoType::ExtProtoInfo EPI;
7804 EPI.ExceptionSpecType = EST_Unevaluated;
7805 EPI.ExceptionSpecDecl = Destructor;
7806 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7807
Richard Smithbc2a35d2012-12-08 08:32:28 +00007808 AddOverriddenMethods(ClassDecl, Destructor);
7809
7810 // We don't need to use SpecialMemberIsTrivial here; triviality for
7811 // destructors is easy to compute.
7812 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7813
7814 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7815 Destructor->setDeletedAsWritten();
7816
Douglas Gregor4923aa22010-07-02 20:37:36 +00007817 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007818 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007819
Douglas Gregor4923aa22010-07-02 20:37:36 +00007820 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007821 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007822 PushOnScopeChains(Destructor, S, false);
7823 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007824
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007825 return Destructor;
7826}
7827
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007828void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007829 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007830 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007831 !Destructor->doesThisDeclarationHaveABody() &&
7832 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007833 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007834 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007835 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007836
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007837 if (Destructor->isInvalidDecl())
7838 return;
7839
Eli Friedman9a14db32012-10-18 20:14:08 +00007840 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007841
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007842 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007843 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7844 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007845
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007846 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007847 Diag(CurrentLocation, diag::note_member_synthesized_at)
7848 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7849
7850 Destructor->setInvalidDecl();
7851 return;
7852 }
7853
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007854 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007855 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007856 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007857 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007858 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007859
7860 if (ASTMutationListener *L = getASTMutationListener()) {
7861 L->CompletedImplicitDefinition(Destructor);
7862 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007863}
7864
Richard Smitha4156b82012-04-21 18:42:51 +00007865/// \brief Perform any semantic analysis which needs to be delayed until all
7866/// pending class member declarations have been parsed.
7867void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007868 // Perform any deferred checking of exception specifications for virtual
7869 // destructors.
7870 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7871 i != e; ++i) {
7872 const CXXDestructorDecl *Dtor =
7873 DelayedDestructorExceptionSpecChecks[i].first;
7874 assert(!Dtor->getParent()->isDependentType() &&
7875 "Should not ever add destructors of templates into the list.");
7876 CheckOverridingFunctionExceptionSpec(Dtor,
7877 DelayedDestructorExceptionSpecChecks[i].second);
7878 }
7879 DelayedDestructorExceptionSpecChecks.clear();
7880}
7881
Richard Smithb9d0b762012-07-27 04:22:15 +00007882void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7883 CXXDestructorDecl *Destructor) {
7884 assert(getLangOpts().CPlusPlus0x &&
7885 "adjusting dtor exception specs was introduced in c++11");
7886
Sebastian Redl0ee33912011-05-19 05:13:44 +00007887 // C++11 [class.dtor]p3:
7888 // A declaration of a destructor that does not have an exception-
7889 // specification is implicitly considered to have the same exception-
7890 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007891 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007892 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007893 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007894 return;
7895
Chandler Carruth3f224b22011-09-20 04:55:26 +00007896 // Replace the destructor's type, building off the existing one. Fortunately,
7897 // the only thing of interest in the destructor type is its extended info.
7898 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007899 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7900 EPI.ExceptionSpecType = EST_Unevaluated;
7901 EPI.ExceptionSpecDecl = Destructor;
7902 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007903
Sebastian Redl0ee33912011-05-19 05:13:44 +00007904 // FIXME: If the destructor has a body that could throw, and the newly created
7905 // spec doesn't allow exceptions, we should emit a warning, because this
7906 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007907 // However, we don't have a body or an exception specification yet, so it
7908 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007909}
7910
Richard Smith8c889532012-11-14 00:50:40 +00007911/// When generating a defaulted copy or move assignment operator, if a field
7912/// should be copied with __builtin_memcpy rather than via explicit assignments,
7913/// do so. This optimization only applies for arrays of scalars, and for arrays
7914/// of class type where the selected copy/move-assignment operator is trivial.
7915static StmtResult
7916buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7917 Expr *To, Expr *From) {
7918 // Compute the size of the memory buffer to be copied.
7919 QualType SizeType = S.Context.getSizeType();
7920 llvm::APInt Size(S.Context.getTypeSize(SizeType),
7921 S.Context.getTypeSizeInChars(T).getQuantity());
7922
7923 // Take the address of the field references for "from" and "to". We
7924 // directly construct UnaryOperators here because semantic analysis
7925 // does not permit us to take the address of an xvalue.
7926 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7927 S.Context.getPointerType(From->getType()),
7928 VK_RValue, OK_Ordinary, Loc);
7929 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7930 S.Context.getPointerType(To->getType()),
7931 VK_RValue, OK_Ordinary, Loc);
7932
7933 const Type *E = T->getBaseElementTypeUnsafe();
7934 bool NeedsCollectableMemCpy =
7935 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7936
7937 // Create a reference to the __builtin_objc_memmove_collectable function
7938 StringRef MemCpyName = NeedsCollectableMemCpy ?
7939 "__builtin_objc_memmove_collectable" :
7940 "__builtin_memcpy";
7941 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7942 Sema::LookupOrdinaryName);
7943 S.LookupName(R, S.TUScope, true);
7944
7945 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7946 if (!MemCpy)
7947 // Something went horribly wrong earlier, and we will have complained
7948 // about it.
7949 return StmtError();
7950
7951 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7952 VK_RValue, Loc, 0);
7953 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7954
7955 Expr *CallArgs[] = {
7956 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7957 };
7958 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7959 Loc, CallArgs, Loc);
7960
7961 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7962 return S.Owned(Call.takeAs<Stmt>());
7963}
7964
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007965/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007966/// \c To.
7967///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007968/// This routine is used to copy/move the members of a class with an
7969/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007970/// copied are arrays, this routine builds for loops to copy them.
7971///
7972/// \param S The Sema object used for type-checking.
7973///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007974/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007975///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007976/// \param T The type of the expressions being copied/moved. Both expressions
7977/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007978///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007979/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007980///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007981/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007982///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007983/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007984/// Otherwise, it's a non-static member subobject.
7985///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007986/// \param Copying Whether we're copying or moving.
7987///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007988/// \param Depth Internal parameter recording the depth of the recursion.
7989///
Richard Smith8c889532012-11-14 00:50:40 +00007990/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
7991/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00007992static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00007993buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
7994 Expr *To, Expr *From,
7995 bool CopyingBaseSubobject, bool Copying,
7996 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00007997 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007998 // Each subobject is assigned in the manner appropriate to its type:
7999 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008000 // - if the subobject is of class type, as if by a call to operator= with
8001 // the subobject as the object expression and the corresponding
8002 // subobject of x as a single function argument (as if by explicit
8003 // qualification; that is, ignoring any possible virtual overriding
8004 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008005 //
8006 // C++03 [class.copy]p13:
8007 // - if the subobject is of class type, the copy assignment operator for
8008 // the class is used (as if by explicit qualification; that is,
8009 // ignoring any possible virtual overriding functions in more derived
8010 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008011 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8012 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008013
Douglas Gregor06a9f362010-05-01 20:49:11 +00008014 // Look for operator=.
8015 DeclarationName Name
8016 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8017 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8018 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008019
Richard Smith044c8aa2012-11-13 00:54:12 +00008020 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8021 // operator.
8022 if (!S.getLangOpts().CPlusPlus0x) {
8023 LookupResult::Filter F = OpLookup.makeFilter();
8024 while (F.hasNext()) {
8025 NamedDecl *D = F.next();
8026 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8027 if (Method->isCopyAssignmentOperator() ||
8028 (!Copying && Method->isMoveAssignmentOperator()))
8029 continue;
8030
8031 F.erase();
8032 }
8033 F.done();
John McCallb0207482010-03-16 06:11:48 +00008034 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008035
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008036 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008037 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008038 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008039 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008040 // ambiguities), we need to cast "this" to that subobject type; to
8041 // ensure that we don't go through the virtual call mechanism, we need
8042 // to qualify the operator= name with the base class (see below). However,
8043 // this means that if the base class has a protected copy assignment
8044 // operator, the protected member access check will fail. So, we
8045 // rewrite "protected" access to "public" access in this case, since we
8046 // know by construction that we're calling from a derived class.
8047 if (CopyingBaseSubobject) {
8048 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8049 L != LEnd; ++L) {
8050 if (L.getAccess() == AS_protected)
8051 L.setAccess(AS_public);
8052 }
8053 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008054
Douglas Gregor06a9f362010-05-01 20:49:11 +00008055 // Create the nested-name-specifier that will be used to qualify the
8056 // reference to operator=; this is required to suppress the virtual
8057 // call mechanism.
8058 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008059 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008060 SS.MakeTrivial(S.Context,
8061 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008062 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008063 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008064
Douglas Gregor06a9f362010-05-01 20:49:11 +00008065 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008066 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008067 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008068 /*TemplateKWLoc=*/SourceLocation(),
8069 /*FirstQualifierInScope=*/0,
8070 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008071 /*TemplateArgs=*/0,
8072 /*SuppressQualifierCheck=*/true);
8073 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008074 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008075
Douglas Gregor06a9f362010-05-01 20:49:11 +00008076 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008077
Richard Smith044c8aa2012-11-13 00:54:12 +00008078 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008079 OpEqualRef.takeAs<Expr>(),
8080 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008081 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008082 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008083
Richard Smith8c889532012-11-14 00:50:40 +00008084 // If we built a call to a trivial 'operator=' while copying an array,
8085 // bail out. We'll replace the whole shebang with a memcpy.
8086 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8087 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8088 return StmtResult((Stmt*)0);
8089
Richard Smith044c8aa2012-11-13 00:54:12 +00008090 // Convert to an expression-statement, and clean up any produced
8091 // temporaries.
8092 return S.ActOnExprStmt(S.MakeFullExpr(Call.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008093 }
John McCallb0207482010-03-16 06:11:48 +00008094
Richard Smith044c8aa2012-11-13 00:54:12 +00008095 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008096 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008097 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008098 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008099 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008100 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008101 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008102 return S.ActOnExprStmt(S.MakeFullExpr(Assignment.take(), Loc));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008103 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008104
8105 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008106 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008107
Douglas Gregor06a9f362010-05-01 20:49:11 +00008108 // Construct a loop over the array bounds, e.g.,
8109 //
8110 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8111 //
8112 // that will copy each of the array elements.
8113 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008114
Douglas Gregor06a9f362010-05-01 20:49:11 +00008115 // Create the iteration variable.
8116 IdentifierInfo *IterationVarName = 0;
8117 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008118 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008119 llvm::raw_svector_ostream OS(Str);
8120 OS << "__i" << Depth;
8121 IterationVarName = &S.Context.Idents.get(OS.str());
8122 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008123 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008124 IterationVarName, SizeType,
8125 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00008126 SC_None, SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008127
Douglas Gregor06a9f362010-05-01 20:49:11 +00008128 // Initialize the iteration variable to zero.
8129 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008130 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008131
8132 // Create a reference to the iteration variable; we'll use this several
8133 // times throughout.
8134 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008135 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008136 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008137 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8138 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8139
Douglas Gregor06a9f362010-05-01 20:49:11 +00008140 // Create the DeclStmt that holds the iteration variable.
8141 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008142
Douglas Gregor06a9f362010-05-01 20:49:11 +00008143 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008144 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008145 IterationVarRefRVal,
8146 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008147 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008148 IterationVarRefRVal,
8149 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008150 if (!Copying) // Cast to rvalue
8151 From = CastForMoving(S, From);
8152
8153 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008154 StmtResult Copy =
8155 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8156 To, From, CopyingBaseSubobject,
8157 Copying, Depth + 1);
8158 // Bail out if copying fails or if we determined that we should use memcpy.
8159 if (Copy.isInvalid() || !Copy.get())
8160 return Copy;
8161
8162 // Create the comparison against the array bound.
8163 llvm::APInt Upper
8164 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8165 Expr *Comparison
8166 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8167 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8168 BO_NE, S.Context.BoolTy,
8169 VK_RValue, OK_Ordinary, Loc, false);
8170
8171 // Create the pre-increment of the iteration variable.
8172 Expr *Increment
8173 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8174 VK_LValue, OK_Ordinary, Loc);
8175
Douglas Gregor06a9f362010-05-01 20:49:11 +00008176 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008177 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008178 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00008179 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008180 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008181}
8182
Richard Smith8c889532012-11-14 00:50:40 +00008183static StmtResult
8184buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8185 Expr *To, Expr *From,
8186 bool CopyingBaseSubobject, bool Copying) {
8187 // Maybe we should use a memcpy?
8188 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8189 T.isTriviallyCopyableType(S.Context))
8190 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8191
8192 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8193 CopyingBaseSubobject,
8194 Copying, 0));
8195
8196 // If we ended up picking a trivial assignment operator for an array of a
8197 // non-trivially-copyable class type, just emit a memcpy.
8198 if (!Result.isInvalid() && !Result.get())
8199 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8200
8201 return Result;
8202}
8203
Richard Smithb9d0b762012-07-27 04:22:15 +00008204Sema::ImplicitExceptionSpecification
8205Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8206 CXXRecordDecl *ClassDecl = MD->getParent();
8207
8208 ImplicitExceptionSpecification ExceptSpec(*this);
8209 if (ClassDecl->isInvalidDecl())
8210 return ExceptSpec;
8211
8212 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8213 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8214 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8215
Douglas Gregorb87786f2010-07-01 17:48:08 +00008216 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008217 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008218 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008219
8220 // It is unspecified whether or not an implicit copy assignment operator
8221 // attempts to deduplicate calls to assignment operators of virtual bases are
8222 // made. As such, this exception specification is effectively unspecified.
8223 // Based on a similar decision made for constness in C++0x, we're erring on
8224 // the side of assuming such calls to be made regardless of whether they
8225 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008226 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8227 BaseEnd = ClassDecl->bases_end();
8228 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008229 if (Base->isVirtual())
8230 continue;
8231
Douglas Gregora376d102010-07-02 21:50:04 +00008232 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008233 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008234 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8235 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008236 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008237 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008238
8239 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8240 BaseEnd = ClassDecl->vbases_end();
8241 Base != BaseEnd; ++Base) {
8242 CXXRecordDecl *BaseClassDecl
8243 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8244 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8245 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008246 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008247 }
8248
Douglas Gregorb87786f2010-07-01 17:48:08 +00008249 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8250 FieldEnd = ClassDecl->field_end();
8251 Field != FieldEnd;
8252 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008253 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008254 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8255 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008256 LookupCopyingAssignment(FieldClassDecl,
8257 ArgQuals | FieldType.getCVRQualifiers(),
8258 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008259 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008260 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008261 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008262
Richard Smithb9d0b762012-07-27 04:22:15 +00008263 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008264}
8265
8266CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8267 // Note: The following rules are largely analoguous to the copy
8268 // constructor rules. Note that virtual bases are not taken into account
8269 // for determining the argument type of the operator. Note also that
8270 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008271 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008272
Richard Smithafb49182012-11-29 01:34:07 +00008273 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8274 if (DSM.isAlreadyBeingDeclared())
8275 return 0;
8276
Sean Hunt30de05c2011-05-14 05:23:20 +00008277 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8278 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithacf796b2012-11-28 06:23:12 +00008279 if (ClassDecl->implicitCopyAssignmentHasConstParam())
Sean Hunt30de05c2011-05-14 05:23:20 +00008280 ArgType = ArgType.withConst();
8281 ArgType = Context.getLValueReferenceType(ArgType);
8282
Douglas Gregord3c35902010-07-01 16:36:15 +00008283 // An implicitly-declared copy assignment operator is an inline public
8284 // member of its class.
8285 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008286 SourceLocation ClassLoc = ClassDecl->getLocation();
8287 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00008288 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008289 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00008290 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00008291 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00008292 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00008293 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008294 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008295 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008296 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008297
8298 // Build an exception specification pointing back at this member.
8299 FunctionProtoType::ExtProtoInfo EPI;
8300 EPI.ExceptionSpecType = EST_Unevaluated;
8301 EPI.ExceptionSpecDecl = CopyAssignment;
8302 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8303
Douglas Gregord3c35902010-07-01 16:36:15 +00008304 // Add the parameter to the operator.
8305 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008306 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008307 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008308 SC_None,
8309 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008310 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008311
Richard Smithbc2a35d2012-12-08 08:32:28 +00008312 AddOverriddenMethods(ClassDecl, CopyAssignment);
8313
8314 CopyAssignment->setTrivial(
8315 ClassDecl->needsOverloadResolutionForCopyAssignment()
8316 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8317 : ClassDecl->hasTrivialCopyAssignment());
8318
Nico Weberafcc96a2012-01-23 03:19:29 +00008319 // C++0x [class.copy]p19:
8320 // .... If the class definition does not explicitly declare a copy
8321 // assignment operator, there is no user-declared move constructor, and
8322 // there is no user-declared move assignment operator, a copy assignment
8323 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008324 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00008325 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008326
Richard Smithbc2a35d2012-12-08 08:32:28 +00008327 // Note that we have added this copy-assignment operator.
8328 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8329
8330 if (Scope *S = getScopeForContext(ClassDecl))
8331 PushOnScopeChains(CopyAssignment, S, false);
8332 ClassDecl->addDecl(CopyAssignment);
8333
Douglas Gregord3c35902010-07-01 16:36:15 +00008334 return CopyAssignment;
8335}
8336
Douglas Gregor06a9f362010-05-01 20:49:11 +00008337void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8338 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008339 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008340 CopyAssignOperator->isOverloadedOperator() &&
8341 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008342 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8343 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008344 "DefineImplicitCopyAssignment called for wrong function");
8345
8346 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8347
8348 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8349 CopyAssignOperator->setInvalidDecl();
8350 return;
8351 }
8352
8353 CopyAssignOperator->setUsed();
8354
Eli Friedman9a14db32012-10-18 20:14:08 +00008355 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008356 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008357
8358 // C++0x [class.copy]p30:
8359 // The implicitly-defined or explicitly-defaulted copy assignment operator
8360 // for a non-union class X performs memberwise copy assignment of its
8361 // subobjects. The direct base classes of X are assigned first, in the
8362 // order of their declaration in the base-specifier-list, and then the
8363 // immediate non-static data members of X are assigned, in the order in
8364 // which they were declared in the class definition.
8365
8366 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008367 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008368
8369 // The parameter for the "other" object, which we are copying from.
8370 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8371 Qualifiers OtherQuals = Other->getType().getQualifiers();
8372 QualType OtherRefType = Other->getType();
8373 if (const LValueReferenceType *OtherRef
8374 = OtherRefType->getAs<LValueReferenceType>()) {
8375 OtherRefType = OtherRef->getPointeeType();
8376 OtherQuals = OtherRefType.getQualifiers();
8377 }
8378
8379 // Our location for everything implicitly-generated.
8380 SourceLocation Loc = CopyAssignOperator->getLocation();
8381
8382 // Construct a reference to the "other" object. We'll be using this
8383 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00008384 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008385 assert(OtherRef && "Reference to parameter cannot fail!");
8386
8387 // Construct the "this" pointer. We'll be using this throughout the generated
8388 // ASTs.
8389 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8390 assert(This && "Reference to this cannot fail!");
8391
8392 // Assign base classes.
8393 bool Invalid = false;
8394 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8395 E = ClassDecl->bases_end(); Base != E; ++Base) {
8396 // Form the assignment:
8397 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8398 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008399 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008400 Invalid = true;
8401 continue;
8402 }
8403
John McCallf871d0c2010-08-07 06:22:56 +00008404 CXXCastPath BasePath;
8405 BasePath.push_back(Base);
8406
Douglas Gregor06a9f362010-05-01 20:49:11 +00008407 // Construct the "from" expression, which is an implicit cast to the
8408 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00008409 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00008410 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8411 CK_UncheckedDerivedToBase,
8412 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008413
8414 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00008415 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008416
8417 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00008418 To = ImpCastExprToType(To.take(),
8419 Context.getCVRQualifiedType(BaseType,
8420 CopyAssignOperator->getTypeQualifiers()),
8421 CK_UncheckedDerivedToBase,
8422 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008423
8424 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00008425 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00008426 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008427 /*CopyingBaseSubobject=*/true,
8428 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008429 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008430 Diag(CurrentLocation, diag::note_member_synthesized_at)
8431 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8432 CopyAssignOperator->setInvalidDecl();
8433 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008434 }
8435
8436 // Success! Record the copy.
8437 Statements.push_back(Copy.takeAs<Expr>());
8438 }
8439
Douglas Gregor06a9f362010-05-01 20:49:11 +00008440 // Assign non-static members.
8441 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8442 FieldEnd = ClassDecl->field_end();
8443 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008444 if (Field->isUnnamedBitfield())
8445 continue;
8446
Douglas Gregor06a9f362010-05-01 20:49:11 +00008447 // Check for members of reference type; we can't copy those.
8448 if (Field->getType()->isReferenceType()) {
8449 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8450 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8451 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008452 Diag(CurrentLocation, diag::note_member_synthesized_at)
8453 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008454 Invalid = true;
8455 continue;
8456 }
8457
8458 // Check for members of const-qualified, non-class type.
8459 QualType BaseType = Context.getBaseElementType(Field->getType());
8460 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8461 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8462 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8463 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008464 Diag(CurrentLocation, diag::note_member_synthesized_at)
8465 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008466 Invalid = true;
8467 continue;
8468 }
John McCallb77115d2011-06-17 00:18:42 +00008469
8470 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008471 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8472 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008473
8474 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008475 if (FieldType->isIncompleteArrayType()) {
8476 assert(ClassDecl->hasFlexibleArrayMember() &&
8477 "Incomplete array type is not valid");
8478 continue;
8479 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008480
8481 // Build references to the field in the object we're copying from and to.
8482 CXXScopeSpec SS; // Intentionally empty
8483 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8484 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008485 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008486 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008487 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008488 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008489 SS, SourceLocation(), 0,
8490 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008491 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008492 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008493 SS, SourceLocation(), 0,
8494 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008495 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8496 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00008497
Douglas Gregor06a9f362010-05-01 20:49:11 +00008498 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008499 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008500 To.get(), From.get(),
8501 /*CopyingBaseSubobject=*/false,
8502 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008503 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008504 Diag(CurrentLocation, diag::note_member_synthesized_at)
8505 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8506 CopyAssignOperator->setInvalidDecl();
8507 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008508 }
8509
8510 // Success! Record the copy.
8511 Statements.push_back(Copy.takeAs<Stmt>());
8512 }
8513
8514 if (!Invalid) {
8515 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008516 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008517
John McCall60d7b3a2010-08-24 06:29:42 +00008518 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008519 if (Return.isInvalid())
8520 Invalid = true;
8521 else {
8522 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008523
8524 if (Trap.hasErrorOccurred()) {
8525 Diag(CurrentLocation, diag::note_member_synthesized_at)
8526 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8527 Invalid = true;
8528 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008529 }
8530 }
8531
8532 if (Invalid) {
8533 CopyAssignOperator->setInvalidDecl();
8534 return;
8535 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008536
8537 StmtResult Body;
8538 {
8539 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008540 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008541 /*isStmtExpr=*/false);
8542 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8543 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008544 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008545
8546 if (ASTMutationListener *L = getASTMutationListener()) {
8547 L->CompletedImplicitDefinition(CopyAssignOperator);
8548 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008549}
8550
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008551Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008552Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8553 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008554
Richard Smithb9d0b762012-07-27 04:22:15 +00008555 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008556 if (ClassDecl->isInvalidDecl())
8557 return ExceptSpec;
8558
8559 // C++0x [except.spec]p14:
8560 // An implicitly declared special member function (Clause 12) shall have an
8561 // exception-specification. [...]
8562
8563 // It is unspecified whether or not an implicit move assignment operator
8564 // attempts to deduplicate calls to assignment operators of virtual bases are
8565 // made. As such, this exception specification is effectively unspecified.
8566 // Based on a similar decision made for constness in C++0x, we're erring on
8567 // the side of assuming such calls to be made regardless of whether they
8568 // actually happen.
8569 // Note that a move constructor is not implicitly declared when there are
8570 // virtual bases, but it can still be user-declared and explicitly defaulted.
8571 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8572 BaseEnd = ClassDecl->bases_end();
8573 Base != BaseEnd; ++Base) {
8574 if (Base->isVirtual())
8575 continue;
8576
8577 CXXRecordDecl *BaseClassDecl
8578 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8579 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008580 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008581 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008582 }
8583
8584 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8585 BaseEnd = ClassDecl->vbases_end();
8586 Base != BaseEnd; ++Base) {
8587 CXXRecordDecl *BaseClassDecl
8588 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8589 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008590 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008591 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008592 }
8593
8594 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8595 FieldEnd = ClassDecl->field_end();
8596 Field != FieldEnd;
8597 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008598 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008599 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008600 if (CXXMethodDecl *MoveAssign =
8601 LookupMovingAssignment(FieldClassDecl,
8602 FieldType.getCVRQualifiers(),
8603 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008604 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008605 }
8606 }
8607
8608 return ExceptSpec;
8609}
8610
Richard Smith1c931be2012-04-02 18:40:40 +00008611/// Determine whether the class type has any direct or indirect virtual base
8612/// classes which have a non-trivial move assignment operator.
8613static bool
8614hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8615 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8616 BaseEnd = ClassDecl->vbases_end();
8617 Base != BaseEnd; ++Base) {
8618 CXXRecordDecl *BaseClass =
8619 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8620
8621 // Try to declare the move assignment. If it would be deleted, then the
8622 // class does not have a non-trivial move assignment.
8623 if (BaseClass->needsImplicitMoveAssignment())
8624 S.DeclareImplicitMoveAssignment(BaseClass);
8625
Richard Smith426391c2012-11-16 00:53:38 +00008626 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00008627 return true;
8628 }
8629
8630 return false;
8631}
8632
8633/// Determine whether the given type either has a move constructor or is
8634/// trivially copyable.
8635static bool
8636hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8637 Type = S.Context.getBaseElementType(Type);
8638
8639 // FIXME: Technically, non-trivially-copyable non-class types, such as
8640 // reference types, are supposed to return false here, but that appears
8641 // to be a standard defect.
8642 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00008643 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00008644 return true;
8645
8646 if (Type.isTriviallyCopyableType(S.Context))
8647 return true;
8648
8649 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00008650 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8651 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008652 if (ClassDecl->needsImplicitMoveConstructor())
8653 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008654 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00008655 }
8656
Richard Smithe5411b72012-12-01 02:35:44 +00008657 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8658 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00008659 if (ClassDecl->needsImplicitMoveAssignment())
8660 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00008661 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00008662}
8663
8664/// Determine whether all non-static data members and direct or virtual bases
8665/// of class \p ClassDecl have either a move operation, or are trivially
8666/// copyable.
8667static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8668 bool IsConstructor) {
8669 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8670 BaseEnd = ClassDecl->bases_end();
8671 Base != BaseEnd; ++Base) {
8672 if (Base->isVirtual())
8673 continue;
8674
8675 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8676 return false;
8677 }
8678
8679 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8680 BaseEnd = ClassDecl->vbases_end();
8681 Base != BaseEnd; ++Base) {
8682 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8683 return false;
8684 }
8685
8686 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8687 FieldEnd = ClassDecl->field_end();
8688 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008689 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008690 return false;
8691 }
8692
8693 return true;
8694}
8695
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008696CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008697 // C++11 [class.copy]p20:
8698 // If the definition of a class X does not explicitly declare a move
8699 // assignment operator, one will be implicitly declared as defaulted
8700 // if and only if:
8701 //
8702 // - [first 4 bullets]
8703 assert(ClassDecl->needsImplicitMoveAssignment());
8704
Richard Smithafb49182012-11-29 01:34:07 +00008705 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8706 if (DSM.isAlreadyBeingDeclared())
8707 return 0;
8708
Richard Smith1c931be2012-04-02 18:40:40 +00008709 // [Checked after we build the declaration]
8710 // - the move assignment operator would not be implicitly defined as
8711 // deleted,
8712
8713 // [DR1402]:
8714 // - X has no direct or indirect virtual base class with a non-trivial
8715 // move assignment operator, and
8716 // - each of X's non-static data members and direct or virtual base classes
8717 // has a type that either has a move assignment operator or is trivially
8718 // copyable.
8719 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8720 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8721 ClassDecl->setFailedImplicitMoveAssignment();
8722 return 0;
8723 }
8724
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008725 // Note: The following rules are largely analoguous to the move
8726 // constructor rules.
8727
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008728 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8729 QualType RetType = Context.getLValueReferenceType(ArgType);
8730 ArgType = Context.getRValueReferenceType(ArgType);
8731
8732 // An implicitly-declared move assignment operator is an inline public
8733 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008734 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8735 SourceLocation ClassLoc = ClassDecl->getLocation();
8736 DeclarationNameInfo NameInfo(Name, ClassLoc);
8737 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008738 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008739 /*TInfo=*/0, /*isStatic=*/false,
8740 /*StorageClassAsWritten=*/SC_None,
8741 /*isInline=*/true,
8742 /*isConstexpr=*/false,
8743 SourceLocation());
8744 MoveAssignment->setAccess(AS_public);
8745 MoveAssignment->setDefaulted();
8746 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008747
Richard Smithb9d0b762012-07-27 04:22:15 +00008748 // Build an exception specification pointing back at this member.
8749 FunctionProtoType::ExtProtoInfo EPI;
8750 EPI.ExceptionSpecType = EST_Unevaluated;
8751 EPI.ExceptionSpecDecl = MoveAssignment;
8752 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8753
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008754 // Add the parameter to the operator.
8755 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8756 ClassLoc, ClassLoc, /*Id=*/0,
8757 ArgType, /*TInfo=*/0,
8758 SC_None,
8759 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008760 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008761
Richard Smithbc2a35d2012-12-08 08:32:28 +00008762 AddOverriddenMethods(ClassDecl, MoveAssignment);
8763
8764 MoveAssignment->setTrivial(
8765 ClassDecl->needsOverloadResolutionForMoveAssignment()
8766 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8767 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008768
8769 // C++0x [class.copy]p9:
8770 // If the definition of a class X does not explicitly declare a move
8771 // assignment operator, one will be implicitly declared as defaulted if and
8772 // only if:
8773 // [...]
8774 // - the move assignment operator would not be implicitly defined as
8775 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008776 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008777 // Cache this result so that we don't try to generate this over and over
8778 // on every lookup, leaking memory and wasting time.
8779 ClassDecl->setFailedImplicitMoveAssignment();
8780 return 0;
8781 }
8782
Richard Smithbc2a35d2012-12-08 08:32:28 +00008783 // Note that we have added this copy-assignment operator.
8784 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8785
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008786 if (Scope *S = getScopeForContext(ClassDecl))
8787 PushOnScopeChains(MoveAssignment, S, false);
8788 ClassDecl->addDecl(MoveAssignment);
8789
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008790 return MoveAssignment;
8791}
8792
8793void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8794 CXXMethodDecl *MoveAssignOperator) {
8795 assert((MoveAssignOperator->isDefaulted() &&
8796 MoveAssignOperator->isOverloadedOperator() &&
8797 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008798 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8799 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008800 "DefineImplicitMoveAssignment called for wrong function");
8801
8802 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8803
8804 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8805 MoveAssignOperator->setInvalidDecl();
8806 return;
8807 }
8808
8809 MoveAssignOperator->setUsed();
8810
Eli Friedman9a14db32012-10-18 20:14:08 +00008811 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008812 DiagnosticErrorTrap Trap(Diags);
8813
8814 // C++0x [class.copy]p28:
8815 // The implicitly-defined or move assignment operator for a non-union class
8816 // X performs memberwise move assignment of its subobjects. The direct base
8817 // classes of X are assigned first, in the order of their declaration in the
8818 // base-specifier-list, and then the immediate non-static data members of X
8819 // are assigned, in the order in which they were declared in the class
8820 // definition.
8821
8822 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008823 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008824
8825 // The parameter for the "other" object, which we are move from.
8826 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8827 QualType OtherRefType = Other->getType()->
8828 getAs<RValueReferenceType>()->getPointeeType();
8829 assert(OtherRefType.getQualifiers() == 0 &&
8830 "Bad argument type of defaulted move assignment");
8831
8832 // Our location for everything implicitly-generated.
8833 SourceLocation Loc = MoveAssignOperator->getLocation();
8834
8835 // Construct a reference to the "other" object. We'll be using this
8836 // throughout the generated ASTs.
8837 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8838 assert(OtherRef && "Reference to parameter cannot fail!");
8839 // Cast to rvalue.
8840 OtherRef = CastForMoving(*this, OtherRef);
8841
8842 // Construct the "this" pointer. We'll be using this throughout the generated
8843 // ASTs.
8844 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8845 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008846
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008847 // Assign base classes.
8848 bool Invalid = false;
8849 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8850 E = ClassDecl->bases_end(); Base != E; ++Base) {
8851 // Form the assignment:
8852 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8853 QualType BaseType = Base->getType().getUnqualifiedType();
8854 if (!BaseType->isRecordType()) {
8855 Invalid = true;
8856 continue;
8857 }
8858
8859 CXXCastPath BasePath;
8860 BasePath.push_back(Base);
8861
8862 // Construct the "from" expression, which is an implicit cast to the
8863 // appropriately-qualified base type.
8864 Expr *From = OtherRef;
8865 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008866 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008867
8868 // Dereference "this".
8869 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8870
8871 // Implicitly cast "this" to the appropriately-qualified base type.
8872 To = ImpCastExprToType(To.take(),
8873 Context.getCVRQualifiedType(BaseType,
8874 MoveAssignOperator->getTypeQualifiers()),
8875 CK_UncheckedDerivedToBase,
8876 VK_LValue, &BasePath);
8877
8878 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00008879 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008880 To.get(), From,
8881 /*CopyingBaseSubobject=*/true,
8882 /*Copying=*/false);
8883 if (Move.isInvalid()) {
8884 Diag(CurrentLocation, diag::note_member_synthesized_at)
8885 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8886 MoveAssignOperator->setInvalidDecl();
8887 return;
8888 }
8889
8890 // Success! Record the move.
8891 Statements.push_back(Move.takeAs<Expr>());
8892 }
8893
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008894 // Assign non-static members.
8895 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8896 FieldEnd = ClassDecl->field_end();
8897 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008898 if (Field->isUnnamedBitfield())
8899 continue;
8900
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008901 // Check for members of reference type; we can't move those.
8902 if (Field->getType()->isReferenceType()) {
8903 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8904 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8905 Diag(Field->getLocation(), diag::note_declared_at);
8906 Diag(CurrentLocation, diag::note_member_synthesized_at)
8907 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8908 Invalid = true;
8909 continue;
8910 }
8911
8912 // Check for members of const-qualified, non-class type.
8913 QualType BaseType = Context.getBaseElementType(Field->getType());
8914 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8915 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8916 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8917 Diag(Field->getLocation(), diag::note_declared_at);
8918 Diag(CurrentLocation, diag::note_member_synthesized_at)
8919 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8920 Invalid = true;
8921 continue;
8922 }
8923
8924 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008925 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8926 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008927
8928 QualType FieldType = Field->getType().getNonReferenceType();
8929 if (FieldType->isIncompleteArrayType()) {
8930 assert(ClassDecl->hasFlexibleArrayMember() &&
8931 "Incomplete array type is not valid");
8932 continue;
8933 }
8934
8935 // Build references to the field in the object we're copying from and to.
8936 CXXScopeSpec SS; // Intentionally empty
8937 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8938 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008939 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008940 MemberLookup.resolveKind();
8941 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8942 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008943 SS, SourceLocation(), 0,
8944 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008945 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8946 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008947 SS, SourceLocation(), 0,
8948 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008949 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8950 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8951
8952 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8953 "Member reference with rvalue base must be rvalue except for reference "
8954 "members, which aren't allowed for move assignment.");
8955
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008956 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00008957 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008958 To.get(), From.get(),
8959 /*CopyingBaseSubobject=*/false,
8960 /*Copying=*/false);
8961 if (Move.isInvalid()) {
8962 Diag(CurrentLocation, diag::note_member_synthesized_at)
8963 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8964 MoveAssignOperator->setInvalidDecl();
8965 return;
8966 }
Richard Smithe7ce7092012-11-12 23:33:00 +00008967
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008968 // Success! Record the copy.
8969 Statements.push_back(Move.takeAs<Stmt>());
8970 }
8971
8972 if (!Invalid) {
8973 // Add a "return *this;"
8974 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8975
8976 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8977 if (Return.isInvalid())
8978 Invalid = true;
8979 else {
8980 Statements.push_back(Return.takeAs<Stmt>());
8981
8982 if (Trap.hasErrorOccurred()) {
8983 Diag(CurrentLocation, diag::note_member_synthesized_at)
8984 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8985 Invalid = true;
8986 }
8987 }
8988 }
8989
8990 if (Invalid) {
8991 MoveAssignOperator->setInvalidDecl();
8992 return;
8993 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008994
8995 StmtResult Body;
8996 {
8997 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008998 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008999 /*isStmtExpr=*/false);
9000 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9001 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009002 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9003
9004 if (ASTMutationListener *L = getASTMutationListener()) {
9005 L->CompletedImplicitDefinition(MoveAssignOperator);
9006 }
9007}
9008
Richard Smithb9d0b762012-07-27 04:22:15 +00009009Sema::ImplicitExceptionSpecification
9010Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9011 CXXRecordDecl *ClassDecl = MD->getParent();
9012
9013 ImplicitExceptionSpecification ExceptSpec(*this);
9014 if (ClassDecl->isInvalidDecl())
9015 return ExceptSpec;
9016
9017 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9018 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9019 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9020
Douglas Gregor0d405db2010-07-01 20:59:04 +00009021 // C++ [except.spec]p14:
9022 // An implicitly declared special member function (Clause 12) shall have an
9023 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009024 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9025 BaseEnd = ClassDecl->bases_end();
9026 Base != BaseEnd;
9027 ++Base) {
9028 // Virtual bases are handled below.
9029 if (Base->isVirtual())
9030 continue;
9031
Douglas Gregor22584312010-07-02 23:41:54 +00009032 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009033 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009034 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009035 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009036 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009037 }
9038 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9039 BaseEnd = ClassDecl->vbases_end();
9040 Base != BaseEnd;
9041 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009042 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009043 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009044 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009045 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009046 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009047 }
9048 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9049 FieldEnd = ClassDecl->field_end();
9050 Field != FieldEnd;
9051 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009052 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009053 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9054 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009055 LookupCopyingConstructor(FieldClassDecl,
9056 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009057 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009058 }
9059 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009060
Richard Smithb9d0b762012-07-27 04:22:15 +00009061 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009062}
9063
9064CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9065 CXXRecordDecl *ClassDecl) {
9066 // C++ [class.copy]p4:
9067 // If the class definition does not explicitly declare a copy
9068 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009069 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009070
Richard Smithafb49182012-11-29 01:34:07 +00009071 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9072 if (DSM.isAlreadyBeingDeclared())
9073 return 0;
9074
Sean Hunt49634cf2011-05-13 06:10:58 +00009075 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9076 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009077 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009078 if (Const)
9079 ArgType = ArgType.withConst();
9080 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009081
Richard Smith7756afa2012-06-10 05:43:50 +00009082 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9083 CXXCopyConstructor,
9084 Const);
9085
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009086 DeclarationName Name
9087 = Context.DeclarationNames.getCXXConstructorName(
9088 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009089 SourceLocation ClassLoc = ClassDecl->getLocation();
9090 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009091
9092 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009093 // member of its class.
9094 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009095 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009096 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009097 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009098 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009099 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009100
Richard Smithb9d0b762012-07-27 04:22:15 +00009101 // Build an exception specification pointing back at this member.
9102 FunctionProtoType::ExtProtoInfo EPI;
9103 EPI.ExceptionSpecType = EST_Unevaluated;
9104 EPI.ExceptionSpecDecl = CopyConstructor;
9105 CopyConstructor->setType(
9106 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9107
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009108 // Add the parameter to the constructor.
9109 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009110 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009111 /*IdentifierInfo=*/0,
9112 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009113 SC_None,
9114 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009115 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009116
Richard Smithbc2a35d2012-12-08 08:32:28 +00009117 CopyConstructor->setTrivial(
9118 ClassDecl->needsOverloadResolutionForCopyConstructor()
9119 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9120 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009121
Nico Weberafcc96a2012-01-23 03:19:29 +00009122 // C++11 [class.copy]p8:
9123 // ... If the class definition does not explicitly declare a copy
9124 // constructor, there is no user-declared move constructor, and there is no
9125 // user-declared move assignment operator, a copy constructor is implicitly
9126 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009127 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00009128 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00009129
Richard Smithbc2a35d2012-12-08 08:32:28 +00009130 // Note that we have declared this constructor.
9131 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9132
9133 if (Scope *S = getScopeForContext(ClassDecl))
9134 PushOnScopeChains(CopyConstructor, S, false);
9135 ClassDecl->addDecl(CopyConstructor);
9136
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009137 return CopyConstructor;
9138}
9139
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009140void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009141 CXXConstructorDecl *CopyConstructor) {
9142 assert((CopyConstructor->isDefaulted() &&
9143 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009144 !CopyConstructor->doesThisDeclarationHaveABody() &&
9145 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009146 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009147
Anders Carlsson63010a72010-04-23 16:24:12 +00009148 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009149 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009150
Eli Friedman9a14db32012-10-18 20:14:08 +00009151 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009152 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009153
Sean Huntcbb67482011-01-08 20:30:50 +00009154 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009155 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009156 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009157 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009158 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009159 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009160 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009161 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9162 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009163 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009164 /*isStmtExpr=*/false)
9165 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009166 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009167 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009168
9169 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009170 if (ASTMutationListener *L = getASTMutationListener()) {
9171 L->CompletedImplicitDefinition(CopyConstructor);
9172 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009173}
9174
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009175Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009176Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9177 CXXRecordDecl *ClassDecl = MD->getParent();
9178
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009179 // C++ [except.spec]p14:
9180 // An implicitly declared special member function (Clause 12) shall have an
9181 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009182 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009183 if (ClassDecl->isInvalidDecl())
9184 return ExceptSpec;
9185
9186 // Direct base-class constructors.
9187 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9188 BEnd = ClassDecl->bases_end();
9189 B != BEnd; ++B) {
9190 if (B->isVirtual()) // Handled below.
9191 continue;
9192
9193 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9194 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009195 CXXConstructorDecl *Constructor =
9196 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009197 // If this is a deleted function, add it anyway. This might be conformant
9198 // with the standard. This might not. I'm not sure. It might not matter.
9199 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009200 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009201 }
9202 }
9203
9204 // Virtual base-class constructors.
9205 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9206 BEnd = ClassDecl->vbases_end();
9207 B != BEnd; ++B) {
9208 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9209 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009210 CXXConstructorDecl *Constructor =
9211 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009212 // If this is a deleted function, add it anyway. This might be conformant
9213 // with the standard. This might not. I'm not sure. It might not matter.
9214 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009215 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009216 }
9217 }
9218
9219 // Field constructors.
9220 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9221 FEnd = ClassDecl->field_end();
9222 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009223 QualType FieldType = Context.getBaseElementType(F->getType());
9224 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9225 CXXConstructorDecl *Constructor =
9226 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009227 // If this is a deleted function, add it anyway. This might be conformant
9228 // with the standard. This might not. I'm not sure. It might not matter.
9229 // In particular, the problem is that this function never gets called. It
9230 // might just be ill-formed because this function attempts to refer to
9231 // a deleted function here.
9232 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009233 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009234 }
9235 }
9236
9237 return ExceptSpec;
9238}
9239
9240CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9241 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009242 // C++11 [class.copy]p9:
9243 // If the definition of a class X does not explicitly declare a move
9244 // constructor, one will be implicitly declared as defaulted if and only if:
9245 //
9246 // - [first 4 bullets]
9247 assert(ClassDecl->needsImplicitMoveConstructor());
9248
Richard Smithafb49182012-11-29 01:34:07 +00009249 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9250 if (DSM.isAlreadyBeingDeclared())
9251 return 0;
9252
Richard Smith1c931be2012-04-02 18:40:40 +00009253 // [Checked after we build the declaration]
9254 // - the move assignment operator would not be implicitly defined as
9255 // deleted,
9256
9257 // [DR1402]:
9258 // - each of X's non-static data members and direct or virtual base classes
9259 // has a type that either has a move constructor or is trivially copyable.
9260 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9261 ClassDecl->setFailedImplicitMoveConstructor();
9262 return 0;
9263 }
9264
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009265 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9266 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009267
Richard Smith7756afa2012-06-10 05:43:50 +00009268 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9269 CXXMoveConstructor,
9270 false);
9271
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009272 DeclarationName Name
9273 = Context.DeclarationNames.getCXXConstructorName(
9274 Context.getCanonicalType(ClassType));
9275 SourceLocation ClassLoc = ClassDecl->getLocation();
9276 DeclarationNameInfo NameInfo(Name, ClassLoc);
9277
9278 // C++0x [class.copy]p11:
9279 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009280 // member of its class.
9281 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009282 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009283 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009284 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009285 MoveConstructor->setAccess(AS_public);
9286 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009287
Richard Smithb9d0b762012-07-27 04:22:15 +00009288 // Build an exception specification pointing back at this member.
9289 FunctionProtoType::ExtProtoInfo EPI;
9290 EPI.ExceptionSpecType = EST_Unevaluated;
9291 EPI.ExceptionSpecDecl = MoveConstructor;
9292 MoveConstructor->setType(
9293 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9294
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009295 // Add the parameter to the constructor.
9296 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9297 ClassLoc, ClassLoc,
9298 /*IdentifierInfo=*/0,
9299 ArgType, /*TInfo=*/0,
9300 SC_None,
9301 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009302 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009303
Richard Smithbc2a35d2012-12-08 08:32:28 +00009304 MoveConstructor->setTrivial(
9305 ClassDecl->needsOverloadResolutionForMoveConstructor()
9306 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9307 : ClassDecl->hasTrivialMoveConstructor());
9308
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009309 // C++0x [class.copy]p9:
9310 // If the definition of a class X does not explicitly declare a move
9311 // constructor, one will be implicitly declared as defaulted if and only if:
9312 // [...]
9313 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009314 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009315 // Cache this result so that we don't try to generate this over and over
9316 // on every lookup, leaking memory and wasting time.
9317 ClassDecl->setFailedImplicitMoveConstructor();
9318 return 0;
9319 }
9320
9321 // Note that we have declared this constructor.
9322 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9323
9324 if (Scope *S = getScopeForContext(ClassDecl))
9325 PushOnScopeChains(MoveConstructor, S, false);
9326 ClassDecl->addDecl(MoveConstructor);
9327
9328 return MoveConstructor;
9329}
9330
9331void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9332 CXXConstructorDecl *MoveConstructor) {
9333 assert((MoveConstructor->isDefaulted() &&
9334 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009335 !MoveConstructor->doesThisDeclarationHaveABody() &&
9336 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009337 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9338
9339 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9340 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9341
Eli Friedman9a14db32012-10-18 20:14:08 +00009342 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009343 DiagnosticErrorTrap Trap(Diags);
9344
9345 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9346 Trap.hasErrorOccurred()) {
9347 Diag(CurrentLocation, diag::note_member_synthesized_at)
9348 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9349 MoveConstructor->setInvalidDecl();
9350 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009351 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009352 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9353 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00009354 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009355 /*isStmtExpr=*/false)
9356 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00009357 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009358 }
9359
9360 MoveConstructor->setUsed();
9361
9362 if (ASTMutationListener *L = getASTMutationListener()) {
9363 L->CompletedImplicitDefinition(MoveConstructor);
9364 }
9365}
9366
Douglas Gregore4e68d42012-02-15 19:33:52 +00009367bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9368 return FD->isDeleted() &&
9369 (FD->isDefaulted() || FD->isImplicit()) &&
9370 isa<CXXMethodDecl>(FD);
9371}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009372
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009373/// \brief Mark the call operator of the given lambda closure type as "used".
9374static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9375 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00009376 = cast<CXXMethodDecl>(
9377 *Lambda->lookup(
9378 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009379 CallOperator->setReferenced();
9380 CallOperator->setUsed();
9381}
9382
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009383void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9384 SourceLocation CurrentLocation,
9385 CXXConversionDecl *Conv)
9386{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009387 CXXRecordDecl *Lambda = Conv->getParent();
9388
9389 // Make sure that the lambda call operator is marked used.
9390 markLambdaCallOperatorUsed(*this, Lambda);
9391
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009392 Conv->setUsed();
9393
Eli Friedman9a14db32012-10-18 20:14:08 +00009394 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009395 DiagnosticErrorTrap Trap(Diags);
9396
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009397 // Return the address of the __invoke function.
9398 DeclarationName InvokeName = &Context.Idents.get("__invoke");
9399 CXXMethodDecl *Invoke
9400 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
9401 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9402 VK_LValue, Conv->getLocation()).take();
9403 assert(FunctionRef && "Can't refer to __invoke function?");
9404 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9405 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
9406 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009407 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009408
9409 // Fill in the __invoke function with a dummy implementation. IR generation
9410 // will fill in the actual details.
9411 Invoke->setUsed();
9412 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009413 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009414
9415 if (ASTMutationListener *L = getASTMutationListener()) {
9416 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00009417 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009418 }
9419}
9420
9421void Sema::DefineImplicitLambdaToBlockPointerConversion(
9422 SourceLocation CurrentLocation,
9423 CXXConversionDecl *Conv)
9424{
9425 Conv->setUsed();
9426
Eli Friedman9a14db32012-10-18 20:14:08 +00009427 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009428 DiagnosticErrorTrap Trap(Diags);
9429
Douglas Gregorac1303e2012-02-22 05:02:47 +00009430 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009431 Expr *This = ActOnCXXThis(CurrentLocation).take();
9432 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009433
Eli Friedman23f02672012-03-01 04:01:32 +00009434 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9435 Conv->getLocation(),
9436 Conv, DerefThis);
9437
9438 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9439 // behavior. Note that only the general conversion function does this
9440 // (since it's unusable otherwise); in the case where we inline the
9441 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00009442 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00009443 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9444 CK_CopyAndAutoreleaseBlockObject,
9445 BuildBlock.get(), 0, VK_RValue);
9446
9447 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009448 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009449 Conv->setInvalidDecl();
9450 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009451 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009452
Douglas Gregorac1303e2012-02-22 05:02:47 +00009453 // Create the return statement that returns the block from the conversion
9454 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009455 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009456 if (Return.isInvalid()) {
9457 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9458 Conv->setInvalidDecl();
9459 return;
9460 }
9461
9462 // Set the body of the conversion function.
9463 Stmt *ReturnS = Return.take();
9464 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9465 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009466 Conv->getLocation()));
9467
Douglas Gregorac1303e2012-02-22 05:02:47 +00009468 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009469 if (ASTMutationListener *L = getASTMutationListener()) {
9470 L->CompletedImplicitDefinition(Conv);
9471 }
9472}
9473
Douglas Gregorf52757d2012-03-10 06:53:13 +00009474/// \brief Determine whether the given list arguments contains exactly one
9475/// "real" (non-default) argument.
9476static bool hasOneRealArgument(MultiExprArg Args) {
9477 switch (Args.size()) {
9478 case 0:
9479 return false;
9480
9481 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009482 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009483 return false;
9484
9485 // fall through
9486 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009487 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009488 }
9489
9490 return false;
9491}
9492
John McCall60d7b3a2010-08-24 06:29:42 +00009493ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009494Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009495 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009496 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009497 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009498 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009499 unsigned ConstructKind,
9500 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009501 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009502
Douglas Gregor2f599792010-04-02 18:24:57 +00009503 // C++0x [class.copy]p34:
9504 // When certain criteria are met, an implementation is allowed to
9505 // omit the copy/move construction of a class object, even if the
9506 // copy/move constructor and/or destructor for the object have
9507 // side effects. [...]
9508 // - when a temporary class object that has not been bound to a
9509 // reference (12.2) would be copied/moved to a class object
9510 // with the same cv-unqualified type, the copy/move operation
9511 // can be omitted by constructing the temporary object
9512 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009513 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009514 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009515 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009516 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009517 }
Mike Stump1eb44332009-09-09 15:08:12 +00009518
9519 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009520 Elidable, ExprArgs, HadMultipleCandidates,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009521 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009522}
9523
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009524/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9525/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009526ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009527Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9528 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009529 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009530 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009531 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009532 unsigned ConstructKind,
9533 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009534 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009535 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009536 Constructor, Elidable, ExprArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009537 HadMultipleCandidates, /*FIXME*/false,
9538 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009539 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9540 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009541}
9542
Mike Stump1eb44332009-09-09 15:08:12 +00009543bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009544 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009545 MultiExprArg Exprs,
9546 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009547 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009548 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009549 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009550 Exprs, HadMultipleCandidates, false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009551 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009552 if (TempResult.isInvalid())
9553 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009554
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009555 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009556 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009557 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009558 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009559 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009560
Anders Carlssonfe2de492009-08-25 05:18:00 +00009561 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009562}
9563
John McCall68c6c9a2010-02-02 09:10:11 +00009564void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009565 if (VD->isInvalidDecl()) return;
9566
John McCall68c6c9a2010-02-02 09:10:11 +00009567 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009568 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009569 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009570 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009571
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009572 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009573 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009574 CheckDestructorAccess(VD->getLocation(), Destructor,
9575 PDiag(diag::err_access_dtor_var)
9576 << VD->getDeclName()
9577 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009578 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009579
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009580 if (!VD->hasGlobalStorage()) return;
9581
9582 // Emit warning for non-trivial dtor in global scope (a real global,
9583 // class-static, function-static).
9584 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9585
9586 // TODO: this should be re-enabled for static locals by !CXAAtExit
9587 if (!VD->isStaticLocal())
9588 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009589}
9590
Douglas Gregor39da0b82009-09-09 23:08:42 +00009591/// \brief Given a constructor and the set of arguments provided for the
9592/// constructor, convert the arguments and add any required default arguments
9593/// to form a proper call to this constructor.
9594///
9595/// \returns true if an error occurred, false otherwise.
9596bool
9597Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9598 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009599 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009600 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009601 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009602 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9603 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009604 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009605
9606 const FunctionProtoType *Proto
9607 = Constructor->getType()->getAs<FunctionProtoType>();
9608 assert(Proto && "Constructor without a prototype?");
9609 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009610
9611 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009612 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009613 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009614 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009615 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009616
9617 VariadicCallType CallType =
9618 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009619 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009620 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9621 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009622 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009623 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009624
9625 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9626
Richard Smith831421f2012-06-25 20:30:08 +00009627 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9628 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009629
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009630 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009631}
9632
Anders Carlsson20d45d22009-12-12 00:32:00 +00009633static inline bool
9634CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9635 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009636 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009637 if (isa<NamespaceDecl>(DC)) {
9638 return SemaRef.Diag(FnDecl->getLocation(),
9639 diag::err_operator_new_delete_declared_in_namespace)
9640 << FnDecl->getDeclName();
9641 }
9642
9643 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009644 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009645 return SemaRef.Diag(FnDecl->getLocation(),
9646 diag::err_operator_new_delete_declared_static)
9647 << FnDecl->getDeclName();
9648 }
9649
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009650 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009651}
9652
Anders Carlsson156c78e2009-12-13 17:53:43 +00009653static inline bool
9654CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9655 CanQualType ExpectedResultType,
9656 CanQualType ExpectedFirstParamType,
9657 unsigned DependentParamTypeDiag,
9658 unsigned InvalidParamTypeDiag) {
9659 QualType ResultType =
9660 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9661
9662 // Check that the result type is not dependent.
9663 if (ResultType->isDependentType())
9664 return SemaRef.Diag(FnDecl->getLocation(),
9665 diag::err_operator_new_delete_dependent_result_type)
9666 << FnDecl->getDeclName() << ExpectedResultType;
9667
9668 // Check that the result type is what we expect.
9669 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9670 return SemaRef.Diag(FnDecl->getLocation(),
9671 diag::err_operator_new_delete_invalid_result_type)
9672 << FnDecl->getDeclName() << ExpectedResultType;
9673
9674 // A function template must have at least 2 parameters.
9675 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9676 return SemaRef.Diag(FnDecl->getLocation(),
9677 diag::err_operator_new_delete_template_too_few_parameters)
9678 << FnDecl->getDeclName();
9679
9680 // The function decl must have at least 1 parameter.
9681 if (FnDecl->getNumParams() == 0)
9682 return SemaRef.Diag(FnDecl->getLocation(),
9683 diag::err_operator_new_delete_too_few_parameters)
9684 << FnDecl->getDeclName();
9685
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009686 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009687 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9688 if (FirstParamType->isDependentType())
9689 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9690 << FnDecl->getDeclName() << ExpectedFirstParamType;
9691
9692 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009693 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009694 ExpectedFirstParamType)
9695 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9696 << FnDecl->getDeclName() << ExpectedFirstParamType;
9697
9698 return false;
9699}
9700
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009701static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009702CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009703 // C++ [basic.stc.dynamic.allocation]p1:
9704 // A program is ill-formed if an allocation function is declared in a
9705 // namespace scope other than global scope or declared static in global
9706 // scope.
9707 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9708 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009709
9710 CanQualType SizeTy =
9711 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9712
9713 // C++ [basic.stc.dynamic.allocation]p1:
9714 // The return type shall be void*. The first parameter shall have type
9715 // std::size_t.
9716 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9717 SizeTy,
9718 diag::err_operator_new_dependent_param_type,
9719 diag::err_operator_new_param_type))
9720 return true;
9721
9722 // C++ [basic.stc.dynamic.allocation]p1:
9723 // The first parameter shall not have an associated default argument.
9724 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009725 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009726 diag::err_operator_new_default_arg)
9727 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9728
9729 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009730}
9731
9732static bool
Richard Smith444d3842012-10-20 08:26:51 +00009733CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009734 // C++ [basic.stc.dynamic.deallocation]p1:
9735 // A program is ill-formed if deallocation functions are declared in a
9736 // namespace scope other than global scope or declared static in global
9737 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009738 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9739 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009740
9741 // C++ [basic.stc.dynamic.deallocation]p2:
9742 // Each deallocation function shall return void and its first parameter
9743 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009744 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9745 SemaRef.Context.VoidPtrTy,
9746 diag::err_operator_delete_dependent_param_type,
9747 diag::err_operator_delete_param_type))
9748 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009749
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009750 return false;
9751}
9752
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009753/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9754/// of this overloaded operator is well-formed. If so, returns false;
9755/// otherwise, emits appropriate diagnostics and returns true.
9756bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009757 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009758 "Expected an overloaded operator declaration");
9759
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009760 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9761
Mike Stump1eb44332009-09-09 15:08:12 +00009762 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009763 // The allocation and deallocation functions, operator new,
9764 // operator new[], operator delete and operator delete[], are
9765 // described completely in 3.7.3. The attributes and restrictions
9766 // found in the rest of this subclause do not apply to them unless
9767 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009768 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009769 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009770
Anders Carlssona3ccda52009-12-12 00:26:23 +00009771 if (Op == OO_New || Op == OO_Array_New)
9772 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009773
9774 // C++ [over.oper]p6:
9775 // An operator function shall either be a non-static member
9776 // function or be a non-member function and have at least one
9777 // parameter whose type is a class, a reference to a class, an
9778 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009779 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9780 if (MethodDecl->isStatic())
9781 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009782 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009783 } else {
9784 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009785 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9786 ParamEnd = FnDecl->param_end();
9787 Param != ParamEnd; ++Param) {
9788 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009789 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9790 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009791 ClassOrEnumParam = true;
9792 break;
9793 }
9794 }
9795
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009796 if (!ClassOrEnumParam)
9797 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009798 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009799 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009800 }
9801
9802 // C++ [over.oper]p8:
9803 // An operator function cannot have default arguments (8.3.6),
9804 // except where explicitly stated below.
9805 //
Mike Stump1eb44332009-09-09 15:08:12 +00009806 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009807 // (C++ [over.call]p1).
9808 if (Op != OO_Call) {
9809 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9810 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009811 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009812 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009813 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009814 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009815 }
9816 }
9817
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009818 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9819 { false, false, false }
9820#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9821 , { Unary, Binary, MemberOnly }
9822#include "clang/Basic/OperatorKinds.def"
9823 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009824
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009825 bool CanBeUnaryOperator = OperatorUses[Op][0];
9826 bool CanBeBinaryOperator = OperatorUses[Op][1];
9827 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009828
9829 // C++ [over.oper]p8:
9830 // [...] Operator functions cannot have more or fewer parameters
9831 // than the number required for the corresponding operator, as
9832 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009833 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009834 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009835 if (Op != OO_Call &&
9836 ((NumParams == 1 && !CanBeUnaryOperator) ||
9837 (NumParams == 2 && !CanBeBinaryOperator) ||
9838 (NumParams < 1) || (NumParams > 2))) {
9839 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009840 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009841 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009842 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009843 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009844 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009845 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009846 assert(CanBeBinaryOperator &&
9847 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009848 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009849 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009850
Chris Lattner416e46f2008-11-21 07:57:12 +00009851 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009852 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009853 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009854
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009855 // Overloaded operators other than operator() cannot be variadic.
9856 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009857 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009858 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009859 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009860 }
9861
9862 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009863 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9864 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009865 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009866 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009867 }
9868
9869 // C++ [over.inc]p1:
9870 // The user-defined function called operator++ implements the
9871 // prefix and postfix ++ operator. If this function is a member
9872 // function with no parameters, or a non-member function with one
9873 // parameter of class or enumeration type, it defines the prefix
9874 // increment operator ++ for objects of that type. If the function
9875 // is a member function with one parameter (which shall be of type
9876 // int) or a non-member function with two parameters (the second
9877 // of which shall be of type int), it defines the postfix
9878 // increment operator ++ for objects of that type.
9879 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9880 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9881 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009882 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009883 ParamIsInt = BT->getKind() == BuiltinType::Int;
9884
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009885 if (!ParamIsInt)
9886 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009887 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009888 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009889 }
9890
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009891 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009892}
Chris Lattner5a003a42008-12-17 07:09:26 +00009893
Sean Hunta6c058d2010-01-13 09:01:02 +00009894/// CheckLiteralOperatorDeclaration - Check whether the declaration
9895/// of this literal operator function is well-formed. If so, returns
9896/// false; otherwise, emits appropriate diagnostics and returns true.
9897bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009898 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009899 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9900 << FnDecl->getDeclName();
9901 return true;
9902 }
9903
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009904 if (FnDecl->isExternC()) {
9905 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9906 return true;
9907 }
9908
Sean Hunta6c058d2010-01-13 09:01:02 +00009909 bool Valid = false;
9910
Richard Smith36f5cfe2012-03-09 08:00:36 +00009911 // This might be the definition of a literal operator template.
9912 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9913 // This might be a specialization of a literal operator template.
9914 if (!TpDecl)
9915 TpDecl = FnDecl->getPrimaryTemplate();
9916
Sean Hunt216c2782010-04-07 23:11:06 +00009917 // template <char...> type operator "" name() is the only valid template
9918 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009919 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009920 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009921 // Must have only one template parameter
9922 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9923 if (Params->size() == 1) {
9924 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009925 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009926
Sean Hunt216c2782010-04-07 23:11:06 +00009927 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009928 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9929 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9930 Valid = true;
9931 }
9932 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009933 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009934 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009935 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9936
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009937 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009938
Sean Hunt30019c02010-04-07 22:57:35 +00009939 // unsigned long long int, long double, and any character type are allowed
9940 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009941 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9942 Context.hasSameType(T, Context.LongDoubleTy) ||
9943 Context.hasSameType(T, Context.CharTy) ||
9944 Context.hasSameType(T, Context.WCharTy) ||
9945 Context.hasSameType(T, Context.Char16Ty) ||
9946 Context.hasSameType(T, Context.Char32Ty)) {
9947 if (++Param == FnDecl->param_end())
9948 Valid = true;
9949 goto FinishedParams;
9950 }
9951
Sean Hunt30019c02010-04-07 22:57:35 +00009952 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009953 const PointerType *PT = T->getAs<PointerType>();
9954 if (!PT)
9955 goto FinishedParams;
9956 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009957 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009958 goto FinishedParams;
9959 T = T.getUnqualifiedType();
9960
9961 // Move on to the second parameter;
9962 ++Param;
9963
9964 // If there is no second parameter, the first must be a const char *
9965 if (Param == FnDecl->param_end()) {
9966 if (Context.hasSameType(T, Context.CharTy))
9967 Valid = true;
9968 goto FinishedParams;
9969 }
9970
9971 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9972 // are allowed as the first parameter to a two-parameter function
9973 if (!(Context.hasSameType(T, Context.CharTy) ||
9974 Context.hasSameType(T, Context.WCharTy) ||
9975 Context.hasSameType(T, Context.Char16Ty) ||
9976 Context.hasSameType(T, Context.Char32Ty)))
9977 goto FinishedParams;
9978
9979 // The second and final parameter must be an std::size_t
9980 T = (*Param)->getType().getUnqualifiedType();
9981 if (Context.hasSameType(T, Context.getSizeType()) &&
9982 ++Param == FnDecl->param_end())
9983 Valid = true;
9984 }
9985
9986 // FIXME: This diagnostic is absolutely terrible.
9987FinishedParams:
9988 if (!Valid) {
9989 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9990 << FnDecl->getDeclName();
9991 return true;
9992 }
9993
Richard Smitha9e88b22012-03-09 08:16:22 +00009994 // A parameter-declaration-clause containing a default argument is not
9995 // equivalent to any of the permitted forms.
9996 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9997 ParamEnd = FnDecl->param_end();
9998 Param != ParamEnd; ++Param) {
9999 if ((*Param)->hasDefaultArg()) {
10000 Diag((*Param)->getDefaultArgRange().getBegin(),
10001 diag::err_literal_operator_default_argument)
10002 << (*Param)->getDefaultArgRange();
10003 break;
10004 }
10005 }
10006
Richard Smith2fb4ae32012-03-08 02:39:21 +000010007 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010008 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10009 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010010 // C++11 [usrlit.suffix]p1:
10011 // Literal suffix identifiers that do not start with an underscore
10012 // are reserved for future standardization.
10013 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +000010014 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010015
Sean Hunta6c058d2010-01-13 09:01:02 +000010016 return false;
10017}
10018
Douglas Gregor074149e2009-01-05 19:45:36 +000010019/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10020/// linkage specification, including the language and (if present)
10021/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10022/// the location of the language string literal, which is provided
10023/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10024/// the '{' brace. Otherwise, this linkage specification does not
10025/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010026Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10027 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010028 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010029 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010030 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010031 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010032 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010033 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010034 Language = LinkageSpecDecl::lang_cxx;
10035 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010036 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010037 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010038 }
Mike Stump1eb44332009-09-09 15:08:12 +000010039
Chris Lattnercc98eac2008-12-17 07:13:27 +000010040 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010041
Douglas Gregor074149e2009-01-05 19:45:36 +000010042 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010043 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010044 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010045 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010046 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010047}
10048
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010049/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010050/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10051/// valid, it's the position of the closing '}' brace in a linkage
10052/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010053Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010054 Decl *LinkageSpec,
10055 SourceLocation RBraceLoc) {
10056 if (LinkageSpec) {
10057 if (RBraceLoc.isValid()) {
10058 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10059 LSDecl->setRBraceLoc(RBraceLoc);
10060 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010061 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010062 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010063 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010064}
10065
Douglas Gregord308e622009-05-18 20:51:54 +000010066/// \brief Perform semantic analysis for the variable declaration that
10067/// occurs within a C++ catch clause, returning the newly-created
10068/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010069VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010070 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010071 SourceLocation StartLoc,
10072 SourceLocation Loc,
10073 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010074 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010075 QualType ExDeclType = TInfo->getType();
10076
Sebastian Redl4b07b292008-12-22 19:15:10 +000010077 // Arrays and functions decay.
10078 if (ExDeclType->isArrayType())
10079 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10080 else if (ExDeclType->isFunctionType())
10081 ExDeclType = Context.getPointerType(ExDeclType);
10082
10083 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10084 // The exception-declaration shall not denote a pointer or reference to an
10085 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010086 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010087 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010088 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010089 Invalid = true;
10090 }
Douglas Gregord308e622009-05-18 20:51:54 +000010091
Sebastian Redl4b07b292008-12-22 19:15:10 +000010092 QualType BaseType = ExDeclType;
10093 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010094 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010095 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010096 BaseType = Ptr->getPointeeType();
10097 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010098 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010099 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010100 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010101 BaseType = Ref->getPointeeType();
10102 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010103 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010104 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010105 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010106 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010107 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010108
Mike Stump1eb44332009-09-09 15:08:12 +000010109 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010110 RequireNonAbstractType(Loc, ExDeclType,
10111 diag::err_abstract_type_in_decl,
10112 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010113 Invalid = true;
10114
John McCall5a180392010-07-24 00:37:23 +000010115 // Only the non-fragile NeXT runtime currently supports C++ catches
10116 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010117 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010118 QualType T = ExDeclType;
10119 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10120 T = RT->getPointeeType();
10121
10122 if (T->isObjCObjectType()) {
10123 Diag(Loc, diag::err_objc_object_catch);
10124 Invalid = true;
10125 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010126 // FIXME: should this be a test for macosx-fragile specifically?
10127 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010128 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010129 }
10130 }
10131
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010132 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10133 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010134 ExDecl->setExceptionVariable(true);
10135
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010136 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010137 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010138 Invalid = true;
10139
Douglas Gregorc41b8782011-07-06 18:14:43 +000010140 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010141 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +000010142 // C++ [except.handle]p16:
10143 // The object declared in an exception-declaration or, if the
10144 // exception-declaration does not specify a name, a temporary (12.2) is
10145 // copy-initialized (8.5) from the exception object. [...]
10146 // The object is destroyed when the handler exits, after the destruction
10147 // of any automatic objects initialized within the handler.
10148 //
10149 // We just pretend to initialize the object with itself, then make sure
10150 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010151 QualType initType = ExDeclType;
10152
10153 InitializedEntity entity =
10154 InitializedEntity::InitializeVariable(ExDecl);
10155 InitializationKind initKind =
10156 InitializationKind::CreateCopy(Loc, SourceLocation());
10157
10158 Expr *opaqueValue =
10159 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10160 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10161 ExprResult result = sequence.Perform(*this, entity, initKind,
10162 MultiExprArg(&opaqueValue, 1));
10163 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010164 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010165 else {
10166 // If the constructor used was non-trivial, set this as the
10167 // "initializer".
10168 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10169 if (!construct->getConstructor()->isTrivial()) {
10170 Expr *init = MaybeCreateExprWithCleanups(construct);
10171 ExDecl->setInit(init);
10172 }
10173
10174 // And make sure it's destructable.
10175 FinalizeVarWithDestructor(ExDecl, recordType);
10176 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010177 }
10178 }
10179
Douglas Gregord308e622009-05-18 20:51:54 +000010180 if (Invalid)
10181 ExDecl->setInvalidDecl();
10182
10183 return ExDecl;
10184}
10185
10186/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10187/// handler.
John McCalld226f652010-08-21 09:40:31 +000010188Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010189 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010190 bool Invalid = D.isInvalidType();
10191
10192 // Check for unexpanded parameter packs.
10193 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10194 UPPC_ExceptionType)) {
10195 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10196 D.getIdentifierLoc());
10197 Invalid = true;
10198 }
10199
Sebastian Redl4b07b292008-12-22 19:15:10 +000010200 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010201 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010202 LookupOrdinaryName,
10203 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010204 // The scope should be freshly made just for us. There is just no way
10205 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010206 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010207 if (PrevDecl->isTemplateParameter()) {
10208 // Maybe we will complain about the shadowed template parameter.
10209 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010210 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010211 }
10212 }
10213
Chris Lattnereaaebc72009-04-25 08:06:05 +000010214 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010215 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10216 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010217 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010218 }
10219
Douglas Gregor83cb9422010-09-09 17:09:21 +000010220 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010221 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010222 D.getIdentifierLoc(),
10223 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010224 if (Invalid)
10225 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010226
Sebastian Redl4b07b292008-12-22 19:15:10 +000010227 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010228 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010229 PushOnScopeChains(ExDecl, S);
10230 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010231 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010232
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010233 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010234 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010235}
Anders Carlssonfb311762009-03-14 00:25:26 +000010236
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010237Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010238 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010239 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010240 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010241 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010242
Richard Smithe3f470a2012-07-11 22:37:56 +000010243 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10244 return 0;
10245
10246 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10247 AssertMessage, RParenLoc, false);
10248}
10249
10250Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10251 Expr *AssertExpr,
10252 StringLiteral *AssertMessage,
10253 SourceLocation RParenLoc,
10254 bool Failed) {
10255 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10256 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010257 // In a static_assert-declaration, the constant-expression shall be a
10258 // constant expression that can be contextually converted to bool.
10259 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10260 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010261 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010262
Richard Smithdaaefc52011-12-14 23:32:26 +000010263 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010264 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010265 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010266 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010267 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010268
Richard Smithe3f470a2012-07-11 22:37:56 +000010269 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +000010270 llvm::SmallString<256> MsgBuffer;
10271 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010272 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010273 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010274 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010275 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010276 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010277 }
Mike Stump1eb44332009-09-09 15:08:12 +000010278
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010279 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010280 AssertExpr, AssertMessage, RParenLoc,
10281 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010282
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010283 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010284 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010285}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010286
Douglas Gregor1d869352010-04-07 16:53:43 +000010287/// \brief Perform semantic analysis of the given friend type declaration.
10288///
10289/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010290FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010291 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010292 TypeSourceInfo *TSInfo) {
10293 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10294
10295 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010296 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010297
Richard Smith6b130222011-10-18 21:39:00 +000010298 // C++03 [class.friend]p2:
10299 // An elaborated-type-specifier shall be used in a friend declaration
10300 // for a class.*
10301 //
10302 // * The class-key of the elaborated-type-specifier is required.
10303 if (!ActiveTemplateInstantiations.empty()) {
10304 // Do not complain about the form of friend template types during
10305 // template instantiation; we will already have complained when the
10306 // template was declared.
10307 } else if (!T->isElaboratedTypeSpecifier()) {
10308 // If we evaluated the type to a record type, suggest putting
10309 // a tag in front.
10310 if (const RecordType *RT = T->getAs<RecordType>()) {
10311 RecordDecl *RD = RT->getDecl();
10312
10313 std::string InsertionText = std::string(" ") + RD->getKindName();
10314
10315 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010316 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010317 diag::warn_cxx98_compat_unelaborated_friend_type :
10318 diag::ext_unelaborated_friend_type)
10319 << (unsigned) RD->getTagKind()
10320 << T
10321 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10322 InsertionText);
10323 } else {
10324 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010325 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010326 diag::warn_cxx98_compat_nonclass_type_friend :
10327 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010328 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010329 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010330 }
Richard Smith6b130222011-10-18 21:39:00 +000010331 } else if (T->getAs<EnumType>()) {
10332 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +000010333 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +000010334 diag::warn_cxx98_compat_enum_friend :
10335 diag::ext_enum_friend)
10336 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010337 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010338 }
10339
Richard Smithd6f80da2012-09-20 01:31:00 +000010340 // C++11 [class.friend]p3:
10341 // A friend declaration that does not declare a function shall have one
10342 // of the following forms:
10343 // friend elaborated-type-specifier ;
10344 // friend simple-type-specifier ;
10345 // friend typename-specifier ;
10346 if (getLangOpts().CPlusPlus0x && LocStart != FriendLoc)
10347 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10348
Douglas Gregor06245bf2010-04-07 17:57:12 +000010349 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010350 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010351 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010352 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010353}
10354
John McCall9a34edb2010-10-19 01:40:49 +000010355/// Handle a friend tag declaration where the scope specifier was
10356/// templated.
10357Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10358 unsigned TagSpec, SourceLocation TagLoc,
10359 CXXScopeSpec &SS,
10360 IdentifierInfo *Name, SourceLocation NameLoc,
10361 AttributeList *Attr,
10362 MultiTemplateParamsArg TempParamLists) {
10363 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10364
10365 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010366 bool Invalid = false;
10367
10368 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010369 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010370 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +000010371 TempParamLists.size(),
10372 /*friend*/ true,
10373 isExplicitSpecialization,
10374 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010375 if (TemplateParams->size() > 0) {
10376 // This is a declaration of a class template.
10377 if (Invalid)
10378 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010379
Eric Christopher4110e132011-07-21 05:34:24 +000010380 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10381 SS, Name, NameLoc, Attr,
10382 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010383 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010384 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010385 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010386 } else {
10387 // The "template<>" header is extraneous.
10388 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10389 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10390 isExplicitSpecialization = true;
10391 }
10392 }
10393
10394 if (Invalid) return 0;
10395
John McCall9a34edb2010-10-19 01:40:49 +000010396 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010397 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010398 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000010399 isAllExplicitSpecializations = false;
10400 break;
10401 }
10402 }
10403
10404 // FIXME: don't ignore attributes.
10405
10406 // If it's explicit specializations all the way down, just forget
10407 // about the template header and build an appropriate non-templated
10408 // friend. TODO: for source fidelity, remember the headers.
10409 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010410 if (SS.isEmpty()) {
10411 bool Owned = false;
10412 bool IsDependent = false;
10413 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10414 Attr, AS_public,
10415 /*ModulePrivateLoc=*/SourceLocation(),
10416 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010417 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010418 /*ScopedEnumUsesClassTag=*/false,
10419 /*UnderlyingType=*/TypeResult());
10420 }
10421
Douglas Gregor2494dd02011-03-01 01:34:45 +000010422 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010423 ElaboratedTypeKeyword Keyword
10424 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010425 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010426 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010427 if (T.isNull())
10428 return 0;
10429
10430 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10431 if (isa<DependentNameType>(T)) {
10432 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010433 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010434 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010435 TL.setNameLoc(NameLoc);
10436 } else {
10437 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010438 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010439 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010440 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10441 }
10442
10443 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10444 TSI, FriendLoc);
10445 Friend->setAccess(AS_public);
10446 CurContext->addDecl(Friend);
10447 return Friend;
10448 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010449
10450 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10451
10452
John McCall9a34edb2010-10-19 01:40:49 +000010453
10454 // Handle the case of a templated-scope friend class. e.g.
10455 // template <class T> class A<T>::B;
10456 // FIXME: we don't support these right now.
10457 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10458 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10459 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10460 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010461 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010462 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010463 TL.setNameLoc(NameLoc);
10464
10465 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10466 TSI, FriendLoc);
10467 Friend->setAccess(AS_public);
10468 Friend->setUnsupportedFriend(true);
10469 CurContext->addDecl(Friend);
10470 return Friend;
10471}
10472
10473
John McCalldd4a3b02009-09-16 22:47:08 +000010474/// Handle a friend type declaration. This works in tandem with
10475/// ActOnTag.
10476///
10477/// Notes on friend class templates:
10478///
10479/// We generally treat friend class declarations as if they were
10480/// declaring a class. So, for example, the elaborated type specifier
10481/// in a friend declaration is required to obey the restrictions of a
10482/// class-head (i.e. no typedefs in the scope chain), template
10483/// parameters are required to match up with simple template-ids, &c.
10484/// However, unlike when declaring a template specialization, it's
10485/// okay to refer to a template specialization without an empty
10486/// template parameter declaration, e.g.
10487/// friend class A<T>::B<unsigned>;
10488/// We permit this as a special case; if there are any template
10489/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010490/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010491Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010492 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010493 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010494
10495 assert(DS.isFriendSpecified());
10496 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10497
John McCalldd4a3b02009-09-16 22:47:08 +000010498 // Try to convert the decl specifier to a type. This works for
10499 // friend templates because ActOnTag never produces a ClassTemplateDecl
10500 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010501 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010502 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10503 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010504 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010505 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010506
Douglas Gregor6ccab972010-12-16 01:14:37 +000010507 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10508 return 0;
10509
John McCalldd4a3b02009-09-16 22:47:08 +000010510 // This is definitely an error in C++98. It's probably meant to
10511 // be forbidden in C++0x, too, but the specification is just
10512 // poorly written.
10513 //
10514 // The problem is with declarations like the following:
10515 // template <T> friend A<T>::foo;
10516 // where deciding whether a class C is a friend or not now hinges
10517 // on whether there exists an instantiation of A that causes
10518 // 'foo' to equal C. There are restrictions on class-heads
10519 // (which we declare (by fiat) elaborated friend declarations to
10520 // be) that makes this tractable.
10521 //
10522 // FIXME: handle "template <> friend class A<T>;", which
10523 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010524 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010525 Diag(Loc, diag::err_tagless_friend_type_template)
10526 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010527 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010528 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010529
John McCall02cace72009-08-28 07:59:38 +000010530 // C++98 [class.friend]p1: A friend of a class is a function
10531 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010532 // This is fixed in DR77, which just barely didn't make the C++03
10533 // deadline. It's also a very silly restriction that seriously
10534 // affects inner classes and which nobody else seems to implement;
10535 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010536 //
10537 // But note that we could warn about it: it's always useless to
10538 // friend one of your own members (it's not, however, worthless to
10539 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010540
John McCalldd4a3b02009-09-16 22:47:08 +000010541 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010542 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010543 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010544 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010545 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010546 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010547 DS.getFriendSpecLoc());
10548 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010549 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010550
10551 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010552 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010553
John McCalldd4a3b02009-09-16 22:47:08 +000010554 D->setAccess(AS_public);
10555 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010556
John McCalld226f652010-08-21 09:40:31 +000010557 return D;
John McCall02cace72009-08-28 07:59:38 +000010558}
10559
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010560Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010561 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010562 const DeclSpec &DS = D.getDeclSpec();
10563
10564 assert(DS.isFriendSpecified());
10565 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10566
10567 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010568 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010569
10570 // C++ [class.friend]p1
10571 // A friend of a class is a function or class....
10572 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010573 // It *doesn't* see through dependent types, which is correct
10574 // according to [temp.arg.type]p3:
10575 // If a declaration acquires a function type through a
10576 // type dependent on a template-parameter and this causes
10577 // a declaration that does not use the syntactic form of a
10578 // function declarator to have a function type, the program
10579 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010580 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010581 Diag(Loc, diag::err_unexpected_friend);
10582
10583 // It might be worthwhile to try to recover by creating an
10584 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010585 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010586 }
10587
10588 // C++ [namespace.memdef]p3
10589 // - If a friend declaration in a non-local class first declares a
10590 // class or function, the friend class or function is a member
10591 // of the innermost enclosing namespace.
10592 // - The name of the friend is not found by simple name lookup
10593 // until a matching declaration is provided in that namespace
10594 // scope (either before or after the class declaration granting
10595 // friendship).
10596 // - If a friend function is called, its name may be found by the
10597 // name lookup that considers functions from namespaces and
10598 // classes associated with the types of the function arguments.
10599 // - When looking for a prior declaration of a class or a function
10600 // declared as a friend, scopes outside the innermost enclosing
10601 // namespace scope are not considered.
10602
John McCall337ec3d2010-10-12 23:13:28 +000010603 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010604 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10605 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010606 assert(Name);
10607
Douglas Gregor6ccab972010-12-16 01:14:37 +000010608 // Check for unexpanded parameter packs.
10609 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10610 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10611 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10612 return 0;
10613
John McCall67d1a672009-08-06 02:15:43 +000010614 // The context we found the declaration in, or in which we should
10615 // create the declaration.
10616 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010617 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010618 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010619 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010620
John McCall337ec3d2010-10-12 23:13:28 +000010621 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010622
John McCall337ec3d2010-10-12 23:13:28 +000010623 // There are four cases here.
10624 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010625 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010626 // there as appropriate.
10627 // Recover from invalid scope qualifiers as if they just weren't there.
10628 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010629 // C++0x [namespace.memdef]p3:
10630 // If the name in a friend declaration is neither qualified nor
10631 // a template-id and the declaration is a function or an
10632 // elaborated-type-specifier, the lookup to determine whether
10633 // the entity has been previously declared shall not consider
10634 // any scopes outside the innermost enclosing namespace.
10635 // C++0x [class.friend]p11:
10636 // If a friend declaration appears in a local class and the name
10637 // specified is an unqualified name, a prior declaration is
10638 // looked up without considering scopes that are outside the
10639 // innermost enclosing non-class scope. For a friend function
10640 // declaration, if there is no prior declaration, the program is
10641 // ill-formed.
10642 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010643 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010644
John McCall29ae6e52010-10-13 05:45:15 +000010645 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010646 DC = CurContext;
10647 while (true) {
10648 // Skip class contexts. If someone can cite chapter and verse
10649 // for this behavior, that would be nice --- it's what GCC and
10650 // EDG do, and it seems like a reasonable intent, but the spec
10651 // really only says that checks for unqualified existing
10652 // declarations should stop at the nearest enclosing namespace,
10653 // not that they should only consider the nearest enclosing
10654 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010655 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010656 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010657
John McCall68263142009-11-18 22:49:29 +000010658 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010659
10660 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010661 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010662 break;
John McCall29ae6e52010-10-13 05:45:15 +000010663
John McCall8a407372010-10-14 22:22:28 +000010664 if (isTemplateId) {
10665 if (isa<TranslationUnitDecl>(DC)) break;
10666 } else {
10667 if (DC->isFileContext()) break;
10668 }
John McCall67d1a672009-08-06 02:15:43 +000010669 DC = DC->getParent();
10670 }
10671
10672 // C++ [class.friend]p1: A friend of a class is a function or
10673 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010674 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010675 // Most C++ 98 compilers do seem to give an error here, so
10676 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010677 if (!Previous.empty() && DC->Equals(CurContext))
10678 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010679 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010680 diag::warn_cxx98_compat_friend_is_member :
10681 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010682
John McCall380aaa42010-10-13 06:22:15 +000010683 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010684
Douglas Gregor883af832011-10-10 01:11:59 +000010685 // C++ [class.friend]p6:
10686 // A function can be defined in a friend declaration of a class if and
10687 // only if the class is a non-local class (9.8), the function name is
10688 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010689 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010690 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10691 }
10692
John McCall337ec3d2010-10-12 23:13:28 +000010693 // - There's a non-dependent scope specifier, in which case we
10694 // compute it and do a previous lookup there for a function
10695 // or function template.
10696 } else if (!SS.getScopeRep()->isDependent()) {
10697 DC = computeDeclContext(SS);
10698 if (!DC) return 0;
10699
10700 if (RequireCompleteDeclContext(SS, DC)) return 0;
10701
10702 LookupQualifiedName(Previous, DC);
10703
10704 // Ignore things found implicitly in the wrong scope.
10705 // TODO: better diagnostics for this case. Suggesting the right
10706 // qualified scope would be nice...
10707 LookupResult::Filter F = Previous.makeFilter();
10708 while (F.hasNext()) {
10709 NamedDecl *D = F.next();
10710 if (!DC->InEnclosingNamespaceSetOf(
10711 D->getDeclContext()->getRedeclContext()))
10712 F.erase();
10713 }
10714 F.done();
10715
10716 if (Previous.empty()) {
10717 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010718 Diag(Loc, diag::err_qualified_friend_not_found)
10719 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010720 return 0;
10721 }
10722
10723 // C++ [class.friend]p1: A friend of a class is a function or
10724 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010725 if (DC->Equals(CurContext))
10726 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010727 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010728 diag::warn_cxx98_compat_friend_is_member :
10729 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010730
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010731 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010732 // C++ [class.friend]p6:
10733 // A function can be defined in a friend declaration of a class if and
10734 // only if the class is a non-local class (9.8), the function name is
10735 // unqualified, and the function has namespace scope.
10736 SemaDiagnosticBuilder DB
10737 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10738
10739 DB << SS.getScopeRep();
10740 if (DC->isFileContext())
10741 DB << FixItHint::CreateRemoval(SS.getRange());
10742 SS.clear();
10743 }
John McCall337ec3d2010-10-12 23:13:28 +000010744
10745 // - There's a scope specifier that does not match any template
10746 // parameter lists, in which case we use some arbitrary context,
10747 // create a method or method template, and wait for instantiation.
10748 // - There's a scope specifier that does match some template
10749 // parameter lists, which we don't handle right now.
10750 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010751 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010752 // C++ [class.friend]p6:
10753 // A function can be defined in a friend declaration of a class if and
10754 // only if the class is a non-local class (9.8), the function name is
10755 // unqualified, and the function has namespace scope.
10756 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10757 << SS.getScopeRep();
10758 }
10759
John McCall337ec3d2010-10-12 23:13:28 +000010760 DC = CurContext;
10761 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010762 }
Douglas Gregor883af832011-10-10 01:11:59 +000010763
John McCall29ae6e52010-10-13 05:45:15 +000010764 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010765 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010766 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10767 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10768 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010769 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010770 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10771 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010772 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010773 }
John McCall67d1a672009-08-06 02:15:43 +000010774 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010775
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010776 // FIXME: This is an egregious hack to cope with cases where the scope stack
10777 // does not contain the declaration context, i.e., in an out-of-line
10778 // definition of a class.
10779 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10780 if (!DCScope) {
10781 FakeDCScope.setEntity(DC);
10782 DCScope = &FakeDCScope;
10783 }
10784
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010785 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010786 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010787 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010788 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010789
Douglas Gregor182ddf02009-09-28 00:08:27 +000010790 assert(ND->getDeclContext() == DC);
10791 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010792
John McCallab88d972009-08-31 22:39:49 +000010793 // Add the function declaration to the appropriate lookup tables,
10794 // adjusting the redeclarations list as necessary. We don't
10795 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010796 //
John McCallab88d972009-08-31 22:39:49 +000010797 // Also update the scope-based lookup if the target context's
10798 // lookup context is in lexical scope.
10799 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010800 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010801 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010802 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010803 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010804 }
John McCall02cace72009-08-28 07:59:38 +000010805
10806 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010807 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010808 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010809 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010810 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010811
John McCall1f2e1a92012-08-10 03:15:35 +000010812 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010813 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010814 } else {
10815 if (DC->isRecord()) CheckFriendAccess(ND);
10816
John McCall6102ca12010-10-16 06:59:13 +000010817 FunctionDecl *FD;
10818 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10819 FD = FTD->getTemplatedDecl();
10820 else
10821 FD = cast<FunctionDecl>(ND);
10822
10823 // Mark templated-scope function declarations as unsupported.
10824 if (FD->getNumTemplateParameterLists())
10825 FrD->setUnsupportedFriend(true);
10826 }
John McCall337ec3d2010-10-12 23:13:28 +000010827
John McCalld226f652010-08-21 09:40:31 +000010828 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010829}
10830
John McCalld226f652010-08-21 09:40:31 +000010831void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10832 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010833
Sebastian Redl50de12f2009-03-24 22:27:57 +000010834 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10835 if (!Fn) {
10836 Diag(DelLoc, diag::err_deleted_non_function);
10837 return;
10838 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010839 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010840 // Don't consider the implicit declaration we generate for explicit
10841 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010842 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10843 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010844 Diag(DelLoc, diag::err_deleted_decl_not_first);
10845 Diag(Prev->getLocation(), diag::note_previous_declaration);
10846 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010847 // If the declaration wasn't the first, we delete the function anyway for
10848 // recovery.
10849 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010850 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010851}
Sebastian Redl13e88542009-04-27 21:33:24 +000010852
Sean Hunte4246a62011-05-12 06:15:49 +000010853void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10854 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10855
10856 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010857 if (MD->getParent()->isDependentType()) {
10858 MD->setDefaulted();
10859 MD->setExplicitlyDefaulted();
10860 return;
10861 }
10862
Sean Hunte4246a62011-05-12 06:15:49 +000010863 CXXSpecialMember Member = getSpecialMember(MD);
10864 if (Member == CXXInvalid) {
10865 Diag(DefaultLoc, diag::err_default_special_members);
10866 return;
10867 }
10868
10869 MD->setDefaulted();
10870 MD->setExplicitlyDefaulted();
10871
Sean Huntcd10dec2011-05-23 23:14:04 +000010872 // If this definition appears within the record, do the checking when
10873 // the record is complete.
10874 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010875 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010876 // Find the uninstantiated declaration that actually had the '= default'
10877 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010878 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010879
10880 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010881 return;
10882
Richard Smithb9d0b762012-07-27 04:22:15 +000010883 CheckExplicitlyDefaultedSpecialMember(MD);
10884
Sean Hunte4246a62011-05-12 06:15:49 +000010885 switch (Member) {
10886 case CXXDefaultConstructor: {
10887 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010888 if (!CD->isInvalidDecl())
10889 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10890 break;
10891 }
10892
10893 case CXXCopyConstructor: {
10894 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010895 if (!CD->isInvalidDecl())
10896 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010897 break;
10898 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010899
Sean Hunt2b188082011-05-14 05:23:28 +000010900 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010901 if (!MD->isInvalidDecl())
10902 DefineImplicitCopyAssignment(DefaultLoc, MD);
10903 break;
10904 }
10905
Sean Huntcb45a0f2011-05-12 22:46:25 +000010906 case CXXDestructor: {
10907 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010908 if (!DD->isInvalidDecl())
10909 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010910 break;
10911 }
10912
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010913 case CXXMoveConstructor: {
10914 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010915 if (!CD->isInvalidDecl())
10916 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010917 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010918 }
Sean Hunt82713172011-05-25 23:16:36 +000010919
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010920 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010921 if (!MD->isInvalidDecl())
10922 DefineImplicitMoveAssignment(DefaultLoc, MD);
10923 break;
10924 }
10925
10926 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010927 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010928 }
10929 } else {
10930 Diag(DefaultLoc, diag::err_default_special_members);
10931 }
10932}
10933
Sebastian Redl13e88542009-04-27 21:33:24 +000010934static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010935 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010936 Stmt *SubStmt = *CI;
10937 if (!SubStmt)
10938 continue;
10939 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010940 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010941 diag::err_return_in_constructor_handler);
10942 if (!isa<Expr>(SubStmt))
10943 SearchForReturnInStmt(Self, SubStmt);
10944 }
10945}
10946
10947void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10948 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10949 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10950 SearchForReturnInStmt(*this, Handler);
10951 }
10952}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010953
Aaron Ballmanfff32482012-12-09 17:45:41 +000010954bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
10955 const CXXMethodDecl *Old) {
10956 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
10957 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
10958
10959 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
10960
10961 // If the calling conventions match, everything is fine
10962 if (NewCC == OldCC)
10963 return false;
10964
10965 // If either of the calling conventions are set to "default", we need to pick
10966 // something more sensible based on the target. This supports code where the
10967 // one method explicitly sets thiscall, and another has no explicit calling
10968 // convention.
10969 CallingConv Default =
10970 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
10971 if (NewCC == CC_Default)
10972 NewCC = Default;
10973 if (OldCC == CC_Default)
10974 OldCC = Default;
10975
10976 // If the calling conventions still don't match, then report the error
10977 if (NewCC != OldCC) {
10978 Diag(New->getLocation(),
10979 diag::err_conflicting_overriding_cc_attributes)
10980 << New->getDeclName() << New->getType() << Old->getType();
10981 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10982 return true;
10983 }
10984
10985 return false;
10986}
10987
Mike Stump1eb44332009-09-09 15:08:12 +000010988bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010989 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010990 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10991 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010992
Chandler Carruth73857792010-02-15 11:53:20 +000010993 if (Context.hasSameType(NewTy, OldTy) ||
10994 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010995 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010996
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010997 // Check if the return types are covariant
10998 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010999
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011000 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011001 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11002 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011003 NewClassTy = NewPT->getPointeeType();
11004 OldClassTy = OldPT->getPointeeType();
11005 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011006 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11007 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11008 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11009 NewClassTy = NewRT->getPointeeType();
11010 OldClassTy = OldRT->getPointeeType();
11011 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011012 }
11013 }
Mike Stump1eb44332009-09-09 15:08:12 +000011014
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011015 // The return types aren't either both pointers or references to a class type.
11016 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011017 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011018 diag::err_different_return_type_for_overriding_virtual_function)
11019 << New->getDeclName() << NewTy << OldTy;
11020 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011021
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011022 return true;
11023 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011024
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011025 // C++ [class.virtual]p6:
11026 // If the return type of D::f differs from the return type of B::f, the
11027 // class type in the return type of D::f shall be complete at the point of
11028 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011029 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11030 if (!RT->isBeingDefined() &&
11031 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011032 diag::err_covariant_return_incomplete,
11033 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011034 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011035 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011036
Douglas Gregora4923eb2009-11-16 21:35:15 +000011037 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011038 // Check if the new class derives from the old class.
11039 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11040 Diag(New->getLocation(),
11041 diag::err_covariant_return_not_derived)
11042 << New->getDeclName() << NewTy << OldTy;
11043 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11044 return true;
11045 }
Mike Stump1eb44332009-09-09 15:08:12 +000011046
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011047 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011048 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011049 diag::err_covariant_return_inaccessible_base,
11050 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11051 // FIXME: Should this point to the return type?
11052 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011053 // FIXME: this note won't trigger for delayed access control
11054 // diagnostics, and it's impossible to get an undelayed error
11055 // here from access control during the original parse because
11056 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011057 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11058 return true;
11059 }
11060 }
Mike Stump1eb44332009-09-09 15:08:12 +000011061
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011062 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011063 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011064 Diag(New->getLocation(),
11065 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011066 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011067 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11068 return true;
11069 };
Mike Stump1eb44332009-09-09 15:08:12 +000011070
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011071
11072 // The new class type must have the same or less qualifiers as the old type.
11073 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11074 Diag(New->getLocation(),
11075 diag::err_covariant_return_type_class_type_more_qualified)
11076 << New->getDeclName() << NewTy << OldTy;
11077 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11078 return true;
11079 };
Mike Stump1eb44332009-09-09 15:08:12 +000011080
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011081 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011082}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011083
Douglas Gregor4ba31362009-12-01 17:24:26 +000011084/// \brief Mark the given method pure.
11085///
11086/// \param Method the method to be marked pure.
11087///
11088/// \param InitRange the source range that covers the "0" initializer.
11089bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011090 SourceLocation EndLoc = InitRange.getEnd();
11091 if (EndLoc.isValid())
11092 Method->setRangeEnd(EndLoc);
11093
Douglas Gregor4ba31362009-12-01 17:24:26 +000011094 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11095 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011096 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011097 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011098
11099 if (!Method->isInvalidDecl())
11100 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11101 << Method->getDeclName() << InitRange;
11102 return true;
11103}
11104
Douglas Gregor552e2992012-02-21 02:22:07 +000011105/// \brief Determine whether the given declaration is a static data member.
11106static bool isStaticDataMember(Decl *D) {
11107 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11108 if (!Var)
11109 return false;
11110
11111 return Var->isStaticDataMember();
11112}
John McCall731ad842009-12-19 09:28:58 +000011113/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11114/// an initializer for the out-of-line declaration 'Dcl'. The scope
11115/// is a fresh scope pushed for just this purpose.
11116///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011117/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11118/// static data member of class X, names should be looked up in the scope of
11119/// class X.
John McCalld226f652010-08-21 09:40:31 +000011120void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011121 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011122 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011123
John McCall731ad842009-12-19 09:28:58 +000011124 // We should only get called for declarations with scope specifiers, like:
11125 // int foo::bar;
11126 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011127 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011128
11129 // If we are parsing the initializer for a static data member, push a
11130 // new expression evaluation context that is associated with this static
11131 // data member.
11132 if (isStaticDataMember(D))
11133 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011134}
11135
11136/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011137/// initializer for the out-of-line declaration 'D'.
11138void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011139 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011140 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011141
Douglas Gregor552e2992012-02-21 02:22:07 +000011142 if (isStaticDataMember(D))
11143 PopExpressionEvaluationContext();
11144
John McCall731ad842009-12-19 09:28:58 +000011145 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011146 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011147}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011148
11149/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11150/// C++ if/switch/while/for statement.
11151/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011152DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011153 // C++ 6.4p2:
11154 // The declarator shall not specify a function or an array.
11155 // The type-specifier-seq shall not contain typedef and shall not declare a
11156 // new class or enumeration.
11157 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11158 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011159
11160 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011161 if (!Dcl)
11162 return true;
11163
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011164 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11165 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011166 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011167 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011168 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011169
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011170 return Dcl;
11171}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011172
Douglas Gregordfe65432011-07-28 19:11:31 +000011173void Sema::LoadExternalVTableUses() {
11174 if (!ExternalSource)
11175 return;
11176
11177 SmallVector<ExternalVTableUse, 4> VTables;
11178 ExternalSource->ReadUsedVTables(VTables);
11179 SmallVector<VTableUse, 4> NewUses;
11180 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11181 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11182 = VTablesUsed.find(VTables[I].Record);
11183 // Even if a definition wasn't required before, it may be required now.
11184 if (Pos != VTablesUsed.end()) {
11185 if (!Pos->second && VTables[I].DefinitionRequired)
11186 Pos->second = true;
11187 continue;
11188 }
11189
11190 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11191 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11192 }
11193
11194 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11195}
11196
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011197void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11198 bool DefinitionRequired) {
11199 // Ignore any vtable uses in unevaluated operands or for classes that do
11200 // not have a vtable.
11201 if (!Class->isDynamicClass() || Class->isDependentContext() ||
11202 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000011203 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011204 return;
11205
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011206 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011207 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011208 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11209 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11210 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11211 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011212 // If we already had an entry, check to see if we are promoting this vtable
11213 // to required a definition. If so, we need to reappend to the VTableUses
11214 // list, since we may have already processed the first entry.
11215 if (DefinitionRequired && !Pos.first->second) {
11216 Pos.first->second = true;
11217 } else {
11218 // Otherwise, we can early exit.
11219 return;
11220 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011221 }
11222
11223 // Local classes need to have their virtual members marked
11224 // immediately. For all other classes, we mark their virtual members
11225 // at the end of the translation unit.
11226 if (Class->isLocalClass())
11227 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011228 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011229 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011230}
11231
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011232bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011233 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011234 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011235 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011236
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011237 // Note: The VTableUses vector could grow as a result of marking
11238 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011239 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011240 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011241 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011242 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011243 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011244 if (!Class)
11245 continue;
11246
11247 SourceLocation Loc = VTableUses[I].second;
11248
Richard Smithb9d0b762012-07-27 04:22:15 +000011249 bool DefineVTable = true;
11250
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011251 // If this class has a key function, but that key function is
11252 // defined in another translation unit, we don't need to emit the
11253 // vtable even though we're using it.
11254 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011255 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011256 switch (KeyFunction->getTemplateSpecializationKind()) {
11257 case TSK_Undeclared:
11258 case TSK_ExplicitSpecialization:
11259 case TSK_ExplicitInstantiationDeclaration:
11260 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011261 DefineVTable = false;
11262 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011263
11264 case TSK_ExplicitInstantiationDefinition:
11265 case TSK_ImplicitInstantiation:
11266 // We will be instantiating the key function.
11267 break;
11268 }
11269 } else if (!KeyFunction) {
11270 // If we have a class with no key function that is the subject
11271 // of an explicit instantiation declaration, suppress the
11272 // vtable; it will live with the explicit instantiation
11273 // definition.
11274 bool IsExplicitInstantiationDeclaration
11275 = Class->getTemplateSpecializationKind()
11276 == TSK_ExplicitInstantiationDeclaration;
11277 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11278 REnd = Class->redecls_end();
11279 R != REnd; ++R) {
11280 TemplateSpecializationKind TSK
11281 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11282 if (TSK == TSK_ExplicitInstantiationDeclaration)
11283 IsExplicitInstantiationDeclaration = true;
11284 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11285 IsExplicitInstantiationDeclaration = false;
11286 break;
11287 }
11288 }
11289
11290 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011291 DefineVTable = false;
11292 }
11293
11294 // The exception specifications for all virtual members may be needed even
11295 // if we are not providing an authoritative form of the vtable in this TU.
11296 // We may choose to emit it available_externally anyway.
11297 if (!DefineVTable) {
11298 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11299 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011300 }
11301
11302 // Mark all of the virtual members of this class as referenced, so
11303 // that we can build a vtable. Then, tell the AST consumer that a
11304 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011305 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011306 MarkVirtualMembersReferenced(Loc, Class);
11307 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11308 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11309
11310 // Optionally warn if we're emitting a weak vtable.
11311 if (Class->getLinkage() == ExternalLinkage &&
11312 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011313 const FunctionDecl *KeyFunctionDef = 0;
11314 if (!KeyFunction ||
11315 (KeyFunction->hasBody(KeyFunctionDef) &&
11316 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000011317 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11318 TSK_ExplicitInstantiationDefinition
11319 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11320 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011321 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011322 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011323 VTableUses.clear();
11324
Douglas Gregor78844032011-04-22 22:25:37 +000011325 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011326}
Anders Carlssond6a637f2009-12-07 08:24:59 +000011327
Richard Smithb9d0b762012-07-27 04:22:15 +000011328void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11329 const CXXRecordDecl *RD) {
11330 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11331 E = RD->method_end(); I != E; ++I)
11332 if ((*I)->isVirtual() && !(*I)->isPure())
11333 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11334}
11335
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011336void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11337 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000011338 // Mark all functions which will appear in RD's vtable as used.
11339 CXXFinalOverriderMap FinalOverriders;
11340 RD->getFinalOverriders(FinalOverriders);
11341 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11342 E = FinalOverriders.end();
11343 I != E; ++I) {
11344 for (OverridingMethods::const_iterator OI = I->second.begin(),
11345 OE = I->second.end();
11346 OI != OE; ++OI) {
11347 assert(OI->second.size() > 0 && "no final overrider");
11348 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000011349
Richard Smithff817f72012-07-07 06:59:51 +000011350 // C++ [basic.def.odr]p2:
11351 // [...] A virtual member function is used if it is not pure. [...]
11352 if (!Overrider->isPure())
11353 MarkFunctionReferenced(Loc, Overrider);
11354 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011355 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011356
11357 // Only classes that have virtual bases need a VTT.
11358 if (RD->getNumVBases() == 0)
11359 return;
11360
11361 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11362 e = RD->bases_end(); i != e; ++i) {
11363 const CXXRecordDecl *Base =
11364 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000011365 if (Base->getNumVBases() == 0)
11366 continue;
11367 MarkVirtualMembersReferenced(Loc, Base);
11368 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000011369}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011370
11371/// SetIvarInitializers - This routine builds initialization ASTs for the
11372/// Objective-C implementation whose ivars need be initialized.
11373void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000011374 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011375 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000011376 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000011377 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011378 CollectIvarsToConstructOrDestruct(OID, ivars);
11379 if (ivars.empty())
11380 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011381 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011382 for (unsigned i = 0; i < ivars.size(); i++) {
11383 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011384 if (Field->isInvalidDecl())
11385 continue;
11386
Sean Huntcbb67482011-01-08 20:30:50 +000011387 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011388 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11389 InitializationKind InitKind =
11390 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11391
11392 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000011393 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000011394 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000011395 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011396 // Note, MemberInit could actually come back empty if no initialization
11397 // is required (e.g., because it would call a trivial default constructor)
11398 if (!MemberInit.get() || MemberInit.isInvalid())
11399 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000011400
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011401 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000011402 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11403 SourceLocation(),
11404 MemberInit.takeAs<Expr>(),
11405 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011406 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011407
11408 // Be sure that the destructor is accessible and is marked as referenced.
11409 if (const RecordType *RecordTy
11410 = Context.getBaseElementType(Field->getType())
11411 ->getAs<RecordType>()) {
11412 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000011413 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011414 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000011415 CheckDestructorAccess(Field->getLocation(), Destructor,
11416 PDiag(diag::err_access_dtor_ivar)
11417 << Context.getBaseElementType(Field->getType()));
11418 }
11419 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000011420 }
11421 ObjCImplementation->setIvarInitializers(Context,
11422 AllToInit.data(), AllToInit.size());
11423 }
11424}
Sean Huntfe57eef2011-05-04 05:57:24 +000011425
Sean Huntebcbe1d2011-05-04 23:29:54 +000011426static
11427void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11428 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11429 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11430 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11431 Sema &S) {
11432 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11433 CE = Current.end();
11434 if (Ctor->isInvalidDecl())
11435 return;
11436
Richard Smitha8eaf002012-08-23 06:16:52 +000011437 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11438
11439 // Target may not be determinable yet, for instance if this is a dependent
11440 // call in an uninstantiated template.
11441 if (Target) {
11442 const FunctionDecl *FNTarget = 0;
11443 (void)Target->hasBody(FNTarget);
11444 Target = const_cast<CXXConstructorDecl*>(
11445 cast_or_null<CXXConstructorDecl>(FNTarget));
11446 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011447
11448 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11449 // Avoid dereferencing a null pointer here.
11450 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11451
11452 if (!Current.insert(Canonical))
11453 return;
11454
11455 // We know that beyond here, we aren't chaining into a cycle.
11456 if (!Target || !Target->isDelegatingConstructor() ||
11457 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11458 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11459 Valid.insert(*CI);
11460 Current.clear();
11461 // We've hit a cycle.
11462 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11463 Current.count(TCanonical)) {
11464 // If we haven't diagnosed this cycle yet, do so now.
11465 if (!Invalid.count(TCanonical)) {
11466 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011467 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011468 << Ctor;
11469
Richard Smitha8eaf002012-08-23 06:16:52 +000011470 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011471 if (TCanonical != Canonical)
11472 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11473
11474 CXXConstructorDecl *C = Target;
11475 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011476 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011477 (void)C->getTargetConstructor()->hasBody(FNTarget);
11478 assert(FNTarget && "Ctor cycle through bodiless function");
11479
Richard Smitha8eaf002012-08-23 06:16:52 +000011480 C = const_cast<CXXConstructorDecl*>(
11481 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011482 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11483 }
11484 }
11485
11486 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11487 Invalid.insert(*CI);
11488 Current.clear();
11489 } else {
11490 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11491 }
11492}
11493
11494
Sean Huntfe57eef2011-05-04 05:57:24 +000011495void Sema::CheckDelegatingCtorCycles() {
11496 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11497
Sean Huntebcbe1d2011-05-04 23:29:54 +000011498 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11499 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011500
Douglas Gregor0129b562011-07-27 21:57:17 +000011501 for (DelegatingCtorDeclsType::iterator
11502 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011503 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011504 I != E; ++I)
11505 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011506
11507 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11508 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011509}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011510
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011511namespace {
11512 /// \brief AST visitor that finds references to the 'this' expression.
11513 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11514 Sema &S;
11515
11516 public:
11517 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11518
11519 bool VisitCXXThisExpr(CXXThisExpr *E) {
11520 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11521 << E->isImplicit();
11522 return false;
11523 }
11524 };
11525}
11526
11527bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11528 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11529 if (!TSInfo)
11530 return false;
11531
11532 TypeLoc TL = TSInfo->getTypeLoc();
11533 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11534 if (!ProtoTL)
11535 return false;
11536
11537 // C++11 [expr.prim.general]p3:
11538 // [The expression this] shall not appear before the optional
11539 // cv-qualifier-seq and it shall not appear within the declaration of a
11540 // static member function (although its type and value category are defined
11541 // within a static member function as they are within a non-static member
11542 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011543 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011544 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11545 FindCXXThisExpr Finder(*this);
11546
11547 // If the return type came after the cv-qualifier-seq, check it now.
11548 if (Proto->hasTrailingReturn() &&
11549 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11550 return true;
11551
11552 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011553 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11554 return true;
11555
11556 return checkThisInStaticMemberFunctionAttributes(Method);
11557}
11558
11559bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11560 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11561 if (!TSInfo)
11562 return false;
11563
11564 TypeLoc TL = TSInfo->getTypeLoc();
11565 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11566 if (!ProtoTL)
11567 return false;
11568
11569 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11570 FindCXXThisExpr Finder(*this);
11571
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011572 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011573 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011574 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011575 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011576 case EST_DynamicNone:
11577 case EST_MSAny:
11578 case EST_None:
11579 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011580
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011581 case EST_ComputedNoexcept:
11582 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11583 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011584
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011585 case EST_Dynamic:
11586 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011587 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011588 E != EEnd; ++E) {
11589 if (!Finder.TraverseType(*E))
11590 return true;
11591 }
11592 break;
11593 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011594
11595 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011596}
11597
11598bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11599 FindCXXThisExpr Finder(*this);
11600
11601 // Check attributes.
11602 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11603 A != AEnd; ++A) {
11604 // FIXME: This should be emitted by tblgen.
11605 Expr *Arg = 0;
11606 ArrayRef<Expr *> Args;
11607 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11608 Arg = G->getArg();
11609 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11610 Arg = G->getArg();
11611 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11612 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11613 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11614 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11615 else if (ExclusiveLockFunctionAttr *ELF
11616 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11617 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11618 else if (SharedLockFunctionAttr *SLF
11619 = dyn_cast<SharedLockFunctionAttr>(*A))
11620 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11621 else if (ExclusiveTrylockFunctionAttr *ETLF
11622 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11623 Arg = ETLF->getSuccessValue();
11624 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11625 } else if (SharedTrylockFunctionAttr *STLF
11626 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11627 Arg = STLF->getSuccessValue();
11628 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11629 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11630 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11631 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11632 Arg = LR->getArg();
11633 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11634 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11635 else if (ExclusiveLocksRequiredAttr *ELR
11636 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11637 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11638 else if (SharedLocksRequiredAttr *SLR
11639 = dyn_cast<SharedLocksRequiredAttr>(*A))
11640 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11641
11642 if (Arg && !Finder.TraverseStmt(Arg))
11643 return true;
11644
11645 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11646 if (!Finder.TraverseStmt(Args[I]))
11647 return true;
11648 }
11649 }
11650
11651 return false;
11652}
11653
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011654void
11655Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11656 ArrayRef<ParsedType> DynamicExceptions,
11657 ArrayRef<SourceRange> DynamicExceptionRanges,
11658 Expr *NoexceptExpr,
11659 llvm::SmallVectorImpl<QualType> &Exceptions,
11660 FunctionProtoType::ExtProtoInfo &EPI) {
11661 Exceptions.clear();
11662 EPI.ExceptionSpecType = EST;
11663 if (EST == EST_Dynamic) {
11664 Exceptions.reserve(DynamicExceptions.size());
11665 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11666 // FIXME: Preserve type source info.
11667 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11668
11669 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11670 collectUnexpandedParameterPacks(ET, Unexpanded);
11671 if (!Unexpanded.empty()) {
11672 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11673 UPPC_ExceptionType,
11674 Unexpanded);
11675 continue;
11676 }
11677
11678 // Check that the type is valid for an exception spec, and
11679 // drop it if not.
11680 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11681 Exceptions.push_back(ET);
11682 }
11683 EPI.NumExceptions = Exceptions.size();
11684 EPI.Exceptions = Exceptions.data();
11685 return;
11686 }
11687
11688 if (EST == EST_ComputedNoexcept) {
11689 // If an error occurred, there's no expression here.
11690 if (NoexceptExpr) {
11691 assert((NoexceptExpr->isTypeDependent() ||
11692 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11693 Context.BoolTy) &&
11694 "Parser should have made sure that the expression is boolean");
11695 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11696 EPI.ExceptionSpecType = EST_BasicNoexcept;
11697 return;
11698 }
11699
11700 if (!NoexceptExpr->isValueDependent())
11701 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011702 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011703 /*AllowFold*/ false).take();
11704 EPI.NoexceptExpr = NoexceptExpr;
11705 }
11706 return;
11707 }
11708}
11709
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011710/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11711Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11712 // Implicitly declared functions (e.g. copy constructors) are
11713 // __host__ __device__
11714 if (D->isImplicit())
11715 return CFT_HostDevice;
11716
11717 if (D->hasAttr<CUDAGlobalAttr>())
11718 return CFT_Global;
11719
11720 if (D->hasAttr<CUDADeviceAttr>()) {
11721 if (D->hasAttr<CUDAHostAttr>())
11722 return CFT_HostDevice;
11723 else
11724 return CFT_Device;
11725 }
11726
11727 return CFT_Host;
11728}
11729
11730bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11731 CUDAFunctionTarget CalleeTarget) {
11732 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11733 // Callable from the device only."
11734 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11735 return true;
11736
11737 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11738 // Callable from the host only."
11739 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11740 // Callable from the host only."
11741 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11742 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11743 return true;
11744
11745 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11746 return true;
11747
11748 return false;
11749}